diff --git a/.agent-steering-domains.md b/.agent-steering-domains.md new file mode 100644 index 0000000000000..688dad8233ea3 --- /dev/null +++ b/.agent-steering-domains.md @@ -0,0 +1,359 @@ +# Project domain steering (domains: postgresql) +# Generated by project-steering (local, gitignored). + +## postgresql-workflow.md +# PostgreSQL Workflow + +This file is required reading for any PostgreSQL-related task — patches, internals questions, performance investigation, design discussion, or extension development. PostgreSQL is the user's primary work domain (≈22.8k topic mentions in chat history); applying this consistently saves substantial time per task. + +## Rule of First Resort: Use `postgresq` MCP, Not Manual Search + +The `postgresq` MCP server (https://pg.ddx.io/mcp) indexes the entire pgsql-hackers archive (76k+ messages) plus the upstream `master` git history with author/date/thread metadata. Before reaching for `grep`, `rg`, web search, or asking the user for context: + +1. **Patch design questions** ("why does X work this way", "has Y been proposed before") → `postgresq` thread search. +2. **Symbol lookup** (`BufferDesc`, `XLogInsert`, executor node X) → `postgresq` symbol+history search. +3. **Reviewer objections in this area** ("what did the community say about lockless approaches") → `postgresq` thread search filtered by reviewer name or subject pattern. +4. **Cross-reference commit ↔ thread** ("what discussion led to commit `abc1234`") → `postgresq` git→list correlation. +5. **Community coding conventions** for a specific area → `postgresq` codified in conventions corpus. + +If `postgresq` returns insufficient results, *then* fall back to web search or manual grep. Don't skip the MCP because "it might not have it" — it usually does. + +**Do NOT use `postgresq` for:** + +- Running SQL queries (use a regular Postgres client) +- Reading the user's own extensions (`ra`, `pg_dyn`, etc.) — those are local code, use file Read/git MCP +- Current end-user PostgreSQL documentation (fetch https://www.postgresql.org/docs/ directly) +- GitHub PRs/issues against forks/extensions (use `github` MCP) + +## Patch Series Workflow + +When the user asks for a patch or patch series targeting upstream PostgreSQL or one of their extensions: + +> **The deliverable is files on disk, never a sent message.** Agents **NEVER** send anything to pgsql-hackers (or any list, or any person): no `git send-email`, no SMTP, no mail client, no "test" copy. That holds even after the user approves the patch and the cover letter. Finish with `git format-patch` output plus a plain-text cover letter, recipients and `In-Reply-To`, and say "ready for you to send". The user sends. See `must-rules.md` § "NEVER send email" (an agent sent a patch to -hackers on 2026-10-07; it can't be recalled). + +1. **Phase 0 — Context gathering** (before touching code) + - `postgresq` search for prior threads on the topic. Read the top 3–5. + - `postgresq` git history for the area being modified — understand recent churn. + - If the user already has a draft or referenced a commit, `postgresq` it for the original design discussion. + +2. **Phase 1 — Design** + - State the design intent in 2–4 sentences. Surface known trade-offs before writing code. + - If a similar design was already reviewed and rejected on -hackers, surface the rejection reason and discuss whether it still applies. + +3. **Phase 2 — Implementation** + - Follow PostgreSQL coding conventions: 4-space indent, `PG_TRY/CATCH` for resource cleanup, `ereport()` for errors with `errcode()`, `palloc` not `malloc`, minimal use of `bool`-returning functions. + - One logical change per commit. Patch series order: prep/refactor commits first, behavior-changing commits last. + - If you're adding a `GUC`, it goes in `guc_tables.c` and `postgresql.conf.sample` together. + +4. **Phase 3 — Testing** + - Build with `--enable-cassert --enable-debug --enable-tap-tests`. + - Run the relevant test suite: `make check`, `make installcheck`, the relevant `src/test/regress` group, or the appropriate TAP suite. + - For buffer manager / WAL / recovery changes: also run `pg_amcheck` or the relevant `pg_isolated` tests. + +5. **Phase 4 — Submission** + - Commit message: present-tense imperative, ≤72 char subject, body explains the *why* not the *what*. Include reproducer if fixing a bug. + - For -hackers submission: cover letter explains the patch series, lists open questions, references prior threads (`postgresq` link or `[1]` style). + - **Attachments for the list** (the user sends; see the NEVER-send rule above): + - **CF-bot opt-out**: any attached file the commitfest bot should IGNORE (not try to apply/build/test -- e.g. a reproducer script, a log, a design doc, a non-patch) must have **`.nocfbot`** appended to its filename (e.g. `repro.sql.nocfbot`, `design-notes.md.nocfbot`). The bot only consumes files it is meant to apply. + - **1 MB moderation threshold**: if the attachment set plus the email body exceeds **1 MB**, the message is held for moderation before it reaches the list (a delay). To stay under it, **compress the attachment set** with tar + gzip into a single `-.tgz` (or `.tar.gz`), e.g. `undo-v7.tgz` -- `tar czf undo-v7.tgz *.patch` (or the specific files). A single compressed tarball also keeps a patch series together and is friendlier for the CF bot than many loose files. + - For local PR against a fork: use the `github` MCP to open with full context. + +## Performance Investigation Workflow + +1. **First**: ask the user for the workload shape (read-heavy / write-heavy / mixed, working set size, isolation level). Don't guess. +2. **Reproduce**: a minimal `pgbench` or `psql` script that exhibits the issue. Time it. Get a baseline. +3. **Profile**: `perf record -p ` for CPU; `bpftrace`/`bcc-tools` for syscalls/IO; `pg_stat_statements` for query-level. Use the `pg-numa-benchmark` skill (see `~/.kiro/skills/pg-numa-benchmark/`) when on bare-metal hardware. +4. **Hypothesize then test**: change one variable at a time. Don't combine config changes. + +### A/B feature benchmarking (vs `master`) + +When measuring a feature branch's impact, always compare against its **merge-base with `origin/master`**, not against an arbitrary master tip -- that isolates the feature from unrelated upstream churn. Build both variants from the same checkout (one `build.sh`-style script that `git checkout --detach`es each rev into its own prefix), refuse to run with a dirty tree, and emit machine-readable results (CSV) plus a human summary (Markdown) under a timestamped results dir so runs are comparable over time. Record TPS, latency, WAL volume, the relevant per-feature counters (e.g. HOT vs HOT-indexed vs non-HOT update counts), index/table bloat before/after, and peak CPU/RSS. Re-run the same harness after every rebase so regressions are caught against current master. + +## Concrete Anti-Patterns to Avoid + +These have appeared repeatedly in chat history and should not recur: + +- **Reaching for `grep` against pgsql-hackers archives** — always use `postgresq` first. +- **Asking the user "what did the community say about X"** — `postgresq` knows; check it first. +- **Implementing a feature without checking prior art** — half the time someone already proposed it; understanding why it stalled saves the same dead-end. +- **Manually reading commit logs to find motivation** — `postgresq` correlates commits to their list threads. +- **Mixing patch series ordering** (behavior + refactor in one commit) — split. +- **Skipping the cassert build** — undefined-behavior bugs only show under cassert. + +## When in Doubt + +Ask `postgresq` first. If the response is empty or unhelpful, only then fall back to other tools. Document the gap so the corpus can be improved. + +## Patch-Series Discipline (hard-won on the HOT-indexed / `tepid` work; recurring) + +These are explicit, repeated requirements for any series aimed at -hackers. Treat them as acceptance criteria, not aspirations. + +- **Every commit builds clean on its own**, with `-Werror` and `--enable-cassert --enable-injection-points`. Zero warnings. A reviewer will `git rebase --exec 'make'` the series; any commit that fails is disqualifying. +- **Every commit passes `make check` on its own** (not just the tip). Bundle each test with the commit that introduces the feature it exercises; later commits may amend that test. A commit that leaves a regress test red is not submittable even if the tip is green. +- **Foundational changes precede their consumers, and must keep every existing consumer correct *at that commit*.** Do not land an infrastructure change in an early patch that breaks a still-upstream consumer until a later patch repairs it. If a change is only correct once its new consumer exists, put the change *in the commit with the consumer*. (Concrete miss: broadening a relcache attr bitmap in the infra patch silently broke heap_update's still-upstream HOT decision for BRIN until the write-path patch rewired it. Fix was to move the one broadening line into the write-path commit.) +- **Minimize churn between commits.** Do not add code in one commit and delete it in another within the same series. If you catch yourself doing that, the change belongs in a different commit. +- **Typedefs go in `src/tools/pgindent/typedefs.list` in the same commit that introduces the type.** +- **Each commit must stand on its own as a defensible idea** with a self-contained rationale in its message. +- **Commit messages**: imperative subject <=72 chars; body explains *why*, not *what*; reference prior `-hackers` threads. No agent attribution, no co-authors unless code is genuinely derived from another contributor's work (e.g. ZHeap-descended table-AM plumbing -> `Co-authored-by:` the real author). Otherwise author is the user. +- **ASCII only** in code, comments, docs, and commit messages. No project codename leaking into identifiers (the `tepid` work forbade the "SIU" acronym in-tree; user-facing name is "HOT with selective index updates", in-source identifier `hot_indexed`). +- **A local-only dev-setup commit** (Nix env, editor config) stays as the first commit and is excluded from the submitted series; the feature branch holds the squashed/clean product, not the development history. + +## Verifying a Series Per-Commit (mechanics that bite) + +- **meson caches the initdb template.** The `setup` test suite builds `tmp_install/initdb-template`; it is *not* regenerated when you `git checkout` a different commit. Stale templates produce false regress diffs (catalog columns from the wrong commit, e.g. `system_views.sql`) and false passes. To test a commit honestly: `trash tmp_install testrun; meson test --suite setup` (regenerate) before `meson test --suite regress`. +- **ninja mtime traps.** Editing a file that was just `git checkout`-ed may not bump its mtime enough for ninja to rebuild; the build silently uses stale objects. When verifying a specific edit, `touch -d ` to force the recompile, and confirm the expected object actually compiles in the output. +- **Distinguish stale-build / stale-template confounds from real regressions before concluding anything.** This wasted real time: a "threshold=0 passes" result was a stale binary; a per-commit "rules.out" diff was a stale template. Rebuild + regenerate template, then re-measure, before forming a hypothesis. +- **Bisect deterministic test failures across the series** (`git checkout` each commit, build, run the single failing spec) to find the introducing commit; that almost always names the root cause. +- **Reproduce isolation/TAP failures standalone**: `initdb` a scratch cluster, drive two `psql` sessions plus the injection point by hand. Gives full error visibility and a live backend to attach. +- `gdb -p -batch -ex 'bt'` for hangs; inspect `PrivateRefCountArray` for held buffer pins and `BufferDescriptors[n].bufferdesc.tag` to identify which relation/block a pin or cleanup-lock is stuck on. + +## Git Mechanics & Safety (repeated) + +- **Never force-push** (a hook blocks it). To rewrite a published branch after explicit approval: create a backup branch and push it (`git branch bkp ; git push origin bkp:bkp`), then `git push origin --delete ` and `git push origin ` fresh. Always back up before any history rewrite. +- **`git add` named paths only** -- never `git add .`/`-A`/`-u`. Don't commit agent artifacts (`.agent/`, `AGENTS.md`, notes); keep them in `.local-gitignore`. +- **`GIT_SEQUENCE_EDITOR=cat` does not "preview" a rebase -- it *executes* it** (cat exits 0, so the unmodified todo is accepted and run). For a real no-op preview, write the todo to a file and inspect it. For scripted rebases use `GIT_SEQUENCE_EDITOR=true GIT_EDITOR=true` (non-interactive) or a Python sequence-editor that rewrites the todo. +- **Reorder/relocate changes across commits** with `edit` stops (amend at each) or `--fixup=` + `git rebase -i --autosquash`. `--autosquash` auto-positions `fixup!` commits under their target; you only hand-move genuine reorders. + +## PostgreSQL-Internals Gotchas (verified the hard way) + +- **HOT determination must compare actual tuple values over the indexed-attr bitmap; do not shortcut via the SQL target list.** `ExecGetAllUpdatedCols()` misses indexed columns mutated outside the SET clause: BEFORE/INSTEAD-OF triggers using `heap_modify_tuple()` (`tsvector_update_trigger`), `FOR PORTION OF` temporal columns, exclusion constraints, and synthetic-`ResultRelInfo` callers (REPACK CONCURRENTLY apply, logical-replication apply). Upstream's `HeapDetermineColumnsInfo` always compares; match that. +- **Synthetic `ResultRelInfo` callers** (REPACK CONCURRENTLY apply has `ri_RangeTableIndex == 0`; logical-rep apply populates `updatedCols` on a synthetic RTE) make any `ExecGet*Cols()` result non-authoritative. Code that consumes the SQL target list must guard for, or simply avoid, these callers. +- **`INDEX_ATTR_BITMAP_*` semantics matter and are easy to get subtly wrong.** The non-summarizing set drives the HOT-blocking decision; `INDEX_ATTR_BITMAP_SUMMARIZED` is deliberately "columns *only* in summarizing indexes" (the `bms_del_members` against the non-summarizing set) so a column shared by a btree and a BRIN is *not* treated as summarizing-only -- otherwise an "all-summarizing" fast-path wrongly classifies its update as classic-HOT and leaves a stale btree entry. +- **btree leaf-pin retention vs VACUUM cleanup lock.** `so->dropPin` historically gated on `!xs_want_itup` as a proxy for "is index-only scan." Setting `xs_want_itup` on a *plain* index scan (e.g. to recheck a leaf key) then wrongly retains the leaf pin across the scan's tuple processing, which blocks VACUUM's cleanup lock behind a `SELECT ... FOR UPDATE` row-lock wait -> hang. Gate `dropPin` on an explicit "index-only" flag instead: `xs_itup` is copied into `so->currTuples` (scan-local), so a heap-fetching plain scan never needs the pin; only IOS does (VM all-visible / TID-recycle race). The planner's `get_actual_variable_endpoint()` scan sets `xs_want_itup` but uses `SnapshotNonVacuumable`, so `IsMVCCLikeSnapshot()` already keeps its pin regardless. +- **A leaf-key recheck needs the stored leaf key for *dedup*, not just qual re-evaluation.** Re-running `indexqualorig` against the live tuple drops false positives but cannot dedup two index entries that chain-walk to the same live tuple (-> duplicate rows). Per-scan TID dedup (the `systable_getnext` approach) works for equality catalog scans but breaks `ORDER BY` (returns the tuple at the stale key's sort position). The stored-leaf-key comparison is the correct general mechanism. +- **System-catalog index consistency after a relfilenode swap.** CLUSTER / VACUUM FULL / REPACK `UPDATE pg_class SET relfilenode` is itself subject to HOT decisions; an *unchanged* index (e.g. `pg_class`'s relname index) chain-walks to the new tuple and must be recheck-*kept*, or a direct `SELECT ... WHERE relname = ...` via the executor index-scan path silently returns no row even though the table is fine. Internal catalog access goes through `systable_getnext` (HeapKeyTest + TID dedup); direct SQL on a catalog goes through the executor IndexScan path -- both must agree. + +## Empirical Discipline (the user enforces this) + +- **Do not assert "behavior-preserving" or "fixed" without evidence.** Prove it: compare the failing artifact at the commit-before vs commit-after; show the test going from red to green; show the standalone repro now returning the right answer. +- **When asked to "verify first," verify and present the evidence before implementing.** Reason through alternatives explicitly and say why the chosen one wins; don't silently pick one. + +## Comment Conventions (PostgreSQL house style) + +These are the project's conventions for comments in patches to core and in +extension code written to match it. They are stricter than general-purpose +commenting advice and they are what reviewers on pgsql-hackers expect. + +- No comment is the default. Code should explain itself, and a comment + that states the obvious is noise in the diff. +- A comment earns its place by telling the reader something non-obvious + — the why, the constraint, the case the code can't show — pitched a + level above the code, in simple words. Usually that takes a sentence + or two; when a subtlety obviously demands a long comment, write the + long comment. +- Comments describe the code as it stands — noting previous behavior is + rarely needed. Leave comments outside the patch's footprint alone, + unless the patch has made them out-of-date or inaccurate; updating + those is part of the change. +- A fix restores intended behavior; it's rarely an occasion to add + comments the original code did without. Don't comment defensively + against edits that haven't happened. +- The default above is for patches to existing code. New code I write + is commented generously: a header comment on nearly every new + function (summary, then the caller contract), a short full-sentence + step comment above each phase of a nontrivial one ("Quick exit if + we already did this."), and multi-sentence blocks for the why and + the constraints. +- Block comments sit above the code, in complete sentences with a + capital and a period. Trailing same-line comments are only for + struct members and short guards, as telegraphic fragments. +- "Note that ..." is the house connective. "NB:" flags a caller + contract or trap. "XXX" marks an acknowledged hack, nothing else. + Never "FIXME", never a "Note:" label. + +## Tests (community norms) + +- The bar for adding a test is high. Simple fixes routinely ship without + one; that is the community norm, not a corner cut. +- A warranted test is minimal and simple, not exhaustive. Cover the case + that matters and skip variations that prove nothing new; redundant + coverage is a cost, not a safety margin. +- Blend new tests into the existing suite. Extend a nearby block in its + own style rather than building new scaffolding. A new block or file is + sometimes right, but treat it as the exception. +- Calibration: roughly one in six behavior fixes ships with a test. When + one does, it is a graft — single statements inside an existing block, + reusing its roles and fixtures and copying its local idioms (e.g., the + "-- fail" markers). +- TAP description strings are lowercase and telegraphic, echoing the + thing under test: 'vacuumdb --dry-run'. Comments inside test files are + still full sentences. + +## Docs (SGML) + +- Present tense, one point per . Caveats become "Note that ..." + sentences or a . +- GUC descriptions follow the skeleton: "Specifies the ... The default + is X. This parameter can only be set ...". +- Prefer a varlistentry list over a table when items deserve anchors. + Alphabetize where order carries no meaning. +- A missing word is a standalone "doc:" commit, not a passenger on + another change. + +## Commit messages (PostgreSQL house style) + +Extends the generic rules in prose-mechanics.md; where they differ, these +win. + +- Subject: "area: Imperative summary." — capitalized, about 50 + characters, and yes, the trailing period. The area prefix is a tool or + module name in its in-tree lowercase spelling (pg_upgrade:, vacuumdb:, + doc:). Backend changes get no prefix. +- Body prose is hard-wrapped at 67 columns. One or two paragraphs is the + norm; a "* " list only for genuinely enumerable sub-changes. +- Fix shape: the broken behavior in present tense ("Presently, ..."), + then its consequence, then "To fix, ...". +- Attribution closes as its own paragraph: "Oversight in commit + <10-hex-hash>.", plus "Per buildfarm." or "Per Coverity." when that is + the source. Trivial fixups can be a subject line and little else. +- Prior commits are "commit " + 10-hex hash, including in lists + ("commits 30e7c175b8, e469f0aaf3, and 492046fa9e"). +- The palette, used naturally and never all at once: "This commit ...", + "While at it, ...", "In passing, ...", "teach X to Y", "left as a + future exercise", "This is preparatory work for a follow-up commit + that will ...", "Bumps catversion." Risk is hedged by understatement: + "seems unlikely to cause too much trouble in practice". +- Trailers, one person per line as Name , in this order: Bug / + Reported-by / Suggested-by, then Author / Co-authored-by, Reviewed-by, + Tested-by, Security, Discussion, and Backpatch-through always last. No + Author: line for sole-author work. Discussion is a percent-encoded + https://postgr.es/m/ link, omitted on CVE commits and trivial fixups. +- Scale to the change; model commits worth imitating: 626d7236b65 (a big + feature), 158408fef8b (a subtle fix), 1fbe2066dcc (a bug fix). + +## Minimization + +- Aim for the smallest patch that does the job well — code, comments, and + tests alike. It reads faster in review and keeps needless churn off the + tree. +- There are exceptions, but they are earned. Put real effort into making + the patch fit nicely before concluding that it cannot. +- Split series: a framework commit, then one conversion per commit. + Re-pgindent and .git-blame-ignore-revs updates are their own commits. +- One adjacent cleanup may ride along if the message flags it with + "While at it, ...". Anything more is deferred and named ("left as a + future exercise"). +- Comment-only fixes are their own commits, never passengers. + +## E-mail to the pgsql lists + +Plain text wrapped near 72 columns, interleaved under trimmed quotes. No +greeting and no closing, ever: the client supplies the attribution line +and the signature, so a draft starts with content and just ends. + +- Default to short. The median reply is about four lines, and a one-line + reply is normal ("Committed.", "WFM.", "Done.", "Agreed."). +- Content goes below the quote it answers. The only thing above the first + quote is a one-line meta note: "Thanks for the report.", "Thanks for + taking a look.", "Committed." Trim quotes hard and mark cuts with + "> [...]". +- Thread-starts open cold with the discovery ("While , I noticed + that ..."), then evidence (commit hashes, [0]-indexed footnote URLs + above the sig), then the proposal and patch, ending "Thoughts?" or "Am + I missing something?". +- Reviews anchor on pasted diff hunks with the comment underneath, + per-patch verdicts like "Otherwise, 0001 looks good.", and minor points + as "nitpick: ..." with an out ("but others might find your version + easier to read"). +- Approvals: "WFM.", "Seems reasonable.", "Looks reasonable to me.", + "+1", "Agreed." Never "LGTM", never a "-1" vote. +- Disagreement: "I don't think we want to ...", "I'm not seeing why we + wouldn't just ...", "I am quite dubious we need to do anything here." + Retraction ends with "Sorry for the noise." +- Process formulas: "Here is what I have staged for commit."; "Barring + additional feedback, I plan to commit this soon."; "I'd like to proceed + with committing this in the next couple of days if there are no + objections."; close the loop with "Committed." plus any caveats. +- Asks are "Would you mind ...?" / "Can you ...?", almost never "please". +- In stock: IIUC, AFAICT, IMHO (never IMO), FWIW, "folks", "Yeah," and + "Ah," openers. Same voice to everyone; newcomers just additionally get + the process spelled out (commitfest entry, cfbot). + +## Postgres-specific prose mechanics + +Extends prose-mechanics.md for this project only. + +- Versions are "v17". Maintenance branches are "the back-branches". + "back-patch" is hyphenated. The product is "Postgres" in casual prose. +- GUCs, options, and file names stay bare, unquoted and unmarked. + +## postgresql-benchmarking.md +# PostgreSQL benchmarking: committer practice + +PostgreSQL-specific rules on top of the generic `benchmarking.md` (read that +first: A/A floor, ABBA order, environment record, verdicts). These capture how +Postgres committers (Andres Freund, Tomas Vondra) actually measure, and the +traps specific to Postgres and pgbench. For the NUMA/EC2 clock-sweep runner see +the `pg-numa-benchmark` skill; this is the methodology it must obey. + +## pgbench correctness + +1. **Scale factor >= client count.** Otherwise you measure contention on + `pgbench_branches`, not the thing under test. +2. **pgbench can be the bottleneck.** Confirm the driver isn't the limit before + trusting a throughput number. +3. **Database state matters.** Results depend on time since init, dead rows and + autovacuum. Rebuild/reset the database the same way before every run. +4. **Read-only vs read-write durations differ.** A read-only run can be ~1 + minute; a read-write run should span 2–3 checkpoints each (hours across a + full set). +5. **Warm up with `pgbench -P 1`.** Watch the live trace to find steady state + (e.g. ~25k -> ~100k tps over ~200 s), discard the warmup, then measure. + +## Measure the right thing + +- **Isolate the code under test.** The SQL form changes how much of the runtime + is your code — from "unusable" to ~50%. Prefer a dedicated C benchmark + function (e.g. a `deform_bench`-style helper) for microbenchmarks, and + estimate the Amdahl fraction first: a 10x speedup on 1.5% of the workload + moves total time from 60 to 59.19. +- **Don't profile contention with CPU cycles.** A `LOCK pgbench_accounts` + workload barely moves from 1 to 8 clients. Use wait events or off-CPU + profiling for contention. + +## Postgres-specific noise sources + +- **Shared-memory page faults.** The first runs after server start pay + page-fault noise (the kernel reserves but doesn't touch pages). Warm up until + it settles; the upstream fix is `MAP_POPULATE` in `sysv_shmem.c` (a possible + developer GUC). +- **Cold-cache runs:** `pg_buffercache_evict_relation` (PG 18+) for shared + buffers, `echo 3 > /proc/sys/vm/drop_caches` for the page cache. Neither + clears the SSD's internal DRAM cache. +- **Very short queries are treacherous.** On a 176-core EPYC, read-only pgbench + fell ~500k -> ~350k tps at ~22 clients and recovered near 100 — pinning moved + or removed it, pipelining 5 queries removed it, and the root cause is + unresolved. Before trusting a client-count curve, retest with pipelining and + different client counts; a dip can be scheduler/idle interaction, not your + change. + +## Build discipline for Postgres + +- Benchmark an **optimized** build. Do **not** benchmark `--enable-cassert` or + debug-only builds — they are much slower and unrepresentative. +- For a sub-5% effect, build stock and patched **several times** with shuffled + section layout and summarize across builds (layout alone is ~1–5% noise). +- Record the exact `configure`/meson flags and commit in the environment record + (generic steering) — a compiler or flag change alone shifts results. + +## Profiling Postgres + +- Decide CPU-bound vs contention-bound first (wait events / off-CPU), then + profile. +- Confirm hardware counters work (virtualization hides them). +- Build with frame pointers (`-fno-omit-frame-pointer`) for `perf` stack walks. +- `perf stat -ddd` for memory latency, dTLB/iTLB and branch misses; read both + `perf report --children` and `--no-children`. +- iTLB-bound code: map the binary on huge pages + (`-Wl,-zcommon-page-size=0x200000 -Wl,-zmax-page-size=0x200000`, or a + `tmpfs huge=always` copy) — compatible with THP `never` for data only via the + tmpfs route. + +## Unverified / gaps (do not assert these) + +- The claim that some BIOS settings exist only on a physical "under your desk" + host and not on cloud metal is **unverified** — it is not in Freund's slides + or the podcasts. Don't state it as sourced. +- No committer source was found on DWARF-vs-LBR unwinding, skid/PEBS, or symbol + handling — flag those as the agent's own judgement, not established practice. + diff --git a/.clangd b/.clangd new file mode 100644 index 0000000000000..490220f56a7c0 --- /dev/null +++ b/.clangd @@ -0,0 +1,43 @@ +Diagnostics: + MissingIncludes: None +InlayHints: + Enabled: true + ParameterNames: true + DeducedTypes: true +CompileFlags: + CompilationDatabase: build/ # Search build/ directory for compile_commands.json + Remove: [ -Werror ] + Add: + - -DDEBUG + - -DLOCAL + - -DPGDLLIMPORT= + - -DPIC + - -O2 + - -Wall + - -Wcast-function-type + - -Wconversion + - -Wdeclaration-after-statement + - -Wendif-labels + - -Werror=vla + - -Wextra + - -Wfloat-equal + - -Wformat-security + - -Wimplicit-fallthrough=3 + - -Wmissing-format-attribute + - -Wmissing-prototypes + - -Wno-format-truncation + - -Wno-sign-conversion + - -Wno-stringop-truncation + - -Wno-unused-const-variable + - -Wpointer-arith + - -Wshadow + - -Wshadow=compatible-local + - -fPIC + - -fexcess-precision=standard + - -fno-strict-aliasing + - -fvisibility=hidden + - -fwrapv + - -g + - -std=c11 + - -I. + - -I../../../../src/include diff --git a/.envrc b/.envrc new file mode 100644 index 0000000000000..730257178089b --- /dev/null +++ b/.envrc @@ -0,0 +1,10 @@ +# Inherit shared CFLAGS from ~/ws/postgres/.envrc, load this worktree's +# flake, then layer the postgres agent context (helpers need flake's PATH + +# write into this worktree's dir). +source_up +watch_file flake.nix +use flake +use project_steering c aws +use project_steering postgresql +use project_mcp postgresq +use project_mcp context7 diff --git a/.gdbinit b/.gdbinit new file mode 100644 index 0000000000000..854e5ecbaf69c --- /dev/null +++ b/.gdbinit @@ -0,0 +1,156 @@ +# HOT Indexed Updates — GDB breakpoints for code review +# +# Usage: gdb -x .gdbinit +# Or from gdb: source .gdbinit +# +# These breakpoints cover the major code paths introduced or modified by +# the HOT indexed updates patch series. They are organized by subsystem +# to make it easy to enable/disable groups during debugging. +# +# Tip: to skip to a specific subsystem, disable all then enable selectively: +# disable breakpoints +# enable 1 2 3 # just the update-decision group + +# ========================================================================= +# 1. UPDATE DECISION — heap_update() HOT/HOT-indexed/non-HOT choice +# src/backend/access/heap/heapam.c +# ========================================================================= + +# Main entry: heap_update +break heapam.c:3210 + +# HOT decision block: pure HOT vs HOT indexed vs non-HOT +# Line 4019: pure HOT (no indexed columns changed) +# Line 4024: HOT indexed path (non-catalog, some indexed columns changed) +# Line 4031: predict augmented tuple size +# Line 4033: size+space check before creating augmented tuple +break heapam.c:4019 +break heapam.c:4024 +break heapam.c:4033 + +# Set HEAP_INDEXED_UPDATED flag on new tuple before page insertion +break heapam.c:4101 + +# Restore HEAP_INDEXED_UPDATED on old tuple (only if it previously had it) +break heapam.c:4147 + +# ========================================================================= +# 2. TUPLE CREATION — building the augmented tuple with embedded bitmap +# src/backend/access/heap/heapam.c +# ========================================================================= + +# Predict augmented tuple size (returns 0 if t_hoff would overflow) +break heap_hot_indexed_tuple_size + +# Create augmented tuple with embedded modified-column bitmap +break heap_hot_indexed_create_tuple + +# Serialize Bitmapset into raw bytes in tuple header +break heap_hot_indexed_serialize_bitmap + +# ========================================================================= +# 3. BITMAP UTILITIES — raw bitmap operations for chain following +# src/backend/access/heap/heapam.c +# ========================================================================= + +# Compute raw bitmap byte size from natts +break heap_hot_indexed_bitmap_raw_size + +# Check if tuple header has room for bitmap between null bitmap and data +break heap_hot_indexed_has_bitmap_space + +# Read HOT indexed bitmap from tuple header (returns Bitmapset) +break heap_hot_indexed_read_bitmap + +# Fast overlap check: does tuple's raw bitmap overlap with indexed_attrs? +break heap_hot_indexed_bitmap_overlaps_raw + +# OR a tuple's raw bitmap into an accumulator buffer +break heap_hot_indexed_bitmap_or_raw + +# Check if accumulated raw bitmap overlaps with indexed_attrs +break heap_hot_indexed_accum_overlaps + +# Merge bitmaps from dead tuples into a target tuple on the page +break heap_hot_indexed_merge_bitmaps_raw + +# Deserialize raw bytes back to Bitmapset +break heap_hot_indexed_deserialize_bitmap + +# ========================================================================= +# 4. INDEX SCAN — HOT chain following with stale-entry detection +# src/backend/access/heap/heapam_indexscan.c +# ========================================================================= + +# Main HOT chain search with indexed update awareness +break heap_hot_search_buffer + +# Redirect-with-data: initialize bitmap accumulator from collapsed redirect +break heapam_indexscan.c:182 + +# Accumulate bitmap from INDEXED_UPDATED tuple in chain +break heapam_indexscan.c:250 + +# Stale entry detection: accumulated bitmap overlaps this index's attrs +break heapam_indexscan.c:297 + +# ========================================================================= +# 5. INDEX SCAN SETUP — indexed_attrs bitmap computation +# src/backend/access/index/indexam.c +# ========================================================================= + +# Compute indexed_attrs for HOT indexed update chain following +break indexam.c:299 + +# ========================================================================= +# 6. INDEX INSERTION — skip unchanged indexes for HOT indexed updates +# src/backend/executor/execIndexing.c +# ========================================================================= + +# Entry: insert/update index tuples +break ExecInsertIndexTuples + +# Index skip decision: skip indexes whose attrs don't overlap modified set +break execIndexing.c:370 + +# ========================================================================= +# 7. PRUNING — chain collapsing and redirect-with-data +# src/backend/access/heap/pruneheap.c +# ========================================================================= + +# Main prune function +break heap_page_prune_and_freeze + +# Per-chain pruning entry +break heap_prune_chain + +# Chain collapsing: collect bitmaps from dead INDEXED_UPDATED intermediates +break pruneheap.c:1802 + +# OR dead tuple bitmaps into combined bitmap +break pruneheap.c:1836 + +# Record redirect-with-data for execute phase +break pruneheap.c:1863 + +# Execute phase: apply redirect-with-data entries on the page +break pruneheap.c:1287 + +# ========================================================================= +# 8. WAL REPLAY — recovery of HOT indexed updates +# src/backend/access/heap/heapam_xlog.c +# ========================================================================= + +# WAL replay for XLOG_HEAP2_INDEXED_UPDATE +break heap_xlog_indexed_update + +# ========================================================================= +# 9. WAL LOGGING — writing HOT indexed update records +# src/backend/access/heap/heapam.c +# ========================================================================= + +# WAL logging for heap updates (handles indexed_update flag) +break log_heap_update + +# Serialize redirect-with-data into WAL record (pruneheap.c) +break pruneheap.c:2936 diff --git a/.github/workflows/fork-ocr-model-check.yml b/.github/workflows/fork-ocr-model-check.yml new file mode 100644 index 0000000000000..b85a990c66fd7 --- /dev/null +++ b/.github/workflows/fork-ocr-model-check.yml @@ -0,0 +1,18 @@ +# Weekly check for a newer Claude Opus on Bedrock; opens/updates one issue here +# when OCR_BEDROCK_MODEL is behind. Notify-only (GITHUB_TOKEN cannot write +# Actions variables). Logic lives in gburd/ci-workflows. + +name: OCR model self-check + +on: + schedule: + - cron: '0 12 * * 1' # Mondays 12:00 UTC + workflow_dispatch: + +jobs: + check: + uses: gburd/ci-workflows/.github/workflows/ocr-model-check.yml@v1 + with: + aws_role_arn: ${{ vars.AWS_ROLE_ARN }} + aws_region: ${{ vars.AWS_REGION }} + bedrock_model: ${{ vars.OCR_BEDROCK_MODEL }} diff --git a/.github/workflows/fork-ocr-review.yml b/.github/workflows/fork-ocr-review.yml new file mode 100644 index 0000000000000..ae938754339b4 --- /dev/null +++ b/.github/workflows/fork-ocr-review.yml @@ -0,0 +1,43 @@ +# AI PR review (Claude Opus on Bedrock). Logic and review rules live in +# gburd/ci-workflows so this fork's master carries a stub instead of ~1000 +# lines that have to be rebased onto upstream forever. +# +# Needs repo variables AWS_ROLE_ARN, AWS_REGION, OCR_BEDROCK_MODEL. Auth is +# GitHub OIDC; no static AWS keys. See the ci-workflows README. + +name: OCR AI Review + +on: + pull_request: + # Note: no draft filter — drafts are reviewed too. + types: [opened, synchronize, reopened, ready_for_review] + issue_comment: + types: [created] + workflow_dispatch: + inputs: + pr_number: + description: 'PR number to review' + required: true + type: number + +# One review per PR; cancel superseded runs to save Bedrock spend. +concurrency: + group: ocr-review-${{ github.event.pull_request.number || github.event.issue.number || github.event.inputs.pr_number }} + cancel-in-progress: true + +jobs: + review: + # Comment events only when the comment is on a PR and starts with the + # trigger keyword; PR events and manual dispatch always. + if: | + github.event_name == 'pull_request' || + github.event_name == 'workflow_dispatch' || + (github.event_name == 'issue_comment' && github.event.issue.pull_request && + (startsWith(github.event.comment.body, '/open-code-review') || + startsWith(github.event.comment.body, '@open-code-review') || + startsWith(github.event.comment.body, '/pg-history'))) + uses: gburd/ci-workflows/.github/workflows/ocr-review.yml@v1 + with: + aws_role_arn: ${{ vars.AWS_ROLE_ARN }} + aws_region: ${{ vars.AWS_REGION }} + bedrock_model: ${{ vars.OCR_BEDROCK_MODEL }} diff --git a/.github/workflows/fork-sync-upstream.yml b/.github/workflows/fork-sync-upstream.yml new file mode 100644 index 0000000000000..022b3101b5a9d --- /dev/null +++ b/.github/workflows/fork-sync-upstream.yml @@ -0,0 +1,48 @@ +# Keep this fork's master rebased on postgres/postgres master, carrying only +# the fork-owned CI stubs (.github/workflows/fork-*.yml). The workflows they +# call, and the OCR review rules, live in gburd/ci-workflows. +# +# Requires the SYNC_TOKEN secret: a PAT with repo+workflow scope. The default +# GITHUB_TOKEN is not allowed to push commits that touch .github/workflows/, +# and every commit we carry does. + +name: Sync from upstream + +on: + schedule: + - cron: '17 */3 * * *' + workflow_dispatch: + +concurrency: + group: fork-sync-upstream + +permissions: + contents: read + +jobs: + sync: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + token: ${{ secrets.SYNC_TOKEN }} + + - name: Rebase master onto upstream + run: | + set -euo pipefail + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + git remote add upstream https://github.com/postgres/postgres.git + git fetch --no-tags upstream master + + # Master carries fork CI only. Anything else means work landed here + # that belongs on a branch; force-rebasing it on a timer would be wrong. + if git diff --name-only upstream/master...HEAD | + grep -v '^\.github/workflows/fork-'; then + echo "::error::master carries non-CI changes (listed above); move them to a branch" + exit 1 + fi + + git rebase upstream/master + git push --force-with-lease diff --git a/.local-gitignore b/.local-gitignore new file mode 100644 index 0000000000000..5a54a35f5fed2 --- /dev/null +++ b/.local-gitignore @@ -0,0 +1,3 @@ +# git config core.excludesFile .local-gitignore +.local-gitignore + diff --git a/.mcp.json b/.mcp.json new file mode 100644 index 0000000000000..cdd4178394258 --- /dev/null +++ b/.mcp.json @@ -0,0 +1,12 @@ +{ + "mcpServers": { + "postgresq": { + "type": "http", + "url": "https://pg.ddx.io/mcp/" + }, + "postgres-mcp": { + "args": [], + "command": "/nix/store/j9ln9cay5m6bn2v1r672i0g7qykiyqx6-postgres-mcp" + } + } +} diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000000000..cc8e2ee7da460 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,3 @@ +# Project instructions + +See .agent-steering-domains.md for domain-specific steering (local). diff --git a/contrib/amcheck/Makefile b/contrib/amcheck/Makefile index 1b7a63cbaa40c..49ea1b3076f55 100644 --- a/contrib/amcheck/Makefile +++ b/contrib/amcheck/Makefile @@ -15,7 +15,7 @@ PGFILEDESC = "amcheck - function for verifying relation integrity" REGRESS = check check_btree check_gin check_heap -EXTRA_INSTALL = contrib/pg_walinspect +EXTRA_INSTALL = contrib/pageinspect contrib/pg_walinspect TAP_TESTS = 1 ifdef USE_PGXS diff --git a/contrib/amcheck/expected/check_btree.out b/contrib/amcheck/expected/check_btree.out index 4fcee5da46326..6826bd3df279b 100644 --- a/contrib/amcheck/expected/check_btree.out +++ b/contrib/amcheck/expected/check_btree.out @@ -283,6 +283,46 @@ SELECT bt_index_check('varlena_bug_idx', true); (1 row) +-- amcheck must decode prefix-compressed leaves and check the BTP_PREFIX +-- invariants. Most keys share a long prefix; the unshared key and the NULL +-- stay uncoded. The row count forces splits and deduplication. +CREATE TABLE prefix_bug (v text COLLATE "C"); +INSERT INTO prefix_bug + SELECT 'https://example.com/path/to/resource/' || lpad(g::text, 8, '0') + FROM generate_series(1, 20000) g; +INSERT INTO prefix_bug + SELECT 'https://example.com/path/to/resource/' || lpad((g % 100)::text, 8, '0') + FROM generate_series(1, 20000) g; +INSERT INTO prefix_bug VALUES ('zzz-no-shared-prefix'), (NULL); +CREATE INDEX prefix_bug_idx ON prefix_bug (v) WITH (prefix_compression = on); +SELECT bt_index_check('prefix_bug_idx', heapallindexed => true); + bt_index_check +---------------- + +(1 row) + +SELECT bt_index_parent_check('prefix_bug_idx', heapallindexed => true, rootdescend => true); + bt_index_parent_check +----------------------- + +(1 row) + +-- The final leaf's decoded split budget includes its last posting tuple, +-- not the smaller high key that would replace it on a non-rightmost leaf. +DROP INDEX prefix_bug_idx; +TRUNCATE prefix_bug; +INSERT INTO prefix_bug + SELECT repeat('x', 115) || lpad(g::text, 4, '0') + FROM generate_series(1, 106) g; +INSERT INTO prefix_bug + SELECT repeat('x', 115) || '0107' FROM generate_series(1, 113); +CREATE INDEX prefix_bug_idx ON prefix_bug (v) WITH (prefix_compression = on); +SELECT bt_index_parent_check('prefix_bug_idx', heapallindexed => true, rootdescend => true); + bt_index_parent_check +----------------------- + +(1 row) + -- cleanup DROP TABLE bttest_a; DROP TABLE bttest_b; @@ -294,3 +334,4 @@ DROP TABLE bttest_unique_nulls; DROP OWNED BY regress_bttest_role; -- permissions DROP ROLE regress_bttest_role; DROP TABLE varlena_bug; +DROP TABLE prefix_bug; diff --git a/contrib/amcheck/meson.build b/contrib/amcheck/meson.build index d5137ef691d61..84dba8b7813f1 100644 --- a/contrib/amcheck/meson.build +++ b/contrib/amcheck/meson.build @@ -50,6 +50,9 @@ tests += { 't/004_verify_nbtree_unique.pl', 't/005_pitr.pl', 't/006_verify_gin.pl', + 't/007_prefix.pl', + 't/008_prefix_limits.pl', + 't/009_prefix_split.pl', ], }, } diff --git a/contrib/amcheck/sql/check_btree.sql b/contrib/amcheck/sql/check_btree.sql index a5585085fad9e..ee3964633bc89 100644 --- a/contrib/amcheck/sql/check_btree.sql +++ b/contrib/amcheck/sql/check_btree.sql @@ -183,6 +183,33 @@ INSERT INTO varlena_bug VALUES (repeat('Test', 250)); ALTER TABLE varlena_bug ALTER COLUMN v SET STORAGE extended; SELECT bt_index_check('varlena_bug_idx', true); +-- amcheck must decode prefix-compressed leaves and check the BTP_PREFIX +-- invariants. Most keys share a long prefix; the unshared key and the NULL +-- stay uncoded. The row count forces splits and deduplication. +CREATE TABLE prefix_bug (v text COLLATE "C"); +INSERT INTO prefix_bug + SELECT 'https://example.com/path/to/resource/' || lpad(g::text, 8, '0') + FROM generate_series(1, 20000) g; +INSERT INTO prefix_bug + SELECT 'https://example.com/path/to/resource/' || lpad((g % 100)::text, 8, '0') + FROM generate_series(1, 20000) g; +INSERT INTO prefix_bug VALUES ('zzz-no-shared-prefix'), (NULL); +CREATE INDEX prefix_bug_idx ON prefix_bug (v) WITH (prefix_compression = on); +SELECT bt_index_check('prefix_bug_idx', heapallindexed => true); +SELECT bt_index_parent_check('prefix_bug_idx', heapallindexed => true, rootdescend => true); + +-- The final leaf's decoded split budget includes its last posting tuple, +-- not the smaller high key that would replace it on a non-rightmost leaf. +DROP INDEX prefix_bug_idx; +TRUNCATE prefix_bug; +INSERT INTO prefix_bug + SELECT repeat('x', 115) || lpad(g::text, 4, '0') + FROM generate_series(1, 106) g; +INSERT INTO prefix_bug + SELECT repeat('x', 115) || '0107' FROM generate_series(1, 113); +CREATE INDEX prefix_bug_idx ON prefix_bug (v) WITH (prefix_compression = on); +SELECT bt_index_parent_check('prefix_bug_idx', heapallindexed => true, rootdescend => true); + -- cleanup DROP TABLE bttest_a; DROP TABLE bttest_b; @@ -194,3 +221,4 @@ DROP TABLE bttest_unique_nulls; DROP OWNED BY regress_bttest_role; -- permissions DROP ROLE regress_bttest_role; DROP TABLE varlena_bug; +DROP TABLE prefix_bug; diff --git a/contrib/amcheck/t/004_verify_nbtree_unique.pl b/contrib/amcheck/t/004_verify_nbtree_unique.pl index 7d5c387325ae8..b750e5311ab41 100644 --- a/contrib/amcheck/t/004_verify_nbtree_unique.pl +++ b/contrib/amcheck/t/004_verify_nbtree_unique.pl @@ -250,5 +250,42 @@ qr/index uniqueness is violated for index "bttest_unique_idx3"/, 'detected uniqueness violation for index "bttest_unique_idx3"'); +# Mark an index containing duplicates as unique. Prefix decoding reuses its +# tuple buffer, but the diagnostic must retain the previous entry's heap TID. +$node->safe_psql( + 'postgres', q( + CREATE TABLE bttest_unique_prefix (u text COLLATE "C"); + INSERT INTO bttest_unique_prefix + SELECT repeat('prefix/', 12) || lpad(g::text, 4, '0') + FROM generate_series(1, 20) g; + INSERT INTO bttest_unique_prefix + SELECT u FROM bttest_unique_prefix + WHERE u = repeat('prefix/', 12) || '0010'; + CREATE INDEX bttest_unique_prefix_idx ON bttest_unique_prefix (u) + WITH (prefix_compression = on, deduplicate_items = off); + UPDATE pg_index SET indisunique = true + WHERE indexrelid = 'bttest_unique_prefix_idx'::regclass; +)); +my $duplicate_tids = $node->safe_psql( + 'postgres', q( + SELECT string_agg('tid=' || ctid::text, ' and ' ORDER BY ctid) + FROM bttest_unique_prefix + WHERE u = repeat('prefix/', 12) || '0010'; +)); +for my $check ('bt_index_check', 'bt_index_parent_check') +{ + my $args = $check eq 'bt_index_check' ? 'true, true' : 'true, true, true'; + ($result, $stdout, $stderr) = $node->psql( + 'postgres', "SELECT $check('bttest_unique_prefix_idx', $args)"); + like( + $stderr, + qr/index uniqueness is violated for index "bttest_unique_prefix_idx"/, + "$check detects uniqueness violation in prefix-compressed index"); + like( + $stderr, + qr/point to heap \Q$duplicate_tids\E/, + "$check reports both distinct heap TIDs in prefix-compressed index"); +} + $node->stop; done_testing(); diff --git a/contrib/amcheck/t/007_prefix.pl b/contrib/amcheck/t/007_prefix.pl new file mode 100644 index 0000000000000..3017093d83158 --- /dev/null +++ b/contrib/amcheck/t/007_prefix.pl @@ -0,0 +1,254 @@ +# Copyright (c) 2026, PostgreSQL Global Development Group + +# Corrupt prefix metadata must make amcheck and index scans report data +# corruption rather than crash. +use strict; +use warnings FATAL => 'all'; + +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +my $node = PostgreSQL::Test::Cluster->new('prefix'); +$node->init(no_data_checksums => 1); +$node->append_conf('postgresql.conf', 'autovacuum = off'); +$node->start; +$node->safe_psql( + 'postgres', q( + CREATE EXTENSION amcheck; + CREATE TABLE prefix_data (u text COLLATE "C"); + INSERT INTO prefix_data + SELECT repeat('prefix/', 12) || lpad(g::text, 4, '0') + FROM generate_series(1, 20) g; + CREATE TABLE prefix_posting AS + SELECT u FROM prefix_data CROSS JOIN generate_series(1, 4); +)); +my $blksize = $node->safe_psql('postgres', 'SHOW block_size'); +my $align = $node->safe_psql('postgres', + 'SELECT max_data_alignment FROM pg_control_init()'); +my $little_endian = pack('L', 1) eq "\x01\x00\x00\x00"; + +# ItemIdData is a native-endian bitfield; tuple metadata uses native uint16. +sub itemid +{ + my ($page, $offnum) = @_; + my $lp = unpack('L', substr($page, 24 + 4 * ($offnum - 1), 4)); + return $little_endian + ? ($lp & 0x7fff, $lp >> 17) + : ($lp >> 17, $lp & 0x7fff); +} + +sub put_short +{ + my ($page, $offset, $value) = @_; + substr($$page, $offset, 2) = pack('S', $value); + return; +} + +# Each case changes one field in its own index. Include a later member so a +# comparison with the next item cannot decode it before it has been checked. +my @cases = ( + [ + 'group', 0, + sub { my ($p, $d, $m) = @_; put_short($p, $m + 8, 65535); } + ], + [ + 'shared length', + 0, sub { my ($p, $d, $m) = @_; put_short($p, $m + 10, 65535); } + ], + [ + 'original size', + 0, sub { my ($p, $d, $m) = @_; put_short($p, $m + 12, 0); } + ], + [ + 'residual extent', + 0, sub { my ($p, $d, $m) = @_; put_short($p, $m + 10, 0); } + ], + [ + 'directory group count', + 0, sub { my ($p, $d) = @_; put_short($p, $d + 8, 65535); } + ], + [ + 'anchor offset', + 0, sub { my ($p, $d) = @_; put_short($p, $d + 14, 65535); } + ], + [ + 'anchor size', + 0, + sub { + my ($p, $d) = @_; + my $a = unpack('S', substr($$p, $d + 14, 2)); + put_short($p, $d + $a, 65535); + } + ], + [ + 'anchor tuple size', + 0, + sub { + my ($p, $d) = @_; + my $a = unpack('S', substr($$p, $d + 14, 2)); + put_short($p, $d + $a + $align + 6, 0); + } + ], + [ + 'decoded size cache', + 0, sub { my ($p, $d) = @_; put_short($p, $d + 10, 0); } + ], + [ + 'short code header', + 0, + sub { + my ($p, $d, $m) = @_; + my $lp = unpack('L', substr($$p, 32, 4)); + $lp = + $little_endian + ? (($lp & 0x1ffff) | (8 << 17)) + : (($lp & 0xffff8000) | 8); + substr($$p, 32, 4) = pack('L', $lp); + put_short($p, $m + 6, 8); + } + ], + [ + 'posting offset', + 1, + sub { + my ($p, $d, $m) = @_; + put_short($p, $m, 0); + put_short($p, $m + 2, 65535); + } + ], + [ + 'posting count', + 1, + sub { + my ($p, $d, $m) = @_; + put_short($p, $m + 4, 0x2000 | 0x0fff); + } + ], + [ + 'pivot member', + 0, + sub { + my ($p) = @_; + my $maxoff = (unpack('S', substr($$p, 12, 2)) - 24) / 4; + my ($m) = itemid($$p, 2 + int(($maxoff - 1) / 2)); + my $info = unpack('S', substr($$p, $m + 6, 2)); + put_short($p, $m + 6, $info | 0x2000); + } + ], + [ + 'member line pointer', + 0, + sub { + my ($p) = @_; + my $maxoff = (unpack('S', substr($$p, 12, 2)) - 24) / 4; + my $lp_off = 24 + 4 * (1 + int(($maxoff - 1) / 2)); + my $lp = unpack('L', substr($$p, $lp_off, 4)); + $lp = $little_endian + ? (($lp & 0xffff8000) | 32760) + : (($lp & 0x1ffff) | (32760 << 17)); + substr($$p, $lp_off, 4) = pack('L', $lp); + } + ],); + +my @paths; +for my $i (0 .. $#cases) +{ + my $table = $cases[$i][1] ? 'prefix_posting' : 'prefix_data'; + $node->safe_psql('postgres', + "CREATE TABLE prefix_case_$i AS TABLE $table; + CREATE INDEX prefix_idx_$i ON prefix_case_$i (u) + WITH (prefix_compression = on)" + ); + is( $node->safe_psql( + 'postgres', + "SELECT bt_index_parent_check('prefix_idx_$i', true, true)"), + '', + "$cases[$i][0]: clean index passes"); + push @paths, + $node->data_dir . '/' + . $node->safe_psql('postgres', + "SELECT pg_relation_filepath('prefix_idx_$i')"); +} + +# Stop before opening relation files, avoiding stale buffers and background +# writes. Checksums are disabled so the errors come from prefix validation. +$node->stop; +for my $i (0 .. $#cases) +{ + open(my $fh, '+<', $paths[$i]) or BAIL_OUT("open: $!"); + binmode $fh; + defined(sysseek($fh, $blksize, 0)) or BAIL_OUT("seek: $!"); + my $page; + sysread($fh, $page, $blksize) == $blksize or BAIL_OUT("read: $!"); + my $special = unpack('S', substr($page, 16, 2)); + my $flags = unpack('S', substr($page, $special + 12, 2)); + ($flags & 0x201) == 0x201 or BAIL_OUT('fixture is not a coded leaf'); + unpack('L', substr($page, $special + 4, 4)) == 0 + or BAIL_OUT('fixture leaf is not rightmost'); + my ($directory) = itemid($page, 1); + my ($member, $membersz) = itemid($page, 3); + my $info = unpack('S', substr($page, $member + 6, 2)); + ($info & 0x1fff) == $membersz or BAIL_OUT('fixture tuple size mismatch'); + + if ($cases[$i][1]) + { + ($info & 0x2000) + && (unpack('S', substr($page, $member + 4, 2)) & 0x2000) + or BAIL_OUT('fixture member is not a posting tuple'); + } + $cases[$i][2]->(\$page, $directory, $member); + defined(sysseek($fh, $blksize, 0)) or BAIL_OUT("seek: $!"); + syswrite($fh, $page) == $blksize or BAIL_OUT("write: $!"); + close($fh) or BAIL_OUT("close: $!"); +} +$node->start; + +for my $i (0 .. $#cases) +{ + for my $check ('bt_index_check', 'bt_index_parent_check') + { + my ($ret, $out, $err) = $node->psql('postgres', + "\\set VERBOSITY verbose\nSELECT $check('prefix_idx_$i');"); + is($ret, 3, "$cases[$i][0]: $check reports an error"); + like($err, qr/ERROR:\s+XX002:.*prefix/i, + "$cases[$i][0]: prefix corruption diagnostic"); + unlike( + $err, + qr/server closed the connection|terminated by signal/i, + "$cases[$i][0]: no backend crash"); + } +} + +# Index scans use the shared decoder without amcheck's whole-page +# validation. The pivot member and member line pointer cases damage the +# first binary-search midpoint, before any member is decoded. +my $scan_settings = q( + SET enable_seqscan = off; + SET enable_bitmapscan = off; + SET enable_indexonlyscan = off; +); +for my $i (0 .. $#cases) +{ + next unless $cases[$i][0] =~ + /^(group|shared length|short code header|posting offset|posting count|pivot member|member line pointer)$/; + my $query = "SELECT u FROM prefix_case_$i + WHERE u >= repeat('prefix/', 12) || '0001'"; + my $plan = $node->safe_psql('postgres', + "$scan_settings EXPLAIN (COSTS OFF) $query"); + like($plan, qr/Index Scan using prefix_idx_$i on prefix_case_$i\b/, + "$cases[$i][0]: direct index scan plan"); + note($plan); + my ($ret, $out, $err) = $node->psql('postgres', + "\\set VERBOSITY verbose\n$scan_settings $query"); + is($ret, 3, "$cases[$i][0]: direct scan reports an error"); + like($err, qr/ERROR:\s+XX002:.*prefix/i, + "$cases[$i][0]: direct scan prefix diagnostic"); + unlike($err, qr/server closed the connection|terminated by signal/i, + "$cases[$i][0]: direct scan does not crash"); +} + +is($node->safe_psql('postgres', 'SELECT 1'), + '1', 'node remains usable after corruption checks'); +$node->stop; +done_testing(); diff --git a/contrib/amcheck/t/008_prefix_limits.pl b/contrib/amcheck/t/008_prefix_limits.pl new file mode 100644 index 0000000000000..c68abc380ce0f --- /dev/null +++ b/contrib/amcheck/t/008_prefix_limits.pl @@ -0,0 +1,186 @@ +# Copyright (c) 2026, PostgreSQL Global Development Group + +# A 32KB page can hold index tuples that exceed the prefix format's limits. +use strict; +use warnings FATAL => 'all'; +use Digest::MD5 qw(md5_hex); +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +# The sizes asserted below assume 32KB pages and 8-byte alignment. +plan skip_all => 'prefix representation limits require 32KB pages and 8-byte alignment' + unless check_pg_config('^#define BLCKSZ 32768$') + && check_pg_config('^#define MAXIMUM_ALIGNOF 8$'); + +my $node = PostgreSQL::Test::Cluster->new('node'); +$node->init; +$node->append_conf('postgresql.conf', 'autovacuum = off'); +$node->start; + +$node->safe_psql('postgres', + 'CREATE EXTENSION amcheck; CREATE EXTENSION pageinspect;'); + +my $small_hash = md5_hex(pack('H*', 'ab' x 1024)); +my $large_hash = md5_hex(pack('H*', 'cd' x 8168)); + +# Check the structure and the exact indexed values, not just heap row counts. +# btpo_flags bits from nbtree.h: BTP_ROOT is 2, BTP_PREFIX is 512. +# Each table has only the index under test when this is called. +sub check_index +{ + my ($table, $expected, $description) = @_; + $node->safe_psql('postgres', "VACUUM ANALYZE $table"); + is( $node->safe_psql('postgres', + "SELECT bt_index_parent_check('${table}_idx', true, true)"), + '', "$description: amcheck"); + my $query = "SELECT a, count(*), octet_length(b), md5(b) FROM $table " + . 'GROUP BY a, b ORDER BY a'; + my $settings = 'SET enable_seqscan = off; SET enable_bitmapscan = off; '; + like( + $node->safe_psql('postgres', + $settings . 'EXPLAIN (COSTS OFF) ' . $query), + qr/Index Only Scan using ${table}_idx/, + "$description: index-only scan"); + is($node->safe_psql('postgres', $settings . $query), + $expected, "$description: indexed values"); +} + +# Ten full anchors cannot fit in one directory IndexTuple, even though the +# page can hold them. The 50-row case also exceeds a plain page's capacity. +$node->safe_psql( + 'postgres', q{ +CREATE TABLE directory (a smallint, b bytea); +ALTER TABLE directory ALTER COLUMN b SET STORAGE PLAIN; +INSERT INTO directory + SELECT a, decode(repeat('ab', 1024), 'hex') + FROM generate_series(1, 10) a, generate_series(1, 3) b; +}); +foreach my $copies (3, 5) +{ + $node->safe_psql( + 'postgres', q{ +CREATE INDEX directory_idx ON directory (a, b) + WITH (prefix_compression = on, deduplicate_items = off); +}); + check_index('directory', + join("\n", map { "$_|$copies|1024|$small_hash" } 1 .. 10), + 'directory with ' . (10 * $copies) . ' rows'); + $node->safe_psql('postgres', 'DROP INDEX directory_idx'); + $node->safe_psql( + 'postgres', q{ +INSERT INTO directory + SELECT a, decode(repeat('ab', 1024), 'hex') + FROM generate_series(1, 10) a, generate_series(1, 2) b; +}) if $copies == 3; +} + +$node->safe_psql( + 'postgres', q{ +CREATE TABLE member (a smallint, b bytea); +ALTER TABLE member ALTER COLUMN b SET STORAGE PLAIN; +INSERT INTO member + SELECT 1, decode(repeat('ab', 1024), 'hex') FROM generate_series(1, 3); +CREATE INDEX member_idx ON member (a, b) + WITH (prefix_compression = on, deduplicate_items = off); +}); +is( $node->safe_psql('postgres', + "SELECT btpo_flags & 512 <> 0 FROM bt_page_stats('member_idx', 1)"), + 't', 'retail insertion starts with a coded leaf'); + +# Establish that the large key is legal in an ordinary index. +$node->safe_psql( + 'postgres', q{ +CREATE TABLE plain (LIKE member); +ALTER TABLE plain ALTER COLUMN b SET STORAGE PLAIN; +INSERT INTO plain SELECT * FROM member; +CREATE INDEX plain_idx ON plain (a, b) WITH (deduplicate_items = off); +INSERT INTO plain VALUES (2, decode(repeat('cd', 8168), 'hex')); +}); +is( $node->safe_psql('postgres', + "SELECT max(itemlen) = 8184 FROM bt_page_items('plain_idx', 1)"), + 't', 'large plain tuple fits the index tuple size field'); +check_index('plain', "1|3|1024|$small_hash\n2|1|8168|$large_hash", + 'plain control'); + +# With no shared bytes, the coded header pushes the size over INDEX_SIZE_MASK. +$node->safe_psql('postgres', + "INSERT INTO member VALUES (2, decode(repeat('cd', 8168), 'hex'))"); +check_index('member', "1|3|1024|$small_hash\n2|1|8168|$large_hash", + 'retail member limit'); + +# A dense coded leaf can fit a plain page without leaving BTMaxItemSize free. +# Force a representation-limit split before, between, and after its key groups. +foreach my $incoming (0, 2, 4) +{ + my $table = "dense_$incoming"; + $node->safe_psql('postgres', qq{ +CREATE TABLE $table (a smallint, b bytea); +ALTER TABLE $table ALTER COLUMN b SET STORAGE PLAIN; +INSERT INTO $table + SELECT CASE WHEN n <= 12 THEN 1 ELSE 3 END, + decode(repeat('ab', 1024), 'hex') FROM generate_series(1, 23) n; +CREATE INDEX ${table}_idx ON $table (a, b) + WITH (prefix_compression = on, deduplicate_items = off); +}); + is( $node->safe_psql('postgres', qq{ +SELECT btpo_flags & 512 <> 0 AND btpo_level = 0 AND btpo_next = 0 + FROM bt_page_stats('${table}_idx', 1); +}), 't', "$table starts with a coded rightmost leaf"); + is( $node->safe_psql('postgres', qq{ +SELECT decoded = 23 * (1040 + 4) AND decoded <= 32724 + AND 32724 - decoded < 10896 AND decoded + 8184 + 4 <= 32724 + FROM (SELECT sum(8 + octet_length(decode(replace(data, ' ', ''), 'hex')) + 4) + AS decoded + FROM bt_page_items('${table}_idx', 1) WHERE itemoffset > 1) s; +}), 't', "$table fits plain but lacks the maximum-item reserve"); + $node->safe_psql('postgres', + "INSERT INTO $table VALUES ($incoming, decode(repeat('cd', 8168), 'hex'))"); + is( $node->safe_psql('postgres', qq{ +SELECT btpo_next <> 0 FROM bt_page_stats('${table}_idx', 1); +}), 't', "$table splits for an unrepresentable coded member"); + my %expected = (1 => "1|12|1024|$small_hash", + 3 => "3|11|1024|$small_hash", $incoming => "$incoming|1|8168|$large_hash"); + check_index($table, join("\n", map { $expected{$_} } sort { $a <=> $b } keys %expected), + "dense member insertion at $incoming"); +} + +# On little-endian hosts, 1 and 257 share one smallint byte; on big-endian +# hosts they share none. Either way the build estimator must reject the +# oversized member. +$node->safe_psql( + 'postgres', q{ +DELETE FROM member WHERE a = 2; +DROP INDEX member_idx; +INSERT INTO member VALUES (257, decode(repeat('cd', 8168), 'hex')); +CREATE INDEX member_idx ON member (a, b) + WITH (prefix_compression = on, deduplicate_items = off); +}); +check_index('member', "1|3|1024|$small_hash\n257|1|8168|$large_hash", + 'build member limit'); + +# VACUUM removes the directory when the root becomes empty. +$node->safe_psql( + 'postgres', q{ +TRUNCATE member; +DROP INDEX member_idx; +INSERT INTO member + SELECT 1, decode(repeat('ab', 1024), 'hex') FROM generate_series(1, 3); +CREATE INDEX member_idx ON member (a, b) + WITH (prefix_compression = on, deduplicate_items = off); +DELETE FROM member; +VACUUM member; +}); +is( $node->safe_psql( + 'postgres', q{ +SELECT btpo_flags & 512 = 0 AND btpo_flags & 2 <> 0 + AND live_items = 0 AND dead_items = 0 + FROM bt_page_stats('member_idx', 1); +}), + 't', 'vacuum removes the empty root directory'); +$node->safe_psql('postgres', + "INSERT INTO member VALUES (2, decode(repeat('cd', 8168), 'hex'))"); +check_index('member', "2|1|8168|$large_hash", 'empty root insertion'); + +$node->stop; +done_testing(); diff --git a/contrib/amcheck/t/009_prefix_split.pl b/contrib/amcheck/t/009_prefix_split.pl new file mode 100644 index 0000000000000..34454c14ca71a --- /dev/null +++ b/contrib/amcheck/t/009_prefix_split.pl @@ -0,0 +1,108 @@ +# Copyright (c) 2026, PostgreSQL Global Development Group + +# Fillfactor must steer a rightmost split of a coded leaf. Both indexes split +# byte-identical pages, so only fillfactor differs. +use strict; +use warnings FATAL => 'all'; +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +plan skip_all => 'prefix split fixture requires 8KB pages and 8-byte alignment' + unless check_pg_config('^#define BLCKSZ 8192$') + && check_pg_config('^#define MAXIMUM_ALIGNOF 8$'); + +my $node = PostgreSQL::Test::Cluster->new('node'); +$node->init; +$node->append_conf('postgresql.conf', 'autovacuum = off'); +$node->start; + +$node->safe_psql( + 'postgres', q{ +CREATE EXTENSION amcheck; +CREATE EXTENSION pageinspect; +CREATE FUNCTION make_key(n integer) RETURNS text LANGUAGE sql IMMUTABLE AS $$ + SELECT '/srv/objects/customer-0042/archive/' || lpad(n::text, 9, '0') || + '/' || repeat('a', 96) || '.json' +$$; +CREATE TABLE low (k text COLLATE "C"); +CREATE INDEX low_idx ON low (k) WITH (prefix_compression = on); +CREATE TABLE high (LIKE low); +CREATE INDEX high_idx ON high (k) WITH (prefix_compression = on); +DO $$ +BEGIN + FOR n IN 1..361 LOOP + INSERT INTO low VALUES (make_key((n - 1) / 4)); + INSERT INTO high VALUES (make_key((n - 1) / 4)); + END LOOP; +END +$$; +}); + +# btpo_flags bit 512 is BTP_PREFIX (nbtree.h). +foreach my $table ('low', 'high') +{ + is( $node->safe_psql('postgres', qq{ +SELECT btpo_flags & 512 <> 0 AND btpo_level = 0 AND btpo_next = 0 + FROM bt_page_stats('${table}_idx', 2); +}), 't', "$table starts with a coded rightmost leaf"); +} + +# Skip pd_lsn, pd_checksum and pd_flags, which differ between the two pages. +is( $node->safe_psql('postgres', q{ +SELECT substring(get_raw_page('low_idx', 2) FROM 13) = + substring(get_raw_page('high_idx', 2) FROM 13); +}), 't', 'fillfactor comparison starts with identical page contents'); + +# Even merging every equal key into a posting list cannot produce a plain +# page. The split must use the decoded-item array, not a temporary plain page. +is( $node->safe_psql('postgres', q{ +SELECT sum(((8 + octet_length(decode(replace(data, ' ', ''), 'hex')) + + CASE WHEN n > 1 THEN n * 6 ELSE 0 END + 7) / 8) * 8 + 4) > + current_setting('block_size')::integer + FROM (SELECT data, sum(coalesce(cardinality(tids), 1)) n + FROM bt_page_items('low_idx', 2) + WHERE itemoffset > 1 GROUP BY data) s; +}), 't', 'decoded leaf exceeds a page even after deduplication'); + +$node->safe_psql('postgres', q{ +ALTER INDEX low_idx SET (fillfactor = 10); +ALTER INDEX high_idx SET (fillfactor = 90); +INSERT INTO low VALUES (make_key(361 / 4)); +INSERT INTO high VALUES (make_key(361 / 4)); +}); + +my %left_tids; +foreach my $table ('low', 'high') +{ + is( $node->safe_psql('postgres', qq{ +SELECT btpo_next <> 0 FROM bt_page_stats('${table}_idx', 2); +}), 't', "$table splits on the same insertion"); + $left_tids{$table} = $node->safe_psql('postgres', qq{ +SELECT sum(coalesce(cardinality(tids), 1)) + FROM bt_page_items('${table}_idx', 2), bt_page_stats('${table}_idx', 2) + WHERE itemoffset > 1 + CASE WHEN btpo_flags & 512 <> 0 THEN 1 ELSE 0 END; +}); + $node->safe_psql('postgres', "VACUUM ANALYZE $table"); + is( $node->safe_psql('postgres', + "SELECT bt_index_parent_check('${table}_idx', true, true)"), + '', "$table: amcheck"); + my $query = "SELECT md5(string_agg(k, ',' ORDER BY k)) FROM $table"; + my $expected = $node->safe_psql('postgres', + "SELECT md5(string_agg(make_key((n - 1) / 4), ',' ORDER BY n)) " + . 'FROM generate_series(1, 362) n'); + my $settings = 'SET enable_seqscan = off; SET enable_bitmapscan = off; '; + like( + $node->safe_psql('postgres', + $settings . 'EXPLAIN (COSTS OFF) ' . $query), + qr/Index Only Scan using ${table}_idx/, + "$table: index-only scan"); + is($node->safe_psql('postgres', $settings . $query), + $expected, "$table: indexed values"); +} + +cmp_ok($left_tids{high}, '>', $left_tids{low}, + 'higher fillfactor leaves more TIDs on the finalized left page'); + +$node->stop; +done_testing(); diff --git a/contrib/amcheck/verify_nbtree.c b/contrib/amcheck/verify_nbtree.c index 97c519b47f53b..3821e9eeacde2 100644 --- a/contrib/amcheck/verify_nbtree.c +++ b/contrib/amcheck/verify_nbtree.c @@ -131,6 +131,10 @@ typedef struct BtreeCheckState bloom_filter *filter; /* Debug counter */ int64 heaptuplespresent; + + /* Decode workspaces for prefix-compressed leaf items */ + BTItemBuf itembuf; /* current target item */ + BTItemBuf nextbuf; /* any other item looked at meanwhile */ } BtreeCheckState; /* @@ -158,7 +162,8 @@ typedef struct BtreeLastVisibleEntry OffsetNumber offset; /* Offset on index block */ int postingIndex; /* Number in the posting list (-1 for * non-deduplicated tuples) */ - ItemPointer tid; /* Heap tid */ + ItemPointerData tid; /* Heap tid, copied: a decoded item's buffer + * is reused */ } BtreeLastVisibleEntry; /* @@ -230,6 +235,7 @@ static inline bool invariant_l_nontarget_offset(BtreeCheckState *state, Page nontarget, OffsetNumber upperbound); static Page palloc_btree_page(BtreeCheckState *state, BlockNumber blocknum); +static void bt_prefix_page_check(BtreeCheckState *state, Page page, BlockNumber blocknum); static inline BTScanInsert bt_mkscankey_pivotsearch(Relation rel, IndexTuple itup); static ItemId PageGetItemIdCareful(BtreeCheckState *state, BlockNumber block, @@ -868,8 +874,8 @@ bt_report_duplicate(BtreeCheckState *state, *pnposting = ""; htid = psprintf("tid=(%u,%u)", - ItemPointerGetBlockNumberNoCheck(lVis->tid), - ItemPointerGetOffsetNumberNoCheck(lVis->tid)); + ItemPointerGetBlockNumberNoCheck(&lVis->tid), + ItemPointerGetOffsetNumberNoCheck(&lVis->tid)); nhtid = psprintf("tid=(%u,%u)", ItemPointerGetBlockNumberNoCheck(nexttid), ItemPointerGetOffsetNumberNoCheck(nexttid)); @@ -916,7 +922,7 @@ bt_entry_unique_check(BtreeCheckState *state, IndexTuple itup, if (heap_entry_is_visible(state, tid)) { has_visible_entry = true; - if (ItemPointerIsValid(lVis->tid)) + if (ItemPointerIsValid(&lVis->tid)) { bt_report_duplicate(state, lVis, @@ -929,13 +935,13 @@ bt_entry_unique_check(BtreeCheckState *state, IndexTuple itup, * between the posting list entries of the first tuple on the * page after cross-page check. */ - if (lVis->blkno != targetblock && ItemPointerIsValid(lVis->tid)) + if (lVis->blkno != targetblock && ItemPointerIsValid(&lVis->tid)) return; lVis->blkno = targetblock; lVis->offset = offset; lVis->postingIndex = i; - lVis->tid = tid; + lVis->tid = *tid; } } } @@ -951,7 +957,7 @@ bt_entry_unique_check(BtreeCheckState *state, IndexTuple itup, if (heap_entry_is_visible(state, tid)) { has_visible_entry = true; - if (ItemPointerIsValid(lVis->tid)) + if (ItemPointerIsValid(&lVis->tid)) { bt_report_duplicate(state, lVis, @@ -961,7 +967,7 @@ bt_entry_unique_check(BtreeCheckState *state, IndexTuple itup, lVis->blkno = targetblock; lVis->offset = offset; - lVis->tid = tid; + lVis->tid = *tid; lVis->postingIndex = -1; } } @@ -981,8 +987,8 @@ bt_entry_unique_check(BtreeCheckState *state, IndexTuple itup, RelationGetRelationName(state->rel)), errdetail("It doesn't have visible heap tids and key is equal to the tid=(%u,%u)%s (points to heap tid=(%u,%u)).", lVis->blkno, lVis->offset, posting, - ItemPointerGetBlockNumberNoCheck(lVis->tid), - ItemPointerGetOffsetNumberNoCheck(lVis->tid)), + ItemPointerGetBlockNumberNoCheck(&lVis->tid), + ItemPointerGetOffsetNumberNoCheck(&lVis->tid)), errhint("VACUUM the table and repeat the check."))); } } @@ -1230,7 +1236,12 @@ bt_target_page_check(BtreeCheckState *state) BTPageOpaque topaque; /* Last visible entry info for checking indexes with unique constraint */ - BtreeLastVisibleEntry lVis = {InvalidBlockNumber, InvalidOffsetNumber, -1, NULL}; + BtreeLastVisibleEntry lVis; + + lVis.blkno = InvalidBlockNumber; + lVis.offset = InvalidOffsetNumber; + lVis.postingIndex = -1; + ItemPointerSetInvalid(&lVis.tid); topaque = BTPageGetOpaque(state->target); max = PageGetMaxOffsetNumber(state->target); @@ -1313,6 +1324,16 @@ bt_target_page_check(BtreeCheckState *state) LSN_FORMAT_ARGS(state->targetlsn)), errhint("This could be a torn page problem."))); + /* + * The coded size was checked against lp_len above; the checks below + * apply to the decoded item. + */ + if (P_HASPREFIX(topaque)) + { + itup = _bt_getitem(state->target, offset, &state->itembuf); + tupsize = IndexTupleSize(itup); + } + /* Check the number of index tuple attributes */ if (!_bt_check_natts(state->rel, state->heapkeyspace, state->target, offset)) @@ -1606,7 +1627,8 @@ bt_target_page_check(BtreeCheckState *state) itemid = PageGetItemIdCareful(state, state->targetblock, state->target, OffsetNumberNext(offset)); - itup = (IndexTuple) PageGetItem(state->target, itemid); + itup = _bt_getitem(state->target, OffsetNumberNext(offset), + &state->nextbuf); tid = BTreeTupleGetPointsToTID(itup); nhtid = psprintf("(%u,%u)", ItemPointerGetBlockNumberNoCheck(tid), @@ -1634,7 +1656,7 @@ bt_target_page_check(BtreeCheckState *state) */ if (state->checkunique && state->indexinfo->ii_Unique && P_ISLEAF(topaque) && !skey->anynullkeys && - (BTreeTupleIsPosting(itup) || ItemPointerIsValid(lVis.tid))) + (BTreeTupleIsPosting(itup) || ItemPointerIsValid(&lVis.tid))) { bt_entry_unique_check(state, itup, state->targetblock, offset, &lVis); @@ -1668,7 +1690,7 @@ bt_target_page_check(BtreeCheckState *state) lVis.blkno = InvalidBlockNumber; lVis.offset = InvalidOffsetNumber; lVis.postingIndex = -1; - lVis.tid = NULL; + ItemPointerSetInvalid(&lVis.tid); } else if (!unique_checked) { @@ -1793,7 +1815,8 @@ bt_target_page_check(BtreeCheckState *state) itemid = PageGetItemIdCareful(state, rightblock_number, rightpage, rightfirstoffset); - itup = (IndexTuple) PageGetItem(rightpage, itemid); + itup = _bt_getitem(rightpage, rightfirstoffset, + &state->nextbuf); bt_entry_unique_check(state, itup, rightblock_number, rightfirstoffset, &lVis); @@ -2047,7 +2070,11 @@ bt_right_page_check_scankey(BtreeCheckState *state, OffsetNumber *rightfirstoffs * Return first real item scankey. Note that this relies on right page * memory remaining allocated. */ - firstitup = (IndexTuple) PageGetItem(rightpage, rightitem); + if (P_ISLEAF(opaque)) + firstitup = CopyIndexTuple(_bt_getitem(rightpage, *rightfirstoffset, + &state->nextbuf)); + else + firstitup = (IndexTuple) PageGetItem(rightpage, rightitem); return bt_mkscankey_pivotsearch(state->rel, firstitup); } @@ -3029,10 +3056,14 @@ bt_rootdescend(BtreeCheckState *state, IndexTuple itup) insertstate.bounds_valid = false; insertstate.buf = lbuf; + /* The search bypasses palloc_btree_page's structural checks. */ + page = BufferGetPage(lbuf); + if (P_HASPREFIX(BTPageGetOpaque(page))) + bt_prefix_page_check(state, page, BufferGetBlockNumber(lbuf)); + /* Get matching tuple on leaf page */ offnum = _bt_binsrch_insert(state->rel, &insertstate); /* Compare first >= matching item on leaf page, if any */ - page = BufferGetPage(lbuf); /* Should match on first heap TID when tuple has a posting list */ if (offnum <= PageGetMaxOffsetNumber(page) && insertstate.postingoff <= 0 && @@ -3095,14 +3126,13 @@ static inline bool invariant_l_offset(BtreeCheckState *state, BTScanInsert key, OffsetNumber upperbound) { - ItemId itemid; int32 cmp; Assert(!key->nextkey && key->backward); /* Verify line pointer before checking tuple */ - itemid = PageGetItemIdCareful(state, state->targetblock, state->target, - upperbound); + (void) PageGetItemIdCareful(state, state->targetblock, state->target, + upperbound); /* pg_upgrade'd indexes may legally have equal sibling tuples */ if (!key->heapkeyspace) return invariant_leq_offset(state, key, upperbound); @@ -3126,8 +3156,8 @@ invariant_l_offset(BtreeCheckState *state, BTScanInsert key, ItemPointer rheaptid; bool nonpivot; - ritup = (IndexTuple) PageGetItem(state->target, itemid); topaque = BTPageGetOpaque(state->target); + ritup = _bt_getitem(state->target, upperbound, &state->nextbuf); nonpivot = P_ISLEAF(topaque) && upperbound >= P_FIRSTDATAKEY(topaque); /* Get number of keys + heap TID for item to the right */ @@ -3218,14 +3248,13 @@ invariant_l_nontarget_offset(BtreeCheckState *state, BTScanInsert key, BlockNumber nontargetblock, Page nontarget, OffsetNumber upperbound) { - ItemId itemid; int32 cmp; Assert(!key->nextkey && key->backward); /* Verify line pointer before checking tuple */ - itemid = PageGetItemIdCareful(state, nontargetblock, nontarget, - upperbound); + (void) PageGetItemIdCareful(state, nontargetblock, nontarget, + upperbound); cmp = _bt_compare(state->rel, key, nontarget, upperbound); /* pg_upgrade'd indexes may legally have equal sibling tuples */ @@ -3241,8 +3270,8 @@ invariant_l_nontarget_offset(BtreeCheckState *state, BTScanInsert key, BTPageOpaque copaque; bool nonpivot; - child = (IndexTuple) PageGetItem(nontarget, itemid); copaque = BTPageGetOpaque(nontarget); + child = _bt_getitem(nontarget, upperbound, &state->nextbuf); nonpivot = P_ISLEAF(copaque) && upperbound >= P_FIRSTDATAKEY(copaque); /* Get number of keys + heap TID for child/non-target item */ @@ -3259,6 +3288,29 @@ invariant_l_nontarget_offset(BtreeCheckState *state, BTScanInsert key, return cmp < 0; } +/* Add relation and block identification to catalog-free prefix diagnostics. */ +static void +bt_prefix_error_callback(void *arg) +{ + errcontext("%s", (char *) arg); +} + +static void +bt_prefix_page_check(BtreeCheckState *state, Page page, BlockNumber blocknum) +{ + ErrorContextCallback errcallback; + + errcallback.callback = bt_prefix_error_callback; + errcallback.arg = psprintf("Index \"%s\", block %u, page LSN %X/%08X.", + RelationGetRelationName(state->rel), blocknum, + LSN_FORMAT_ARGS(PageGetLSN(page))); + errcallback.previous = error_context_stack; + error_context_stack = &errcallback; + _bt_prefix_check(page); + error_context_stack = errcallback.previous; + pfree(errcallback.arg); +} + /* * Given a block number of a B-Tree page, return page in palloc()'d memory. * While at it, perform some basic checks of the page. @@ -3398,6 +3450,22 @@ palloc_btree_page(BtreeCheckState *state, BlockNumber blocknum) errmsg("non-rightmost leaf block %u in index \"%s\" lacks high key item", blocknum, RelationGetRelationName(state->rel)))); + /* + * A prefix-compressed page is a live leaf holding its directory item and + * at least one coded data item (an emptied page drops the directory). + */ + if (P_HASPREFIX(opaque) && + (!P_ISLEAF(opaque) || P_ISDELETED(opaque) || P_ISHALFDEAD(opaque) || + maxoffset < P_FIRSTDATAKEY(opaque))) + ereport(ERROR, + (errcode(ERRCODE_INDEX_CORRUPTED), + errmsg("block %u in index \"%s\" has an invalid prefix-compressed layout", + blocknum, RelationGetRelationName(state->rel)))); + + /* Validate all members before a comparison can decode any of them. */ + if (P_HASPREFIX(opaque)) + bt_prefix_page_check(state, page, blocknum); + /* * In general, internal pages are never marked half-dead, except on * versions of Postgres prior to 9.4, where it can be valid transient diff --git a/contrib/pageinspect/btreefuncs.c b/contrib/pageinspect/btreefuncs.c index f5433f10accbe..d40641fad4d79 100644 --- a/contrib/pageinspect/btreefuncs.c +++ b/contrib/pageinspect/btreefuncs.c @@ -96,6 +96,7 @@ typedef struct ua_page_items bool leafpage; bool rightmost; TupleDesc tupd; + BTItemBuf decodebuf; /* decoded data item of a BTP_PREFIX leaf */ } ua_page_items; @@ -497,11 +498,20 @@ bt_page_print_tuples(ua_page_items *uargs) itup = (IndexTuple) PageGetItem(page, id); + /* + * Show a prefix-compressed leaf's data items decoded, but itemlen as the + * stored (coded) size. The prefix directory item is shown raw. + */ + if (leafpage && + P_HASPREFIX(BTPageGetOpaque(page)) && + offset >= P_FIRSTDATAKEY(BTPageGetOpaque(page))) + itup = _bt_getitem(page, offset, &uargs->decodebuf); + j = 0; memset(nulls, 0, sizeof(nulls)); values[j++] = Int16GetDatum(offset); values[j++] = ItemPointerGetDatum(&itup->t_tid); - values[j++] = Int16GetDatum(IndexTupleSize(itup)); + values[j++] = Int16GetDatum(ItemIdGetLength(id)); values[j++] = BoolGetDatum(IndexTupleHasNulls(itup)); values[j++] = BoolGetDatum(IndexTupleHasVarwidths(itup)); @@ -663,6 +673,8 @@ bt_page_items_internal(PG_FUNCTION_ARGS, enum pageinspect_version ext_version) uargs->offset = FirstOffsetNumber; opaque = BTPageGetOpaque(uargs->page); + if (P_HASPREFIX(opaque)) + _bt_prefix_check(uargs->page); if (!P_ISDELETED(opaque)) fctx->max_calls = PageGetMaxOffsetNumber(uargs->page); @@ -756,6 +768,13 @@ bt_page_items_bytea(PG_FUNCTION_ARGS) uargs->offset = FirstOffsetNumber; + /* The raw header's page size cannot establish allocation bounds. */ + if (((PageHeader) uargs->page)->pd_special != + BLCKSZ - MAXALIGN(sizeof(BTPageOpaqueData))) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("input page is not a valid %s page", "btree"))); + /* verify the special space has the expected size */ if (PageGetSpecialSize(uargs->page) != MAXALIGN(sizeof(BTPageOpaqueData))) ereport(ERROR, @@ -777,6 +796,9 @@ bt_page_items_bytea(PG_FUNCTION_ARGS) (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("block is not a valid btree leaf page"))); + if (P_HASPREFIX(opaque)) + _bt_prefix_check(uargs->page); + if (P_ISDELETED(opaque)) elog(NOTICE, "page is deleted"); diff --git a/contrib/pageinspect/expected/btree.out b/contrib/pageinspect/expected/btree.out index 0aa5d73322f82..9448dd5f1cc0b 100644 --- a/contrib/pageinspect/expected/btree.out +++ b/contrib/pageinspect/expected/btree.out @@ -211,6 +211,13 @@ SELECT bt_page_items(get_raw_page('test1', 0)); ERROR: input page is not a valid btree page SELECT bt_page_items(get_raw_page('test1_a_brin', 0)); ERROR: input page is not a valid btree page +-- A forged page size must not make an out-of-bounds special area look valid. +WITH raw AS (SELECT get_raw_page('test1_a_idx', 1) AS p) +SELECT bt_page_items(set_byte(set_byte(set_byte(set_byte(p, + 16, CASE WHEN get_byte(p, 18) = 4 THEN 240 ELSE 255 END), + 17, CASE WHEN get_byte(p, 18) = 4 THEN 255 ELSE 240 END), 18, 0), 19, 0)) +FROM raw; +ERROR: input page is not a valid btree page \set VERBOSITY default -- Tests with all-zero pages. SHOW block_size \gset @@ -219,3 +226,38 @@ SELECT bt_page_items(decode(repeat('00', :block_size), 'hex')); bt_page_items | DROP TABLE test1; +-- A prefix-compressed leaf: data items are shown decoded, so data and htid +-- read as on a plain page, while itemlen shows the stored (coded) size. +CREATE TABLE test_prefix (u text COLLATE "C"); +INSERT INTO test_prefix + SELECT 'https://example.com/path/' || lpad(g::text, 4, '0') + FROM generate_series(1, 20) g; +CREATE INDEX test_prefix_idx ON test_prefix (u) WITH (prefix_compression = on); +CREATE INDEX test_plain_idx ON test_prefix (u); +SELECT btpo_flags & 512 <> 0 AS coded FROM bt_page_stats('test_prefix_idx', 1); +-[ RECORD 1 ] +coded | t + +-- same decoded items as the plain index (offset 1 is the prefix directory) +SELECT count(*) AS mismatches + FROM bt_page_items('test_prefix_idx', 1) c + FULL JOIN bt_page_items('test_plain_idx', 1) p ON p.itemoffset = c.itemoffset - 1 + WHERE c.itemoffset > 1 AND (c.data IS DISTINCT FROM p.data OR c.htid IS DISTINCT FROM p.htid); +-[ RECORD 1 ]- +mismatches | 0 + +-- and the same from a raw page image +SELECT count(*) AS mismatches + FROM bt_page_items(get_raw_page('test_prefix_idx', 1)) c + JOIN bt_page_items('test_prefix_idx', 1) r USING (itemoffset) + WHERE c.data IS DISTINCT FROM r.data; +-[ RECORD 1 ]- +mismatches | 0 + +-- coded items are smaller than the plain ones +SELECT (SELECT sum(itemlen) FROM bt_page_items('test_prefix_idx', 1) WHERE itemoffset > 1) < + (SELECT sum(itemlen) FROM bt_page_items('test_plain_idx', 1)) AS smaller; +-[ RECORD 1 ] +smaller | t + +DROP TABLE test_prefix; diff --git a/contrib/pageinspect/sql/btree.sql b/contrib/pageinspect/sql/btree.sql index 102ebdefe3c1b..d0893e6450fdb 100644 --- a/contrib/pageinspect/sql/btree.sql +++ b/contrib/pageinspect/sql/btree.sql @@ -53,6 +53,12 @@ SELECT bt_page_items('aaa'::bytea); CREATE INDEX test1_a_brin ON test1 USING brin(a); SELECT bt_page_items(get_raw_page('test1', 0)); SELECT bt_page_items(get_raw_page('test1_a_brin', 0)); +-- A forged page size must not make an out-of-bounds special area look valid. +WITH raw AS (SELECT get_raw_page('test1_a_idx', 1) AS p) +SELECT bt_page_items(set_byte(set_byte(set_byte(set_byte(p, + 16, CASE WHEN get_byte(p, 18) = 4 THEN 240 ELSE 255 END), + 17, CASE WHEN get_byte(p, 18) = 4 THEN 255 ELSE 240 END), 18, 0), 19, 0)) +FROM raw; \set VERBOSITY default -- Tests with all-zero pages. @@ -60,3 +66,27 @@ SHOW block_size \gset SELECT bt_page_items(decode(repeat('00', :block_size), 'hex')); DROP TABLE test1; + +-- A prefix-compressed leaf: data items are shown decoded, so data and htid +-- read as on a plain page, while itemlen shows the stored (coded) size. +CREATE TABLE test_prefix (u text COLLATE "C"); +INSERT INTO test_prefix + SELECT 'https://example.com/path/' || lpad(g::text, 4, '0') + FROM generate_series(1, 20) g; +CREATE INDEX test_prefix_idx ON test_prefix (u) WITH (prefix_compression = on); +CREATE INDEX test_plain_idx ON test_prefix (u); +SELECT btpo_flags & 512 <> 0 AS coded FROM bt_page_stats('test_prefix_idx', 1); +-- same decoded items as the plain index (offset 1 is the prefix directory) +SELECT count(*) AS mismatches + FROM bt_page_items('test_prefix_idx', 1) c + FULL JOIN bt_page_items('test_plain_idx', 1) p ON p.itemoffset = c.itemoffset - 1 + WHERE c.itemoffset > 1 AND (c.data IS DISTINCT FROM p.data OR c.htid IS DISTINCT FROM p.htid); +-- and the same from a raw page image +SELECT count(*) AS mismatches + FROM bt_page_items(get_raw_page('test_prefix_idx', 1)) c + JOIN bt_page_items('test_prefix_idx', 1) r USING (itemoffset) + WHERE c.data IS DISTINCT FROM r.data; +-- coded items are smaller than the plain ones +SELECT (SELECT sum(itemlen) FROM bt_page_items('test_prefix_idx', 1) WHERE itemoffset > 1) < + (SELECT sum(itemlen) FROM bt_page_items('test_plain_idx', 1)) AS smaller; +DROP TABLE test_prefix; diff --git a/doc/src/sgml/pageinspect.sgml b/doc/src/sgml/pageinspect.sgml index 3a113439e1dc4..3d4345f099e64 100644 --- a/doc/src/sgml/pageinspect.sgml +++ b/doc/src/sgml/pageinspect.sgml @@ -471,6 +471,18 @@ test=# SELECT itemoffset, ctid, itemlen, nulls, vars, data, dead, htid, tids[0:2 valid downlink in its ctid field, however. + + On a leaf page of an index with + prefix_compression + enabled, the item after the high key (or the first item, on a rightmost + page) may be the page's prefix directory, which holds the leading bytes + that the page's data items share. Such a page has bit 512 + (BTP_PREFIX) set in btpo_flags. + Its data items are shown decoded, so data + and htid read as they would on an + uncompressed page, while itemlen shows the + item's stored, compressed size. + For more details about the structure of B-tree indexes, see . For more details about diff --git a/doc/src/sgml/ref/create_index.sgml b/doc/src/sgml/ref/create_index.sgml index bb7505d171b6d..813d238c0f47a 100644 --- a/doc/src/sgml/ref/create_index.sgml +++ b/doc/src/sgml/ref/create_index.sgml @@ -477,6 +477,47 @@ CREATE [ UNIQUE ] INDEX [ CONCURRENTLY ] [ [ IF NOT EXISTS ] + + + prefix_compression (boolean) + + prefix_compression storage parameter + + + + + Controls leaf key prefix compression. When set to + ON, a leaf page may store the leading bytes that a + run of its tuples share just once and record only each tuple's + unshared remainder, which can substantially shrink indexes whose keys + share long leading bytes (for example URLs, jsonb paths, + zero-padded codes, or low-cardinality leading columns of a multicolumn + index). It applies to key columns of any data type. Compression can + save space and I/O, but adds CPU overhead during index builds, inserts, + and scans that reconstruct key values, including index-only scans. + Savings depend on the stored representation: different string length + headers can prevent sharing even when the strings have a common prefix. + Set to + ON or OFF to enable or disable the + optimization. The default is OFF. + + + + + Prefix compression only changes how keys are stored; comparisons always + see the original key values, so every collation and operator class + behaves identically with it on or off. A leaf is compressed only when + it is written as a whole (during an index build, or either half of a + page split), so turning prefix_compression on or off + via ALTER INDEX does not rewrite the index: existing + pages are left as they are and are converted the next time they are + written whole (REINDEX converts them all at once). No REINDEX is required, and indexes + upgraded with pg_upgrade keep working + unchanged. + + + + diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000000000..0a8ea19633bbb --- /dev/null +++ b/flake.lock @@ -0,0 +1,134 @@ +{ + "nodes": { + "flake-utils": { + "inputs": { + "systems": "systems" + }, + "locked": { + "lastModified": 1794427683, + "narHash": "sha256-o7ey9gEilsxaifqJWnBDlYSKbNWYQYtKwDyXeZU2kaU=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "cd489559845d81f673a12885576016c65cbe9363", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "flake-utils_2": { + "inputs": { + "systems": "systems_2" + }, + "locked": { + "lastModified": 1731533236, + "narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "11707dc2f618dd54ca8739b309ec4fc024de578b", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "libumem": { + "inputs": { + "flake-utils": "flake-utils_2", + "nixpkgs": [ + "nixpkgs-unstable" + ] + }, + "locked": { + "lastModified": 1792183156, + "narHash": "sha256-IGHrRJHSiAeKH6oUHIRfo9gl0P6LthIo5Iz7oHyKSSs=", + "ref": "refs/tags/v4.2.1", + "rev": "2d8645fb5f9e635a37b052868a32c6407a158a96", + "revCount": 1049, + "type": "git", + "url": "https://codeberg.org/gregburd/libumem" + }, + "original": { + "ref": "refs/tags/v4.2.1", + "type": "git", + "url": "https://codeberg.org/gregburd/libumem" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1767313136, + "narHash": "sha256-16KkgfdYqjaeRGBaYsNrhPRRENs0qzkQVUooNHtoy2w=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "ac62194c3917d5f474c1a844b6fd6da2db95077d", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixos-25.05", + "repo": "nixpkgs", + "type": "github" + } + }, + "nixpkgs-unstable": { + "locked": { + "lastModified": 1794644783, + "narHash": "sha256-3GnIGIy15bMduoS9RnWqKTmsJLWThla42UFtm0S7+us=", + "owner": "nixos", + "repo": "nixpkgs", + "rev": "5d2b81a7a3be3e2f832879028e4d60abbf58e9a0", + "type": "github" + }, + "original": { + "owner": "nixos", + "ref": "nixpkgs-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "flake-utils": "flake-utils", + "libumem": "libumem", + "nixpkgs": "nixpkgs", + "nixpkgs-unstable": "nixpkgs-unstable" + } + }, + "systems": { + "locked": { + "lastModified": 1791244623, + "narHash": "sha256-uuanbkFk8a313Zfrxdcz8Us/yQtaxNnKJtX8v0ZPpd8=", + "owner": "nix-systems", + "repo": "default", + "rev": "d36eeed142f88b5a636f2e3856a53c61654cf29b", + "type": "github" + }, + "original": { + "owner": "nix-systems", + "repo": "default", + "type": "github" + } + }, + "systems_2": { + "locked": { + "lastModified": 1681028828, + "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", + "owner": "nix-systems", + "repo": "default", + "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", + "type": "github" + }, + "original": { + "owner": "nix-systems", + "repo": "default", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000000000..0ff3960911812 --- /dev/null +++ b/flake.nix @@ -0,0 +1,70 @@ +{ + description = "PostgreSQL development environment"; + + inputs = { + nixpkgs.url = "github:NixOS/nixpkgs/nixos-25.05"; + nixpkgs-unstable.url = "github:nixos/nixpkgs/nixpkgs-unstable"; + flake-utils.url = "github:numtide/flake-utils"; + + # libumem: LD_PRELOAD malloc, the umem/umemctl CLI, and GDB/LLDB helpers. + # Track the latest tagged release that BUILDS. Bump the ref to a newer tag + # and run `nix flake update libumem`; do NOT point this at a branch, so the + # dev shell always builds a released version rather than an arbitrary + # master commit. + # + # Pinned to v4.2.1, the latest tag whose own flake.nix `version` matches + # its configure.ac AC_INIT. v4.2.2..v4.3.2 left the flake version at + # "4.2.1" while bumping configure.ac, so libumem's own build assertion + # (flake.nix version != configure.ac AC_INIT) fails. Bump this ref once + # upstream syncs the two version strings again. + # + # Follow nixpkgs-unstable, the same pin the dev shell's compiler and + # libraries use, so libumem links the same glibc the dev shell does. + # Mixing glibc versions here produced a GLIBC_PRIVATE symbol-lookup + # failure when LD_PRELOAD'ing libumem into freshly built binaries. + libumem = { + url = "git+https://codeberg.org/gregburd/libumem?ref=refs/tags/v4.2.1"; + inputs.nixpkgs.follows = "nixpkgs-unstable"; + }; + }; + + outputs = { + self, + nixpkgs, + nixpkgs-unstable, + flake-utils, + libumem, + }: + flake-utils.lib.eachDefaultSystem ( + system: let + pkgs = import nixpkgs { + inherit system; + config.allowUnfree = true; + }; + pkgs-unstable = import nixpkgs-unstable { + inherit system; + config.allowUnfree = true; + }; + + libumemPkg = libumem.packages.${system}.libumem; + + shellConfig = import ./shell.nix { + inherit pkgs pkgs-unstable system libumemPkg; + }; + in { + formatter = pkgs.alejandra; + devShells = { + default = shellConfig.devShell; + gcc = shellConfig.devShell; + clang = shellConfig.clangDevShell; + }; + + packages = { + inherit (shellConfig) gdbConfig flameGraphScript pgbenchScript; + libumem = libumemPkg; + }; + + environment.localBinInPath = true; + } + ); +} diff --git a/glibc-no-fortify-warning.patch b/glibc-no-fortify-warning.patch new file mode 100644 index 0000000000000..4657a12adbcc5 --- /dev/null +++ b/glibc-no-fortify-warning.patch @@ -0,0 +1,24 @@ +From 130c231020f97e5eb878cc9fdb2bd9b186a5aa04 Mon Sep 17 00:00:00 2001 +From: Greg Burd +Date: Fri, 24 Oct 2025 11:58:24 -0400 +Subject: [PATCH] no warnings with -O0 and fortify source please + +--- + include/features.h | 1 - + 1 file changed, 1 deletion(-) + +diff --git a/include/features.h b/include/features.h +index 673c4036..a02c8a3f 100644 +--- a/include/features.h ++++ b/include/features.h +@@ -432,7 +432,6 @@ + + #if defined _FORTIFY_SOURCE && _FORTIFY_SOURCE > 0 + # if !defined __OPTIMIZE__ || __OPTIMIZE__ <= 0 +-# warning _FORTIFY_SOURCE requires compiling with optimization (-O) + # elif !__GNUC_PREREQ (4, 1) + # warning _FORTIFY_SOURCE requires GCC 4.1 or later + # elif _FORTIFY_SOURCE > 2 && (__glibc_clang_prereq (9, 0) \ +-- +2.50.1 + diff --git a/pg-aliases.sh b/pg-aliases.sh new file mode 100644 index 0000000000000..42bddff4c2730 --- /dev/null +++ b/pg-aliases.sh @@ -0,0 +1,703 @@ +# PostgreSQL Development Aliases + +# ============================================================ +# Build helpers shared by every variant. +# ============================================================ +pg_clean_for_compiler() { + local current_compiler="$(basename $CC)" + local build_dir="${1:-$PG_BUILD_DIR}" + + if [ -f "$build_dir/compile_commands.json" ]; then + local last_compiler=$(grep -o '/[^/]*/bin/[gc]cc\|/[^/]*/bin/clang' "$build_dir/compile_commands.json" | head -1 | xargs basename 2>/dev/null || echo "unknown") + + if [ "$last_compiler" != "$current_compiler" ] && [ "$last_compiler" != "unknown" ]; then + echo "Detected compiler change from $last_compiler to $current_compiler" + echo "Cleaning build directory..." + trash "$build_dir" 2>/dev/null || rm -rf "$build_dir" + mkdir -p "$build_dir" + fi + fi + + mkdir -p "$build_dir" + echo "$current_compiler" >"$build_dir/.compiler_used" +} + +# ============================================================ +# Core PostgreSQL commands (default/debug build) +# ============================================================ +alias pg-setup=' + if [ -z "$PERL_CORE_DIR" ]; then + echo "Error: Could not find perl CORE directory" >&2 + return 1 + fi + + pg_clean_for_compiler "$PG_BUILD_DIR" + + echo "=== PostgreSQL Build Configuration ===" + echo "Compiler: $CC" + echo "LLVM: $(llvm-config --version 2>/dev/null || echo disabled)" + echo "Source: $PG_SOURCE_DIR" + echo "Build: $PG_BUILD_DIR" + echo "Install: $PG_INSTALL_DIR" + echo "======================================" + + env CFLAGS="-I$PERL_CORE_DIR $CFLAGS" \ + LDFLAGS="-L$PERL_CORE_DIR -lperl $LDFLAGS" \ + meson setup $MESON_EXTRA_SETUP \ + --reconfigure \ + -Doptimization=g \ + -Ddebug=true \ + -Db_sanitize=none \ + -Db_lundef=false \ + -Dlz4=enabled \ + -Dzstd=enabled \ + -Dllvm=disabled \ + -Dplperl=enabled \ + -Dplpython=enabled \ + -Dpltcl=enabled \ + -Dlibxml=enabled \ + -Duuid=e2fs \ + -Dlibxslt=enabled \ + -Dssl=openssl \ + -Dldap=disabled \ + -Dcassert=true \ + -Dtap_tests=enabled \ + -Dinjection_points=true \ + -Ddocs_pdf=enabled \ + -Ddocs_html_style=website \ + --prefix="$PG_INSTALL_DIR" \ + "$PG_BUILD_DIR" \ + "$PG_SOURCE_DIR"' + +alias pg-compdb='compdb -p build/ list > compile_commands.json' +alias pg-build='meson compile -C "$PG_BUILD_DIR"' +alias pg-install='meson install -C "$PG_BUILD_DIR"' +alias pg-test='meson test -q --print-errorlogs -C "$PG_BUILD_DIR"' + +# Clean commands +alias pg-clean='ninja -C "$PG_BUILD_DIR" clean' +alias pg-full-clean='trash "$PG_BUILD_DIR" "$PG_INSTALL_DIR" 2>/dev/null || rm -rf "$PG_BUILD_DIR" "$PG_INSTALL_DIR"; echo "Build and install directories cleaned"' + +# Database management +alias pg-init='trash "$PG_DATA_DIR" 2>/dev/null || rm -rf "$PG_DATA_DIR"; "$PG_INSTALL_DIR/bin/initdb" --debug --no-clean "$PG_DATA_DIR"' + +alias pg-start='ulimit -c unlimited && "$PG_INSTALL_DIR/bin/postgres" -D "$PG_DATA_DIR" -k "$PG_DATA_DIR"' + +alias pg-stop='pkill -f "postgres.*-D.*$PG_DATA_DIR" || true' +alias pg-restart='pg-stop && sleep 2 && pg-start' +alias pg-status='pgrep -f "postgres.*-D.*$PG_DATA_DIR" && echo "PostgreSQL is running" || echo "PostgreSQL is not running"' + +# Client connections +alias pg-psql='"$PG_INSTALL_DIR/bin/psql" -h "$PG_DATA_DIR" postgres' +alias pg-createdb='"$PG_INSTALL_DIR/bin/createdb" -h "$PG_DATA_DIR"' +alias pg-dropdb='"$PG_INSTALL_DIR/bin/dropdb" -h "$PG_DATA_DIR"' + +# ============================================================ +# Debugger attachments +# ============================================================ +alias pg-debug-gdb='gdb -x "$GDBINIT" -x .gdbinit "$PG_INSTALL_DIR/bin/postgres"' +alias pg-debug-lldb='lldb "$PG_INSTALL_DIR/bin/postgres"' +alias pg-debug=' + if command -v gdb >/dev/null 2>&1; then + pg-debug-gdb + elif command -v lldb >/dev/null 2>&1; then + pg-debug-lldb + else + echo "No debugger available (gdb or lldb required)" + fi' + +alias pg-attach-gdb=' + PG_PID=$(pgrep -f "postgres.*-D.*$PG_DATA_DIR" | head -1) + if [ -n "$PG_PID" ]; then + echo "Attaching GDB to PostgreSQL process $PG_PID" + gdb -x "$GDBINIT" -x .gdbinit -p "$PG_PID" + else + echo "No PostgreSQL process found" + fi' + +alias pg-attach-lldb=' + PG_PID=$(pgrep -f "postgres.*-D.*$PG_DATA_DIR" | head -1) + if [ -n "$PG_PID" ]; then + echo "Attaching LLDB to PostgreSQL process $PG_PID" + lldb -p "$PG_PID" + else + echo "No PostgreSQL process found" + fi' + +alias pg-attach=' + if command -v gdb >/dev/null 2>&1; then + pg-attach-gdb + elif command -v lldb >/dev/null 2>&1; then + pg-attach-lldb + else + echo "No debugger available (gdb or lldb required)" + fi' + +# ============================================================ +# libumem (LD_PRELOAD malloc + umem/umemctl CLI + GDB/LLDB helpers) +# ============================================================ +# The nix devShell exports PG_UMEM_PRELOAD / PG_UMEM_GDB_HELPER / +# PG_UMEM_LLDB_HELPER and puts umem, umemctl and pg-umem-preload on PATH. +# These aliases wire libumem into the normal pg-start / debug flow. + +# Start the server with libumem's malloc LD_PRELOAD'ed (heap debugging). +alias pg-start-umem='ulimit -c unlimited && pg-umem-preload "$PG_INSTALL_DIR/bin/postgres" -D "$PG_DATA_DIR" -k "$PG_DATA_DIR"' + +# umemctl against the running postgres backend (default: the postmaster). +# Usage: pg-umem-ctl [args] (stats|caches|cache |whatis |leaks) +# pg-umem-ctl -p ... to target a specific backend +pg-umem-ctl() { + local pid + if [ "$1" = "-p" ]; then pid="$2"; shift 2; + else pid=$(pgrep -f "postgres.*-D.*$PG_DATA_DIR" | head -1); fi + if [ -z "$pid" ]; then echo "No PostgreSQL process found"; return 1; fi + umemctl "$pid" "$@" +} +alias pg-umem-stats='pg-umem-ctl stats' +alias pg-umem-leaks='pg-umem-ctl leaks' +alias pg-umem-caches='pg-umem-ctl caches' + +# Attach GDB with the libumem extension loaded (adds the `umem ...` commands). +# The postgres gdbinit already sources the helper, but this is explicit and +# also works when attaching to a non-postgres umem process. +alias pg-umem-gdb=' + PG_PID=$(pgrep -f "postgres.*-D.*$PG_DATA_DIR" | head -1) + if [ -n "$PG_PID" ]; then + gdb -x "$GDBINIT" -ex "source $PG_UMEM_GDB_HELPER" -p "$PG_PID" + else + echo "No PostgreSQL process found" + fi' + +# Attach LLDB with the libumem Python extension imported. +alias pg-umem-lldb=' + PG_PID=$(pgrep -f "postgres.*-D.*$PG_DATA_DIR" | head -1) + if [ -n "$PG_PID" ]; then + lldb -o "command script import $PG_UMEM_LLDB_HELPER" -p "$PG_PID" + else + echo "No PostgreSQL process found" + fi' + +# ============================================================ +# Valgrind-instrumented build and tests +# +# The valgrind build lives in a separate directory so the normal +# build stays warm. Runs use a wrapper dir that shadows `postgres` +# with a valgrind wrapper -- pg_regress finds it via PATH. +# ============================================================ +pg-build-valgrind() { + local bdir="$PG_BUILD_DIR_VALGRIND" + if [ -z "$PERL_CORE_DIR" ]; then + echo "Error: PERL_CORE_DIR is not set" >&2 + return 1 + fi + + pg_clean_for_compiler "$bdir" + + echo "=== Configuring Valgrind build in $bdir ===" + env CFLAGS="-Og -ggdb3 -fno-omit-frame-pointer -DUSE_VALGRIND -I$PERL_CORE_DIR $CFLAGS" \ + LDFLAGS="-L$PERL_CORE_DIR -lperl $LDFLAGS" \ + meson setup --reconfigure \ + -Doptimization=g \ + -Ddebug=true \ + -Dcassert=true \ + -Dtap_tests=enabled \ + -Dinjection_points=true \ + -Dllvm=disabled \ + -Dplperl=enabled -Dplpython=enabled -Dpltcl=enabled \ + -Dlz4=enabled -Dzstd=enabled \ + -Dlibxml=enabled -Dlibxslt=enabled -Dssl=openssl -Duuid=e2fs \ + -Dldap=disabled \ + --prefix="$PG_INSTALL_DIR-valgrind" \ + "$bdir" "$PG_SOURCE_DIR" || return 1 + + meson compile -C "$bdir" +} + +# Drop a wrapper directory that shadows the real binaries; `postgres` +# exec's into valgrind, everything else is a symlink. Writes to the +# supplied wrap dir and echoes its path. +_pg_make_valgrind_wrapper() { + local bindir="$1" + local wrapdir="$2" + + mkdir -p "$wrapdir" + cat >"$wrapdir/postgres" <&2 + return 1 + fi + + local tmpbin="$bdir/tmp_install$PG_INSTALL_DIR-valgrind/bin" + if [ ! -x "$tmpbin/postgres" ]; then + echo "Populating tmp_install..." + meson test -C "$bdir" tmp_install install_test_files initdb_cache >/dev/null || return 1 + fi + + local wrap + wrap=$(mktemp -d /tmp/pg-vg-wrap-XXXXXX) + _pg_make_valgrind_wrapper "$tmpbin" "$wrap" + + mkdir -p "$PG_BENCH_DIR" + echo "Valgrind logs: $PG_BENCH_DIR/valgrind-*.log" + echo "Wrapper dir: $wrap (will be removed on exit)" + echo "Expect the regress suite to take 15-45 minutes under valgrind." + + local rc=0 + (cd "$bdir" && PATH="$wrap:$PATH" meson test -t 60 --print-errorlogs regress/regress) || rc=$? + + trash "$wrap" 2>/dev/null || rm -rf "$wrap" + return "$rc" +} + +pg-valgrind-test() { + local bdir="$PG_BUILD_DIR_VALGRIND" + if [ ! -x "$bdir/src/backend/postgres" ]; then + echo "Valgrind build not found; run 'pg-build-valgrind' first." >&2 + return 1 + fi + + echo "This runs the FULL postgres test suite under valgrind." + echo "Expect many hours, and tens of GB of valgrind log output." + echo "Logs: $PG_BENCH_DIR/valgrind-*.log" + local yn + read -r -p "Continue? [y/N] " yn + case "$yn" in + y | Y | yes) ;; + *) echo "Aborted."; return 0 ;; + esac + + local tmpbin="$bdir/tmp_install$PG_INSTALL_DIR-valgrind/bin" + if [ ! -x "$tmpbin/postgres" ]; then + echo "Populating tmp_install..." + meson test -C "$bdir" tmp_install install_test_files initdb_cache >/dev/null || return 1 + fi + + local wrap + wrap=$(mktemp -d /tmp/pg-vg-wrap-XXXXXX) + _pg_make_valgrind_wrapper "$tmpbin" "$wrap" + mkdir -p "$PG_BENCH_DIR" + + local rc=0 + (cd "$bdir" && PATH="$wrap:$PATH" meson test -t 60 --print-errorlogs) || rc=$? + + trash "$wrap" 2>/dev/null || rm -rf "$wrap" + return "$rc" +} + +# ============================================================ +# AddressSanitizer / UndefinedBehaviorSanitizer build and tests +# ============================================================ +pg-build-asan() { + local bdir="$PG_BUILD_DIR_ASAN" + if [ -z "$PERL_CORE_DIR" ]; then + echo "Error: PERL_CORE_DIR is not set" >&2 + return 1 + fi + + pg_clean_for_compiler "$bdir" + + echo "=== Configuring ASan+UBSan build in $bdir ===" + env CFLAGS="-Og -ggdb3 -fno-omit-frame-pointer -fsanitize=address,undefined -fno-sanitize-recover=all -I$PERL_CORE_DIR $CFLAGS" \ + LDFLAGS="-fsanitize=address,undefined -L$PERL_CORE_DIR -lperl $LDFLAGS" \ + meson setup --reconfigure \ + -Doptimization=g \ + -Ddebug=true \ + -Dcassert=true \ + -Dtap_tests=enabled \ + -Dinjection_points=true \ + -Dllvm=disabled \ + -Dplperl=enabled -Dplpython=enabled -Dpltcl=enabled \ + -Dlz4=enabled -Dzstd=enabled \ + -Dlibxml=enabled -Dlibxslt=enabled -Dssl=openssl -Duuid=e2fs \ + -Dldap=disabled \ + --prefix="$PG_INSTALL_DIR-asan" \ + "$bdir" "$PG_SOURCE_DIR" || return 1 + + meson compile -C "$bdir" +} + +pg-asan-regress() { + local bdir="$PG_BUILD_DIR_ASAN" + if [ ! -x "$bdir/src/backend/postgres" ]; then + echo "ASan build not found; run 'pg-build-asan' first." >&2 + return 1 + fi + + # halt_on_error=0 lets regress continue past the first diagnostic so + # the whole suite runs; abort_on_error=1 makes each hit fail the test. + ASAN_OPTIONS="halt_on_error=0:abort_on_error=1:detect_leaks=0:print_summary=1:print_stacktrace=1" \ + UBSAN_OPTIONS="halt_on_error=1:abort_on_error=1:print_stacktrace=1:print_summary=1" \ + meson test -t 5 --print-errorlogs -C "$bdir" regress/regress +} + +# ============================================================ +# rr (deterministic record-and-replay) +# Requires kernel.perf_event_paranoid <= 1. rr is the single most +# effective tool for postgres bugs that reproduce intermittently. +# ============================================================ +pg-rr-check() { + if ! command -v rr >/dev/null; then + echo "rr is not installed (expected in the dev shell)." >&2 + return 1 + fi + local paranoid + paranoid=$(cat /proc/sys/kernel/perf_event_paranoid 2>/dev/null || echo 99) + if [ "$paranoid" -gt 1 ]; then + echo "rr requires kernel.perf_event_paranoid <= 1; currently $paranoid" + echo "To enable (root needed):" + echo " echo 1 | sudo tee /proc/sys/kernel/perf_event_paranoid" + return 1 + fi + echo "rr ready (perf_event_paranoid=$paranoid)" +} + +pg-rr-record() { + pg-rr-check >/dev/null || { + pg-rr-check + return 1 + } + ulimit -c unlimited + rr record -- "$PG_INSTALL_DIR/bin/postgres" -D "$PG_DATA_DIR" -k "$PG_DATA_DIR" +} + +pg-rr-replay() { + rr replay "$@" +} + +# ============================================================ +# perf wrappers (parallel to the flame-graph helper) +# ============================================================ +pg-perf-record() { + local pid + pid=$(pgrep -f "postgres.*-D.*$PG_DATA_DIR" | head -1) + if [ -z "$pid" ]; then + echo "No postgres running under $PG_DATA_DIR" >&2 + return 1 + fi + mkdir -p "$PG_BENCH_DIR" + local out="$PG_BENCH_DIR/perf-$(date +%Y%m%d_%H%M%S).data" + echo "Recording to $out (Ctrl-C to stop)" + perf record -F 997 --call-graph dwarf -p "$pid" -o "$out" "$@" + echo "Saved: $out" +} + +pg-perf-report() { + local data + data=$(ls -t "$PG_BENCH_DIR"/perf-*.data 2>/dev/null | head -1) + if [ -z "$data" ]; then + echo "No perf data in $PG_BENCH_DIR" >&2 + return 1 + fi + echo "Reading $data" + perf report -i "$data" "$@" +} + +pg-perf-annotate() { + local data + data=$(ls -t "$PG_BENCH_DIR"/perf-*.data 2>/dev/null | head -1) + if [ -z "$data" ]; then + echo "No perf data in $PG_BENCH_DIR" >&2 + return 1 + fi + perf annotate -i "$data" "$@" +} + +# ============================================================ +# Single regression test / group runner. +# Runs pg_regress directly against the existing build so you skip the +# full meson-driven suite wrapper. Usage: pg-test-one boolean [name ...] +# ============================================================ +pg-test-one() { + if [ $# -eq 0 ]; then + echo "usage: pg-test-one TESTNAME [TESTNAME ...]" + echo "example: pg-test-one boolean" + return 2 + fi + local bdir="${PG_BUILD_DIR_ONE:-$PG_BUILD_DIR}" + local tmpbin="$bdir/tmp_install$PG_INSTALL_DIR/bin" + if [ ! -x "$tmpbin/postgres" ]; then + echo "Populating tmp_install..." + meson test -C "$bdir" tmp_install install_test_files initdb_cache >/dev/null || return 1 + fi + local outdir + outdir=$(mktemp -d /tmp/pg-test-one-XXXXXX) + echo "Test output: $outdir" + "$bdir/src/test/regress/pg_regress" \ + --bindir="$tmpbin" \ + --inputdir="$PG_SOURCE_DIR/src/test/regress" \ + --expecteddir="$PG_SOURCE_DIR/src/test/regress" \ + --dlpath="$bdir/src/test/regress" \ + --outputdir="$outdir" \ + --temp-instance="$outdir/tmp" \ + --port=40099 \ + "$@" +} + +# Full flame graph / benchmark aliases +alias pg-flame='pg-flame-generate' +alias pg-flame-30='pg-flame-generate 30' +alias pg-flame-60='pg-flame-generate 60' +alias pg-flame-120='pg-flame-generate 120' + +pg-flame-custom() { + local duration=${1:-30} + local output_dir=${2:-$PG_FLAME_DIR} + echo "Generating flame graph for ${duration}s, output to: $output_dir" + pg-flame-generate "$duration" "$output_dir" +} + +alias pg-bench='pg-bench-run' +alias pg-bench-quick='pg-bench-run 5 1 100 1 30 select-only' +alias pg-bench-standard='pg-bench-run 10 2 1000 10 60 tpcb-like' +alias pg-bench-heavy='pg-bench-run 50 4 5000 100 300 tpcb-like' +alias pg-bench-readonly='pg-bench-run 20 4 2000 50 120 select-only' + +pg-bench-custom() { + local clients=${1:-10} + local threads=${2:-2} + local transactions=${3:-1000} + local scale=${4:-10} + local duration=${5:-60} + local test_type=${6:-tpcb-like} + + echo "Running custom benchmark:" + echo " Clients: $clients, Threads: $threads" + echo " Transactions: $transactions, Scale: $scale" + echo " Duration: ${duration}s, Type: $test_type" + + pg-bench-run "$clients" "$threads" "$transactions" "$scale" "$duration" "$test_type" +} + +pg-bench-flame() { + local duration=${1:-60} + local clients=${2:-10} + local scale=${3:-10} + + echo "Running benchmark with flame graph generation" + echo "Duration: ${duration}s, Clients: $clients, Scale: $scale" + + pg-bench-run "$clients" 2 1000 "$scale" "$duration" tpcb-like & + local bench_pid=$! + + sleep 5 + + local flame_duration=$((duration - 10)) + if [ $flame_duration -gt 10 ]; then + pg-flame-generate "$flame_duration" & + local flame_pid=$! + fi + + wait $bench_pid + if [ -n "${flame_pid:-}" ]; then + wait $flame_pid + fi + + echo "Benchmark and flame graph generation completed" +} + +# Live monitoring +alias pg-perf='perf top -p $(pgrep -f "postgres.*-D.*$PG_DATA_DIR" | head -1)' +alias pg-htop='htop -p $(pgrep -f "postgres.*-D.*$PG_DATA_DIR" | tr "\n" "," | sed "s/,$//")' + +pg-stats() { + local duration=${1:-30} + echo "Collecting system stats for ${duration}s..." + + iostat -x 1 "$duration" >"$PG_BENCH_DIR/iostat_$(date +%Y%m%d_%H%M%S).log" & + vmstat 1 "$duration" >"$PG_BENCH_DIR/vmstat_$(date +%Y%m%d_%H%M%S).log" & + + wait + echo "System stats saved to $PG_BENCH_DIR" +} + +# ============================================================ +# Code quality helpers +# ============================================================ +pg-format() { + local since=${1:-HEAD} + + if [ ! -f "$PG_SOURCE_DIR/src/tools/pgindent/pgindent" ]; then + echo "Error: pgindent not found at $PG_SOURCE_DIR/src/tools/pgindent/pgindent" + else + + modified_files=$(git diff --name-only "${since}" | grep -E "\.c$|\.h$") + + if [ -z "$modified_files" ]; then + echo "No modified .c or .h files found" + else + + echo "Formatting modified files with pgindent:" + for file in $modified_files; do + if [ -f "$file" ]; then + echo " Formatting: $file" + "$PG_SOURCE_DIR/src/tools/pgindent/pgindent" "$file" + else + echo " Warning: File not found: $file" + fi + done + + echo "Checking files for whitespace:" + git diff --check "${since}" + fi + fi +} + +pg-tidy() { + local since=${1:-HEAD} + local files + files=$(git diff --name-only "$since" | grep -E "\.(c|h)$") + if [ -z "$files" ]; then + echo "No modified .c or .h files." + return 0 + fi + for f in $files; do + [ -f "$f" ] || continue + echo "clang-tidy: $f" + clang-tidy -p "$PG_BUILD_DIR" "$f" 2>&1 | head -50 + done +} + +pg-spell() { + local since=${1:-HEAD} + local files=$(git diff --name-only "$since" | grep -E '\.(c|h|sgml|md)$') + if [ -z "$files" ]; then + echo "No .c/.h/.sgml/.md files changed since $since" + return 0 + fi + for f in $files; do + [ -f "$f" ] || continue + case "$f" in + *.c | *.h) + grep -nE '^\s*(/\*|\*|//)' "$f" | codespell --stdin-single-line - 2>/dev/null \ + && echo " $f: ok" || true + ;; + *.sgml | *.md) + codespell "$f" || true + ;; + esac + done +} + +# ============================================================ +# Core dump one-shots (one-time, requires root). kernel.core_pattern +# is a system-wide sysctl -- we don't touch it on every shell entry. +# ============================================================ +pg-cores-status() { + echo "ulimit -c: $(ulimit -c)" + echo "kernel.core_pattern: $(cat /proc/sys/kernel/core_pattern 2>/dev/null || echo unreadable)" + echo "cwd: $(pwd)" +} + +pg-enable-cores() { + ulimit -c unlimited + if ! [ -w /proc/sys/kernel/core_pattern ]; then + echo "Setting kernel.core_pattern (requires sudo)..." + echo "core.%p" | sudo tee /proc/sys/kernel/core_pattern >/dev/null || { + echo "Failed to write /proc/sys/kernel/core_pattern" >&2 + return 1 + } + else + echo "core.%p" >/proc/sys/kernel/core_pattern + fi + pg-cores-status +} + +pg-disable-cores() { + ulimit -c 0 + if ! [ -w /proc/sys/kernel/core_pattern ]; then + echo "Restoring kernel.core_pattern to 'core' (requires sudo)..." + echo "core" | sudo tee /proc/sys/kernel/core_pattern >/dev/null || { + echo "Failed to restore /proc/sys/kernel/core_pattern" >&2 + return 1 + } + else + echo "core" >/proc/sys/kernel/core_pattern + fi + pg-cores-status +} + +# ============================================================ +# Logs and results +# ============================================================ +alias pg-log='tail -f "$PG_DATA_DIR/log/postgresql-$(date +%Y-%m-%d).log" 2>/dev/null || echo "No log file found"' +alias pg-log-errors='grep -i error "$PG_DATA_DIR/log/"*.log 2>/dev/null || echo "No error logs found"' + +alias pg-build-log='cat "$PG_BUILD_DIR/meson-logs/meson-log.txt"' +alias pg-build-errors='grep -i error "$PG_BUILD_DIR/meson-logs/meson-log.txt" 2>/dev/null || echo "No build errors found"' + +alias pg-bench-results='ls -la "$PG_BENCH_DIR" && echo "Latest results:" && tail -20 "$PG_BENCH_DIR"/results_*.txt 2>/dev/null | tail -20' +alias pg-flame-results='ls -la "$PG_FLAME_DIR" && echo "Open flame graphs with: firefox $PG_FLAME_DIR/*.svg"' + +pg-clean-results() { + local days=${1:-7} + echo "Cleaning benchmark and flame graph results older than $days days..." + find "$PG_BENCH_DIR" -type f -mtime +$days -delete 2>/dev/null || true + find "$PG_FLAME_DIR" -type f -mtime +$days -delete 2>/dev/null || true + echo "Cleanup completed" +} + +# ============================================================ +# Info +# ============================================================ +alias pg-info=' + echo "=== PostgreSQL Development Environment ===" + echo "Source: $PG_SOURCE_DIR" + echo "Build (default): $PG_BUILD_DIR" + echo "Build (valgrind):$PG_BUILD_DIR_VALGRIND" + echo "Build (asan): $PG_BUILD_DIR_ASAN" + echo "Install: $PG_INSTALL_DIR" + echo "Data: $PG_DATA_DIR" + echo "Benchmarks: $PG_BENCH_DIR" + echo "Flame graphs: $PG_FLAME_DIR" + echo "Compiler: $CC" + echo "" + echo "Available commands:" + echo " Setup/build: pg-setup, pg-build, pg-install" + echo " Database: pg-init, pg-start, pg-stop, pg-psql" + echo " Tests: pg-test, pg-test-one NAME" + echo " Valgrind: pg-build-valgrind, pg-valgrind-regress, pg-valgrind-test" + echo " ASan/UBSan: pg-build-asan, pg-asan-regress" + echo " Debug: pg-debug, pg-attach" + echo " libumem: pg-start-umem, pg-umem-ctl, pg-umem-stats/leaks/caches, pg-umem-gdb/lldb" + echo " Record/replay: pg-rr-check, pg-rr-record, pg-rr-replay" + echo " Perf: pg-perf-record, pg-perf-report, pg-perf-annotate, pg-perf" + echo " Flame graphs: pg-flame, pg-flame-30, pg-flame-60, pg-flame-custom" + echo " Benchmarks: pg-bench-quick, pg-bench-standard, pg-bench-heavy" + echo " Combined: pg-bench-flame" + echo " Results: pg-bench-results, pg-flame-results" + echo " Logs: pg-log, pg-build-log" + echo " Clean: pg-clean, pg-full-clean, pg-clean-results" + echo " Code quality: pg-format, pg-tidy, pg-spell" + echo " Cores: pg-enable-cores, pg-disable-cores, pg-cores-status" + echo "=========================================="' + +echo "PostgreSQL aliases loaded. Run 'pg-info' for available commands." diff --git a/shell.nix b/shell.nix new file mode 100644 index 0000000000000..93cb0dbb7e461 --- /dev/null +++ b/shell.nix @@ -0,0 +1,747 @@ +{ + pkgs, + pkgs-unstable, + system, + libumemPkg, +}: let + # Create a patched glibc only for the dev shell. + # + # Glibc's features.h emits a `-Wcpp` diagnostic when _FORTIFY_SOURCE is + # defined without an optimization level. Meson's dependency probes + # (notably the libcurl thread-safety check) compile small snippets with + # `-O0 -Werror` under the nixpkgs hardening defaults, which turns that cpp + # warning into a hard error and breaks reconfigure. The patch drops the + # warning. It is scoped to this dev shell only and never leaks into system + # glibc or release builds. + # Patch glibc's features.h to drop a -Wcpp warning. + # + # Glibc's features.h emits a `-Wcpp` diagnostic when _FORTIFY_SOURCE is + # defined without an optimization level. Meson's dependency probes + # (notably the libcurl thread-safety check) compile small snippets with + # `-O0 -Werror` under the nixpkgs hardening defaults, which turns that cpp + # warning into a hard error and breaks reconfigure. The patch drops the + # warning. It is scoped to this dev shell only and never leaks into system + # glibc or release builds. Pinned to the SAME nixpkgs as the compiler + # (pkgs-unstable, glibc 2.42) so the glibc this adds to the link matches the + # one gccPkg was built against; a stable-pin glibc here (2.40) alongside an + # unstable gcc16 (2.42) made binaries load a 2.40 libc.so.6 at runtime and + # fail with "undefined symbol: __nptl_change_stack_perm". + patchedGlibc = pkgs-unstable.glibc.overrideAttrs (oldAttrs: { + patches = + (oldAttrs.patches or []) + ++ [ + ./glibc-no-fortify-warning.patch + ]; + }); + + # Modern toolchain, pinned to nixpkgs-unstable. + gccPkg = pkgs-unstable.gcc16; + gdbPkg = pkgs-unstable.gdb; + llvmPkgs = pkgs-unstable.llvmPackages_22; + + # libumem debugger helpers (installed by the flake package under + # $out/share/umem/debugger/{gdb,lldb}). + umemGdbHelper = "${libumemPkg}/share/umem/debugger/gdb/umem_gdb.py"; + umemLldbHelper = "${libumemPkg}/share/umem/debugger/lldb/umem_lldb.py"; + umemPreload = "${libumemPkg}/lib/libumem_malloc.so"; + + # Configuration constants + config = { + pgSourceDir = "$PWD"; + pgBuildDir = "$PWD/build"; + pgBuildDirValgrind = "$PWD/build-valgrind"; + pgBuildDirAsan = "$PWD/build-asan"; + pgInstallDir = "$PWD/install"; + pgDataDir = "/tmp/test-db-$(basename $PWD)"; + pgBenchDir = "/tmp/pgbench-results-$(basename $PWD)"; + pgFlameDir = "/tmp/flame-graphs-$(basename $PWD)"; + }; + + # PostgreSQL build + development dependencies (glibc target). + # + # Built from pkgs-unstable so their glibc (2.42) matches the compiler + # (gccPkg = pkgs-unstable.gcc16, also glibc 2.42). If these came from the + # stable `pkgs` (glibc 2.40) their -dev outputs would leak a 2.40 -L into + # NIX_LDFLAGS, and a 2.40 libc.so.6 would load ahead of the 2.42 the + # compiler links, killing every binary with "undefined symbol: + # __nptl_change_stack_perm". + postgreSQLDeps = with pkgs-unstable; + [ + # Build system (always use host tools) + pkgs-unstable.meson + pkgs-unstable.ninja + pkg-config + autoconf + git + which + binutils + gnumake + mold # fast linker, big wins on large postgres links + + # Parser/lexer tools + bison + flex + + gettext # msgfmt/xgettext for NLS (translation) builds + + # Perl with required packages + (perl.withPackages (ps: with ps; [IPCRun])) + + # Documentation + docbook_xml_dtd_45 + docbook-xsl-nons + libxslt + libxml2 + fop + + # Development tools (always use host tools) + coreutils + shellcheck + ripgrep + valgrind + curl + uv + pylint + black + lcov + strace + ltrace + perf-tools + perf # was linuxPackages.perf; renamed to top-level `perf` in nixpkgs-unstable + flamegraph + bpftrace # kernel-level tracing (probes, uprobes) + rr # record-and-replay deterministic debugger + htop + iotop + sysstat + ccache + cppcheck + compdb + + # Spell checking + aspell + aspellDicts.en + codespell + + # GCC 16 + GDB (nixpkgs-unstable) + gccPkg + gdbPkg + + # LLVM 22 toolchain + llvmPkgs.llvm + llvmPkgs.llvm.dev + llvmPkgs.clang-tools + llvmPkgs.lldb + + # libumem: LD_PRELOAD malloc + umem/umemctl CLI + debugger helpers + libumemPkg + + # Language support + (python3.withPackages (ps: with ps; [requests browser-cookie3])) + tcl + ] + ++ [ + # Glibc target libraries + readline + zlib + openssl + icu + lz4 + zstd + libuuid + libkrb5 + linux-pam + libxcrypt + numactl + openldap + liburing + libselinux + patchedGlibc + patchedGlibc.dev + ]; + + # GDB configuration for PostgreSQL debugging + gdbConfig = pkgs.writeText "gdbinit-postgres" '' + # PostgreSQL-specific GDB configuration + + # Pretty-print PostgreSQL data structures + define print_node + if $arg0 + printf "Node type: %s\n", nodeTagNames[$arg0->type] + print *$arg0 + else + printf "NULL node\n" + end + end + document print_node + Print a PostgreSQL Node with type information + Usage: print_node + end + + define print_list + set $list = (List*)$arg0 + if $list + printf "List length: %d\n", $list->length + set $cell = $list->head + set $i = 0 + while $cell && $i < $list->length + printf " [%d]: ", $i + print_node $cell->data.ptr_value + set $cell = $cell->next + set $i = $i + 1 + end + else + printf "NULL list\n" + end + end + document print_list + Print a PostgreSQL List structure + Usage: print_list + end + + define print_query + set $query = (Query*)$arg0 + if $query + printf "Query type: %d, command type: %d\n", $query->querySource, $query->commandType + print *$query + else + printf "NULL query\n" + end + end + document print_query + Print a PostgreSQL Query structure + Usage: print_query + end + + define print_relcache + set $rel = (Relation)$arg0 + if $rel + printf "Relation: %s.%s (OID: %u)\n", $rel->rd_rel->relnamespace, $rel->rd_rel->relname.data, $rel->rd_id + printf " natts: %d, relkind: %c\n", $rel->rd_rel->relnatts, $rel->rd_rel->relkind + else + printf "NULL relation\n" + end + end + document print_relcache + Print relation cache entry information + Usage: print_relcache + end + + define print_tupdesc + set $desc = (TupleDesc)$arg0 + if $desc + printf "TupleDesc: %d attributes\n", $desc->natts + set $i = 0 + while $i < $desc->natts + set $attr = $desc->attrs[$i] + printf " [%d]: %s (type: %u, len: %d)\n", $i, $attr->attname.data, $attr->atttypid, $attr->attlen + set $i = $i + 1 + end + else + printf "NULL tuple descriptor\n" + end + end + document print_tupdesc + Print tuple descriptor information + Usage: print_tupdesc + end + + define print_slot + set $slot = (TupleTableSlot*)$arg0 + if $slot + printf "TupleTableSlot: %s\n", $slot->tts_ops->name + printf " empty: %d, shouldFree: %d\n", $slot->tts_empty, $slot->tts_shouldFree + if $slot->tts_tupleDescriptor + print_tupdesc $slot->tts_tupleDescriptor + end + else + printf "NULL slot\n" + end + end + document print_slot + Print tuple table slot information + Usage: print_slot + end + + # Memory context debugging + define print_mcxt + set $context = (MemoryContext)$arg0 + if $context + printf "MemoryContext: %s\n", $context->name + printf " type: %s, parent: %p\n", $context->methods->name, $context->parent + printf " total: %zu, free: %zu\n", $context->mem_allocated, $context->freep - $context->freeptr + else + printf "NULL memory context\n" + end + end + document print_mcxt + Print memory context information + Usage: print_mcxt + end + + # Process debugging + define print_proc + set $proc = (PGPROC*)$arg0 + if $proc + printf "PGPROC: pid=%d, database=%u\n", $proc->pid, $proc->databaseId + printf " waiting: %d, waitStatus: %d\n", $proc->waiting, $proc->waitStatus + else + printf "NULL process\n" + end + end + document print_proc + Print process information + Usage: print_proc + end + + # Set useful defaults + set print pretty on + set print object on + set print static-members off + set print vtbl on + set print demangle on + set demangle-style gnu-v3 + set print sevenbit-strings off + set history save on + set history size 1000 + set history filename ~/.gdb_history_postgres + + # Common breakpoints for PostgreSQL debugging + define pg_break_common + break elog + break errfinish + break ExceptionalCondition + break ProcessInterrupts + end + document pg_break_common + Set common PostgreSQL debugging breakpoints + end + + # libumem GDB helpers (umem heap/event inspection). Loaded if present; + # provides the 'umem' command family (umem break, umem events, ...). + python + try: + gdb.execute("source ${umemGdbHelper}") + except Exception as e: + pass + end + + printf "PostgreSQL GDB configuration loaded.\n" + printf "Available commands: print_node, print_list, print_query, print_relcache,\n" + printf " print_tupdesc, print_slot, print_mcxt, print_proc, pg_break_common\n" + ''; + + # Flame graph generation script + flameGraphScript = pkgs.writeScriptBin "pg-flame-generate" '' + #!${pkgs.bash}/bin/bash + set -euo pipefail + + DURATION=''${1:-30} + OUTPUT_DIR=''${2:-${config.pgFlameDir}} + TIMESTAMP=$(date +%Y%m%d_%H%M%S) + + mkdir -p "$OUTPUT_DIR" + + echo "Generating flame graph for PostgreSQL (duration: ''${DURATION}s)" + + # Find PostgreSQL processes + PG_PIDS=$(pgrep -f "postgres.*-D.*${config.pgDataDir}" || true) + + if [ -z "$PG_PIDS" ]; then + echo "Error: No PostgreSQL processes found" + exit 1 + fi + + echo "Found PostgreSQL processes: $PG_PIDS" + + # Record perf data + PERF_DATA="$OUTPUT_DIR/perf_$TIMESTAMP.data" + echo "Recording perf data to $PERF_DATA" + + ${pkgs.linuxPackages.perf}/bin/perf record \ + -F 997 \ + -g \ + --call-graph dwarf \ + -p "$(echo $PG_PIDS | tr ' ' ',')" \ + -o "$PERF_DATA" \ + sleep "$DURATION" + + # Generate flame graph + FLAME_SVG="$OUTPUT_DIR/postgres_flame_$TIMESTAMP.svg" + echo "Generating flame graph: $FLAME_SVG" + + ${pkgs.linuxPackages.perf}/bin/perf script -i "$PERF_DATA" | \ + ${pkgs.flamegraph}/bin/stackcollapse-perf.pl | \ + ${pkgs.flamegraph}/bin/flamegraph.pl \ + --title "PostgreSQL Flame Graph ($TIMESTAMP)" \ + --width 1200 \ + --height 800 \ + > "$FLAME_SVG" + + echo "Flame graph generated: $FLAME_SVG" + echo "Perf data saved: $PERF_DATA" + + # Generate summary report + REPORT="$OUTPUT_DIR/report_$TIMESTAMP.txt" + echo "Generating performance report: $REPORT" + + { + echo "PostgreSQL Performance Analysis Report" + echo "Generated: $(date)" + echo "Duration: ''${DURATION}s" + echo "Processes: $PG_PIDS" + echo "" + echo "=== Top Functions ===" + ${pkgs.linuxPackages.perf}/bin/perf report -i "$PERF_DATA" --stdio --sort comm,dso,symbol | head -50 + echo "" + echo "=== Call Graph ===" + ${pkgs.linuxPackages.perf}/bin/perf report -i "$PERF_DATA" --stdio -g --sort comm,dso,symbol | head -100 + } > "$REPORT" + + echo "Report generated: $REPORT" + echo "" + echo "Files created:" + echo " Flame graph: $FLAME_SVG" + echo " Perf data: $PERF_DATA" + echo " Report: $REPORT" + ''; + + # pgbench wrapper script + pgbenchScript = pkgs.writeScriptBin "pg-bench-run" '' + #!${pkgs.bash}/bin/bash + set -euo pipefail + + # Default parameters + CLIENTS=''${1:-10} + THREADS=''${2:-2} + TRANSACTIONS=''${3:-1000} + SCALE=''${4:-10} + DURATION=''${5:-60} + TEST_TYPE=''${6:-tpcb-like} + + OUTPUT_DIR="${config.pgBenchDir}" + TIMESTAMP=$(date +%Y%m%d_%H%M%S) + + mkdir -p "$OUTPUT_DIR" + + echo "=== PostgreSQL Benchmark Configuration ===" + echo "Clients: $CLIENTS" + echo "Threads: $THREADS" + echo "Transactions: $TRANSACTIONS" + echo "Scale factor: $SCALE" + echo "Duration: ''${DURATION}s" + echo "Test type: $TEST_TYPE" + echo "Output directory: $OUTPUT_DIR" + echo "============================================" + + # Check if PostgreSQL is running + if ! pgrep -f "postgres.*-D.*${config.pgDataDir}" >/dev/null; then + echo "Error: PostgreSQL is not running. Start it with 'pg-start'" + exit 1 + fi + + PGBENCH="${config.pgInstallDir}/bin/pgbench" + PSQL="${config.pgInstallDir}/bin/psql" + CREATEDB="${config.pgInstallDir}/bin/createdb" + DROPDB="${config.pgInstallDir}/bin/dropdb" + + DB_NAME="pgbench_test_$TIMESTAMP" + RESULTS_FILE="$OUTPUT_DIR/results_$TIMESTAMP.txt" + LOG_FILE="$OUTPUT_DIR/pgbench_$TIMESTAMP.log" + + echo "Creating test database: $DB_NAME" + "$CREATEDB" -h "${config.pgDataDir}" "$DB_NAME" || { + echo "Failed to create database" + exit 1 + } + + # Initialize pgbench tables + echo "Initializing pgbench tables (scale factor: $SCALE)" + "$PGBENCH" -h "${config.pgDataDir}" -i -s "$SCALE" "$DB_NAME" || { + echo "Failed to initialize pgbench tables" + "$DROPDB" -h "${config.pgDataDir}" "$DB_NAME" 2>/dev/null || true + exit 1 + } + + # Run benchmark based on test type + echo "Running benchmark..." + + case "$TEST_TYPE" in + "tpcb-like"|"default") + BENCH_ARGS="" + ;; + "select-only") + BENCH_ARGS="-S" + ;; + "simple-update") + BENCH_ARGS="-N" + ;; + "read-write") + BENCH_ARGS="-b select-only@70 -b tpcb-like@30" + ;; + *) + echo "Unknown test type: $TEST_TYPE" + echo "Available types: tpcb-like, select-only, simple-update, read-write" + "$DROPDB" -h "${config.pgDataDir}" "$DB_NAME" 2>/dev/null || true + exit 1 + ;; + esac + + { + echo "PostgreSQL Benchmark Results" + echo "Generated: $(date)" + echo "Test type: $TEST_TYPE" + echo "Clients: $CLIENTS, Threads: $THREADS" + echo "Transactions: $TRANSACTIONS, Duration: ''${DURATION}s" + echo "Scale factor: $SCALE" + echo "Database: $DB_NAME" + echo "" + echo "=== System Information ===" + echo "CPU: $(nproc) cores" + echo "Memory: $(free -h | grep '^Mem:' | awk '{print $2}')" + echo "Compiler: $CC" + echo "PostgreSQL version: $("$PSQL" --no-psqlrc -h "${config.pgDataDir}" -d "$DB_NAME" -t -c "SELECT version();" | head -1)" + echo "" + echo "=== Benchmark Results ===" + } > "$RESULTS_FILE" + + # Run the actual benchmark + "$PGBENCH" \ + -h "${config.pgDataDir}" \ + -c "$CLIENTS" \ + -j "$THREADS" \ + -T "$DURATION" \ + -P 5 \ + --log \ + --log-prefix="$OUTPUT_DIR/pgbench_$TIMESTAMP" \ + $BENCH_ARGS \ + "$DB_NAME" 2>&1 | tee -a "$RESULTS_FILE" + + # Collect additional statistics + { + echo "" + echo "=== Database Statistics ===" + "$PSQL" --no-psqlrc -h "${config.pgDataDir}" -d "$DB_NAME" -c " + SELECT + schemaname, + relname, + n_tup_ins as inserts, + n_tup_upd as updates, + n_tup_del as deletes, + n_live_tup as live_tuples, + n_dead_tup as dead_tuples + FROM pg_stat_user_tables; + " + + echo "" + echo "=== Index Statistics ===" + "$PSQL" --no-psqlrc -h "${config.pgDataDir}" -d "$DB_NAME" -c " + SELECT + schemaname, + relname, + indexrelname, + idx_scan, + idx_tup_read, + idx_tup_fetch + FROM pg_stat_user_indexes; + " + } >> "$RESULTS_FILE" + + # Clean up + echo "Cleaning up test database: $DB_NAME" + "$DROPDB" -h "${config.pgDataDir}" "$DB_NAME" 2>/dev/null || true + + echo "" + echo "Benchmark completed!" + echo "Results saved to: $RESULTS_FILE" + echo "Transaction logs: $OUTPUT_DIR/pgbench_$TIMESTAMP*" + + # Show summary + echo "" + echo "=== Quick Summary ===" + grep -E "(tps|latency)" "$RESULTS_FILE" | tail -5 + ''; + + # LD_PRELOAD libumem's malloc into a command: pg-umem-preload + # A script (not a shell function) so it survives subshells and non-login + # invocations. Preloads $out/lib/libumem_malloc.so ahead of any existing + # LD_PRELOAD. + umemPreloadScript = pkgs.writeScriptBin "pg-umem-preload" '' + #!${pkgs.bash}/bin/bash + if [ $# -eq 0 ]; then + echo "usage: pg-umem-preload [args...]" >&2 + echo " runs with libumem_malloc.so LD_PRELOAD'ed" >&2 + exit 2 + fi + export LD_PRELOAD="${umemPreload}''${LD_PRELOAD:+:$LD_PRELOAD}" + exec "$@" + ''; + + # Shared shellHook fragments. Each devShell prepends its own compiler/CFLAGS + # block, then appends the common tail via ${commonHookTail variant}. + commonHookHead = icon: '' + # History configuration + export HISTFILE=.history + export HISTSIZE=1000000 + export HISTFILESIZE=1000000 + + # Clean environment + unset LD_LIBRARY_PATH LD_PRELOAD LIBRARY_PATH C_INCLUDE_PATH CPLUS_INCLUDE_PATH + + # Essential tools in PATH + export PATH="${pkgs.which}/bin:${pkgs.coreutils}/bin:$PATH" + export PS1="$(echo -e '\u${icon}') {\[$(tput sgr0)\]\[\033[38;5;228m\]\w\[$(tput sgr0)\]\[\033[38;5;15m\]} ($(git rev-parse --abbrev-ref HEAD)) \\$ \[$(tput sgr0)\]" + + # Ccache configuration + export PATH=${pkgs.ccache}/bin:$PATH + export CCACHE_COMPILERCHECK=content + # Loosen a few rules so ccache hits across rebuilds with touched headers. + export CCACHE_SLOPPINESS=pch_defines,time_macros,include_file_mtime,include_file_ctime + export CCACHE_DIR=$HOME/.ccache/pg/$(basename $PWD) + mkdir -p "$CCACHE_DIR" + + # Development tools in PATH + export PATH=${pkgs.clang-tools}/bin:$PATH + export PATH=${pkgs.cppcheck}/bin:$PATH + ''; + + # Tail shared by every devShell: PG env vars, GDB, tool PATH, per-process + # setup and alias load. Kernel core_pattern is NOT touched here -- + # run 'pg-enable-cores' explicitly if you need per-PID cores in CWD. + commonHookTail = label: '' + # PostgreSQL environment + export PG_SOURCE_DIR="${config.pgSourceDir}" + export PG_BUILD_DIR="${config.pgBuildDir}" + export PG_BUILD_DIR_VALGRIND="${config.pgBuildDirValgrind}" + export PG_BUILD_DIR_ASAN="${config.pgBuildDirAsan}" + export PG_INSTALL_DIR="${config.pgInstallDir}" + export PG_DATA_DIR="${config.pgDataDir}" + export PG_BENCH_DIR="${config.pgBenchDir}" + export PG_FLAME_DIR="${config.pgFlameDir}" + export PERL_CORE_DIR=$(find ${pkgs-unstable.perl} -maxdepth 5 -path "*/CORE" -type d) + + # GDB configuration + export GDBINIT="${gdbConfig}" + + # libumem: LD_PRELOAD malloc, the umem/umemctl CLI, and debugger helpers. + # The CLI and 'pg-umem-preload' are already on PATH (buildInputs). Export + # the preload object and helper paths; do NOT preload by default -- opt in + # per-command with 'pg-umem-preload ' or export + # LD_PRELOAD="$PG_UMEM_PRELOAD". + export PG_UMEM_PRELOAD="${umemPreload}" + export PG_UMEM_GDB_HELPER="${umemGdbHelper}" + export PG_UMEM_LLDB_HELPER="${umemLldbHelper}" + + # Performance tools in PATH + export PATH="${flameGraphScript}/bin:${pgbenchScript}/bin:${umemPreloadScript}/bin:$PATH" + + # Create output directories + mkdir -p "$PG_BENCH_DIR" "$PG_FLAME_DIR" + + # Per-process core dump size limit. Kernel core_pattern is NOT + # touched here -- run 'pg-enable-cores' explicitly when you need + # per-PID cores in CWD. + ulimit -c unlimited + + # Local git excludes + git config core.excludesFile .local-gitignore 2>/dev/null || true + + # Load PostgreSQL development aliases + if [ -f ./pg-aliases.sh ]; then + source ./pg-aliases.sh + else + echo "Warning: pg-aliases.sh not found in current directory" + fi + + echo "" + echo "PostgreSQL Development Environment Ready (${label})" + echo "Run 'pg-info' for available commands" + echo "libumem: umem/umemctl on PATH; 'pg-umem-preload ' to LD_PRELOAD libumem_malloc" + ''; + + # Development shell (GCC 16 + glibc) + # + # Build the shell with the SAME nixpkgs pin as the compiler (pkgs-unstable), + # so the glibc that mkShell leaks into NIX_LDFLAGS / the cc wrapper matches + # the glibc gccPkg (pkgs-unstable.gcc16) was built against. Using + # pkgs.mkShell (stable glibc 2.40) with an unstable gcc16 (glibc 2.42) put a + # 2.40 libc.so.6 ahead of 2.42 at runtime, so every compiled binary died + # with "undefined symbol: __nptl_change_stack_perm, version GLIBC_PRIVATE" + # and meson's compiler sanity check failed. + devShell = pkgs-unstable.mkShell { + name = "postgresql-dev"; + buildInputs = + postgreSQLDeps + ++ [ + flameGraphScript + pgbenchScript + umemPreloadScript + ]; + + shellHook = + (commonHookHead "f121") + + '' + # LLVM configuration + export LLVM_CONFIG="${llvmPkgs.llvm}/bin/llvm-config" + export PATH="${llvmPkgs.llvm}/bin:$PATH" + export PKG_CONFIG_PATH="${llvmPkgs.llvm.dev}/lib/pkgconfig:$PKG_CONFIG_PATH" + export LLVM_DIR="${llvmPkgs.llvm.dev}/lib/cmake/llvm" + export LLVM_ROOT="${llvmPkgs.llvm}" + + # PostgreSQL Development CFLAGS + export CFLAGS="" + export CXXFLAGS="" + + # Python UV + UV_PYTHON_DOWNLOADS=never + + # GCC 16 (default compiler) + export CC="${gccPkg}/bin/gcc" + export CXX="${gccPkg}/bin/g++" + + echo "Environment configured:" + echo " Compiler: $CC ($($CC -dumpversion 2>/dev/null))" + echo " libc: glibc" + echo " LLVM: $(llvm-config --version 2>/dev/null || echo 'not available')" + '' + + (commonHookTail "GCC 16 + glibc"); + }; + + # Clang 22 + glibc variant + clangDevShell = pkgs-unstable.mkShell { + name = "postgresql-clang-glibc"; + buildInputs = + postgreSQLDeps + ++ [ + llvmPkgs.clang + llvmPkgs.lld + llvmPkgs.compiler-rt + flameGraphScript + pgbenchScript + umemPreloadScript + ]; + + shellHook = + (commonHookHead "f121") + + '' + # LLVM configuration + export LLVM_CONFIG="${llvmPkgs.llvm}/bin/llvm-config" + export PATH="${llvmPkgs.llvm}/bin:$PATH" + export PKG_CONFIG_PATH="${llvmPkgs.llvm.dev}/lib/pkgconfig:$PKG_CONFIG_PATH" + export LLVM_DIR="${llvmPkgs.llvm.dev}/lib/cmake/llvm" + export LLVM_ROOT="${llvmPkgs.llvm}" + + # Clang 22 + glibc + export CC="${llvmPkgs.clang}/bin/clang" + export CXX="${llvmPkgs.clang}/bin/clang++" + + echo "Environment configured:" + echo " Compiler: $CC ($($CC -dumpversion 2>/dev/null))" + echo " libc: glibc" + echo " LLVM: $(llvm-config --version 2>/dev/null || echo 'not available')" + '' + + (commonHookTail "Clang 22 + glibc"); + }; +in { + inherit devShell clangDevShell gdbConfig flameGraphScript pgbenchScript; +} diff --git a/src/backend/access/common/reloptions.c b/src/backend/access/common/reloptions.c index ea9a04179090e..be1fcd9a15b21 100644 --- a/src/backend/access/common/reloptions.c +++ b/src/backend/access/common/reloptions.c @@ -153,6 +153,16 @@ static relopt_bool boolRelOpts[] = }, true }, + { + { + "prefix_compression", + "Enables leaf key prefix compression for this btree index", + RELOPT_KIND_BTREE, + ShareUpdateExclusiveLock /* since it applies only to later + * whole-page writes */ + }, + false + }, /* list terminator */ {{NULL}} }; diff --git a/src/backend/access/nbtree/Makefile b/src/backend/access/nbtree/Makefile index 0daf640af96c7..0044d77f548d2 100644 --- a/src/backend/access/nbtree/Makefile +++ b/src/backend/access/nbtree/Makefile @@ -18,6 +18,7 @@ OBJS = \ nbtinsert.o \ nbtpage.o \ nbtpreprocesskeys.o \ + nbtprefix.o \ nbtreadpage.o \ nbtree.o \ nbtsearch.o \ diff --git a/src/backend/access/nbtree/README b/src/backend/access/nbtree/README index f3867547691d0..55c6061eb9d86 100644 --- a/src/backend/access/nbtree/README +++ b/src/backend/access/nbtree/README @@ -1081,3 +1081,127 @@ item is irrelevant, and need not be stored at all. This arrangement corresponds to the fact that an L&Y non-leaf page has one more pointer than key. Suffix truncation's negative infinity attributes behave in the same way. + +Notes about leaf key prefix compression +---------------------------------------- + +With the prefix_compression storage parameter (default off) a leaf page may +store the leading bytes that a run of its data tuples share just once, in a +per-page directory, and record only each tuple's unshared remainder. This +shrinks indexes whose keys share long leading bytes: URLs, jsonb paths, +zero-padded codes, multi-column keys with low-cardinality leading columns. +Like deduplication, it alters the physical representation of tuples without +changing the logical contents of the index, and comparisons always operate on +the reconstructed original values, so every collation and operator class is +unaffected. + +Sharing is decided by equality of stored bytes, never by the opclass notion +of equality. That is what makes it sound for every column type, including +types whose equal values can have different representations (numeric 1.0 and +1.00): only bytes that are already identical are shared, so an index-only +scan gets back exactly the bytes that were stored, and no equalimage support +function is needed. Deduplication needs equalimage because it merges tuples +the comparator calls equal and keeps one copy; prefix compression never +merges anything. Sharing is not tied to column boundaries: a member shares +the longest common prefix of its data area with its group's anchor, which +covers whole leading columns plus any leading bytes of the first column that +differs. + +A leaf that uses the technique carries the BTP_PREFIX page flag and one extra +item, the PREFIX DIRECTORY, at the offset where its first data item would +otherwise be (P_HIKEY on a rightmost page, P_FIRSTKEY otherwise); data items +begin one offset later, which P_FIRSTDATAKEY() accounts for. Keeping the +whole directory in a single item preserves the "exactly one item before the +data" property, so P_FIRSTDATAKEY depends only on the page flag, neither +BTPageOpaqueData nor the on-disk page header changes, and binary search over +the data items is unaffected. The directory holds one or more GROUPS of +consecutive data items. A group's ANCHOR is a copy of the key part of its +first member; a new group starts when an item shares no byte with the current +anchor, or when it shares strictly more with its immediate predecessor than +with the current anchor (by at least a MAXALIGN quantum) -- the latter lets a +long run of tuples that share a long prefix with one another form its own +group even when the leaf's first tuple only shares a short leading prefix (say +a low-cardinality leading column) with them. The rule looks only backwards, +so the running size estimate used when filling pages during CREATE INDEX makes +the identical grouping decisions one tuple at a time. + +Each data item is stored "coded": an IndexTupleData header whose +t_tid is the item's own heap TID (no t_tid bit is stolen), a small code header +(group, shared byte count, the original's t_info), the original's null bitmap, +the residual -- the original's data-area bytes after the shared ones -- and, +for a posting list tuple, its posting list in the standard layout. Code that +reads only heap TIDs (VACUUM, LP_DEAD hinting, index deletion, posting list +splits) therefore works on coded items as is. Pivots (high keys and +downlinks) are never coded. Decoding splices the anchor's shared bytes back +in front of the residual and reproduces the original tuple byte for byte. + +Coding and decoding depend only on the page and the tuple, never on the +catalog. _bt_getitem() is the one accessor through which readers obtain a +decoded leaf data item; _bt_compare() decodes the item it compares against, +and _bt_readpage() skips decoding altogether when a scan needs only heap TIDs +and no key comparison remains to be made on the page (not an index-only scan, +every scan key already satisfied for the whole page, no array keys). + +A page gets a directory only when it is written as a whole: a leaf during an +index build, or either half of a leaf page split. An index build collects a +leaf's tuples and fills it according to a running estimate of the coded size, +honoring fillfactor in coded bytes, so a compressible index is built dense +rather than coded after the fact. An insert codes the new tuple against the +group of its neighbor, sharing however much it happens to share (possibly +nothing); no insert, VACUUM or deduplication ever rewrites a page to keep its +directory "good". Deduplication and bottom-up deletion both work on decoded +copies of a coded page's items; deduplication re-codes each resulting tuple +against the page's existing directory, so the page can only shrink. When +VACUUM or page deletion empties a coded leaf, the directory is removed and the +flag cleared, so an emptied leaf holds only its high key, as page deletion +expects. + +A coded page can hold more data than fits on a plain page, and it must still +be possible to split it into two plain pages. The directory caches the +decoded size of the page's items (their sum and the largest), maintained +exactly by every change and repeated by redo, and an insert splits the page +before its decoded content would exceed what a size-balanced split can always +place on two pages, counting the left half's new high key +(_bt_prefix_split_needed has the argument). A split decodes the page, +chooses a split point by plain sizes (upstream _bt_findsplitloc when the +decoded items fit one page, otherwise a size-checked balanced point), writes +both halves plain, and codes each half as a whole page. For the rare case +where a large incoming tuple leaves no legal split point once it is added, the +existing items are split alone and the insert is retried from the top. + +Because the format is a per-page opt-in flag with no btree version change, +pages without the flag are read exactly as before, so pg_upgrade and +replication keep working and existing indexes continue to work with no +REINDEX. Turning the parameter on with ALTER INDEX rewrites nothing; each +leaf is converted the next time it is written whole, and compressed and +uncompressed leaves coexist in the same index indefinitely. Turning it off +likewise rewrites nothing: existing BTP_PREFIX leaves keep their coded form +and are still read correctly, since every reader decodes based on the page +flag, not on the current setting. Index-only scans keep their per-page tuple +workspace sized for a plain page and grow it the first time they read a +BTP_PREFIX page, since a decoded page can exceed one block. + +WAL replay never needs a full-page image for a coded page. An in-place +insert logs the coded tuple, which redo adds verbatim before updating the +directory's cached size. A split record says, in its flags, whether the +original page and each half were coded; for a coded original page its +offsets refer to the decoded item sequence. Redo decodes the original page's +items, collects the left half's items exactly as the primary did, and lays +the left half out with the same routine the primary used +(_bt_prefix_form_page); the right half arrives as its coded items, directory +included, which _bt_restore_page lays out exactly as the primary did. +Deduplication and posting list splits on a coded page are replayed by +repeating the primary's decode, merge and re-code steps. The coded records +are smaller than the plain ones, since every item and the right half travel +in coded form. + +Prefix compression is a separate mechanism from deduplication rather than an +extension of it because the two attack different redundancy. Deduplication +collapses tuples whose whole key is equal into one posting list tuple; it does +nothing for keys that are all distinct. Prefix compression factors out a +leading run shared by distinct keys and leaves their differing suffixes alone; +it does nothing for exact duplicates that a posting list already collapses. +The common case this targets -- a URL or jsonb-path column whose values are +distinct but share a long prefix -- is exactly where deduplication does not +help. The two compose on one page: a posting list tuple is coded like any +other, carrying its posting list after the residual. diff --git a/src/backend/access/nbtree/meson.build b/src/backend/access/nbtree/meson.build index 812f067e7101c..cbd342013288a 100644 --- a/src/backend/access/nbtree/meson.build +++ b/src/backend/access/nbtree/meson.build @@ -6,6 +6,7 @@ backend_sources += files( 'nbtinsert.c', 'nbtpage.c', 'nbtpreprocesskeys.c', + 'nbtprefix.c', 'nbtreadpage.c', 'nbtree.c', 'nbtsearch.c', diff --git a/src/backend/access/nbtree/nbtdedup.c b/src/backend/access/nbtree/nbtdedup.c index af7affdf409d3..17869e3367876 100644 --- a/src/backend/access/nbtree/nbtdedup.c +++ b/src/backend/access/nbtree/nbtdedup.c @@ -70,6 +70,8 @@ _bt_dedup_pass(Relation rel, Buffer buf, IndexTuple newitem, Size newitemsz, bool singlevalstrat = false; int nkeyatts = IndexRelationGetNumberOfKeyAttributes(rel); XLogRecPtr recptr; + bool coded = P_HASPREFIX(opaque); + IndexTuple *ditems = NULL; /* Passed-in newitemsz is MAXALIGNED but does not include line pointer */ newitemsz += sizeof(ItemIdData); @@ -131,12 +133,36 @@ _bt_dedup_pass(Relation rel, Buffer buf, IndexTuple newitem, Size newitemsz, elog(ERROR, "deduplication failed to add highkey"); } + /* + * On a prefix-compressed page, merge decoded copies of the items, and + * keep the page's directory: each output tuple is coded against the group + * of its interval's base item (_bt_dedup_finish_pending_coded). Merging + * never enlarges a coded page, so the result always fits. + */ + if (coded) + { + OffsetNumber prefixoff = BTPageGetPrefixOff(opaque); + ItemId diritemid = PageGetItemId(page, prefixoff); + IndexTuple dummyhikey; + Size dummyhikeysz; + + if (PageAddItem(newpage, PageGetItem(page, diritemid), + ItemIdGetLength(diritemid), prefixoff, + false, false) == InvalidOffsetNumber) + elog(ERROR, "deduplication failed to add prefix directory"); + (void) _bt_prefix_decode_items(page, &ditems, &dummyhikey, + &dummyhikeysz); + if (dummyhikey) + pfree(dummyhikey); + } + for (offnum = minoff; offnum <= maxoff; offnum = OffsetNumberNext(offnum)) { ItemId itemid = PageGetItemId(page, offnum); - IndexTuple itup = (IndexTuple) PageGetItem(page, itemid); + IndexTuple itup = coded ? ditems[offnum - minoff] : + (IndexTuple) PageGetItem(page, itemid); Assert(!ItemIdIsDead(itemid)); @@ -170,7 +196,10 @@ _bt_dedup_pass(Relation rel, Buffer buf, IndexTuple newitem, Size newitemsz, * form new posting tuple and add it to our temp page (newpage). * Else add pending interval's base tuple to the temp page as-is. */ - pagesaving += _bt_dedup_finish_pending(newpage, state); + if (coded) + _bt_dedup_finish_pending_coded(page, newpage, state); + else + pagesaving += _bt_dedup_finish_pending(newpage, state); if (singlevalstrat) { @@ -203,7 +232,17 @@ _bt_dedup_pass(Relation rel, Buffer buf, IndexTuple newitem, Size newitemsz, } /* Handle the last item */ - pagesaving += _bt_dedup_finish_pending(newpage, state); + if (coded) + _bt_dedup_finish_pending_coded(page, newpage, state); + else + pagesaving += _bt_dedup_finish_pending(newpage, state); + + if (ditems) + { + for (int i = 0; i <= maxoff - minoff; i++) + pfree(ditems[i]); + pfree(ditems); + } /* * If no items suitable for deduplication were found, newpage must be @@ -240,6 +279,9 @@ _bt_dedup_pass(Relation rel, Buffer buf, IndexTuple newitem, Size newitemsz, START_CRIT_SECTION(); + /* the copied directory's cached sizes describe the old items */ + if (coded) + _bt_prefix_recount(newpage); PageRestoreTempPage(newpage, page); MarkBufferDirty(buf); @@ -272,7 +314,8 @@ _bt_dedup_pass(Relation rel, Buffer buf, IndexTuple newitem, Size newitemsz, END_CRIT_SECTION(); /* Local space accounting should agree with page accounting */ - Assert(pagesaving < newitemsz || PageGetExactFreeSpace(page) >= newitemsz); + Assert(coded || pagesaving < newitemsz || + PageGetExactFreeSpace(page) >= newitemsz); /* cannot leak memory here */ pfree(state->htids); @@ -317,6 +360,7 @@ _bt_bottomupdel_pass(Relation rel, Buffer buf, Relation heapRel, BTDedupState state; TM_IndexDeleteOp delstate; bool neverdedup; + IndexTuple *ditems = NULL; int nkeyatts = IndexRelationGetNumberOfKeyAttributes(rel); /* Passed-in newitemsz is MAXALIGNED but does not include line pointer */ @@ -362,12 +406,30 @@ _bt_bottomupdel_pass(Relation rel, Buffer buf, Relation heapRel, minoff = P_FIRSTDATAKEY(opaque); maxoff = PageGetMaxOffsetNumber(page); + + /* + * On a prefix-compressed page compare decoded copies of the items. Coded + * tuples keep their heap TIDs and posting lists in the standard layout, + * so the code below that reads only TIDs works on them as is. + */ + if (P_HASPREFIX(opaque)) + { + IndexTuple dummyhikey; + Size dummyhikeysz; + + (void) _bt_prefix_decode_items(page, &ditems, &dummyhikey, + &dummyhikeysz); + if (dummyhikey) + pfree(dummyhikey); + } + for (offnum = minoff; offnum <= maxoff; offnum = OffsetNumberNext(offnum)) { ItemId itemid = PageGetItemId(page, offnum); - IndexTuple itup = (IndexTuple) PageGetItem(page, itemid); + IndexTuple itup = ditems ? ditems[offnum - minoff] : + (IndexTuple) PageGetItem(page, itemid); Assert(!ItemIdIsDead(itemid)); @@ -393,6 +455,13 @@ _bt_bottomupdel_pass(Relation rel, Buffer buf, Relation heapRel, /* Finalize final interval -- move its TIDs to delete state */ _bt_bottomupdel_finish_pending(page, state, &delstate); + if (ditems) + { + for (int i = 0; i <= maxoff - minoff; i++) + pfree(ditems[i]); + pfree(ditems); + } + /* * We don't give up now in the event of having few (or even zero) * promising tuples for the tableam because it's not up to us as the index @@ -419,7 +488,11 @@ _bt_bottomupdel_pass(Relation rel, Buffer buf, Relation heapRel, return true; /* Don't dedup when we won't end up back here any time soon anyway */ - return PageGetExactFreeSpace(page) >= Max(BLCKSZ / 24, newitemsz); + return PageGetExactFreeSpace(page) >= + Max(BLCKSZ / 24, newitemsz + + (P_HASPREFIX(opaque) ? BTREE_PREFIX_CODE_OVERHEAD : 0)) && + (!P_HASPREFIX(opaque) || + !_bt_prefix_split_needed(page, newitemsz - sizeof(ItemIdData))); } /* @@ -608,6 +681,55 @@ _bt_dedup_finish_pending(Page newpage, BTDedupState state) return spacesaving; } +/* + * _bt_dedup_finish_pending for a prefix-compressed page. The tuple added to + * newpage is coded against the group of the interval's base item, using the + * source page's directory, which newpage carries unchanged. A lone base item + * is copied in its existing coded form. Uses only the two pages, so WAL redo + * calls it to repeat the primary's deduplication exactly. + */ +void +_bt_dedup_finish_pending_coded(Page page, Page newpage, BTDedupState state) +{ + OffsetNumber tupoff = OffsetNumberNext(PageGetMaxOffsetNumber(newpage)); + IndexTuple out; + Size outsz; + + Assert(state->nitems > 0); + Assert(state->nitems <= state->nhtids); + Assert(state->intervals[state->nintervals].baseoff == state->baseoff); + + if (state->nitems == 1) + { + ItemId itemid = PageGetItemId(page, state->baseoff); + + out = (IndexTuple) PageGetItem(page, itemid); + outsz = ItemIdGetLength(itemid); + if (PageAddItem(newpage, out, outsz, tupoff, false, false) == InvalidOffsetNumber) + elog(ERROR, "deduplication failed to add tuple to page"); + } + else + { + IndexTuple final; + + final = _bt_form_posting(state->base, state->htids, state->nhtids); + Assert(IndexTupleSize(final) <= state->maxpostingsize); + state->intervals[state->nintervals].nitems = state->nitems; + + out = _bt_prefix_recode(page, state->baseoff, final); + outsz = IndexTupleSize(out); + if (PageAddItem(newpage, out, outsz, tupoff, false, false) == InvalidOffsetNumber) + elog(ERROR, "deduplication failed to add tuple to page"); + pfree(out); + pfree(final); + state->nintervals++; + } + + state->nhtids = 0; + state->nitems = 0; + state->phystupsize = 0; +} + /* * Finalize interval during bottom-up index deletion. * @@ -783,16 +905,14 @@ _bt_do_singleval(Relation rel, Page page, BTDedupState state, OffsetNumber minoff, IndexTuple newitem) { int nkeyatts = IndexRelationGetNumberOfKeyAttributes(rel); - ItemId itemid; IndexTuple itup; + BTItemBuf buf; - itemid = PageGetItemId(page, minoff); - itup = (IndexTuple) PageGetItem(page, itemid); + itup = _bt_getitem(page, minoff, &buf); if (_bt_keep_natts_fast(rel, newitem, itup) > nkeyatts) { - itemid = PageGetItemId(page, PageGetMaxOffsetNumber(page)); - itup = (IndexTuple) PageGetItem(page, itemid); + itup = _bt_getitem(page, PageGetMaxOffsetNumber(page), &buf); if (_bt_keep_natts_fast(rel, newitem, itup) > nkeyatts) return true; diff --git a/src/backend/access/nbtree/nbtinsert.c b/src/backend/access/nbtree/nbtinsert.c index d5d964301c1b4..04c0a83a7990d 100644 --- a/src/backend/access/nbtree/nbtinsert.c +++ b/src/backend/access/nbtree/nbtinsert.c @@ -46,7 +46,7 @@ static OffsetNumber _bt_findinsertloc(Relation rel, Relation heapRel); static void _bt_stepright(Relation rel, Relation heaprel, BTInsertState insertstate, BTStack stack); -static void _bt_insertonpg(Relation rel, Relation heaprel, BTScanInsert itup_key, +static bool _bt_insertonpg(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, Buffer cbuf, BTStack stack, @@ -58,7 +58,8 @@ static void _bt_insertonpg(Relation rel, Relation heaprel, BTScanInsert itup_key static Buffer _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, Buffer cbuf, OffsetNumber newitemoff, Size newitemsz, IndexTuple newitem, IndexTuple orignewitem, - IndexTuple nposting, uint16 postingoff); + IndexTuple nposting, uint16 postingoff, + bool *newitemplaced); static void _bt_insert_parent(Relation rel, Relation heaprel, Buffer buf, Buffer rbuf, BTStack stack, bool isroot, bool isonly); static void _bt_freestack(BTStack stack); @@ -260,9 +261,27 @@ _bt_doinsert(Relation rel, IndexTuple itup, */ newitemoff = _bt_findinsertloc(rel, &insertstate, checkingunique, indexUnchanged, stack, heapRel); - _bt_insertonpg(rel, heapRel, itup_key, insertstate.buf, InvalidBuffer, - stack, itup, insertstate.itemsz, newitemoff, - insertstate.postingoff, false); + if (!_bt_insertonpg(rel, heapRel, itup_key, insertstate.buf, + InvalidBuffer, stack, itup, insertstate.itemsz, + newitemoff, insertstate.postingoff, false)) + { + /* + * A prefix leaf was split without placing itup, because no split + * point kept both decoded halves within a page with itup added. + * Retry from the top. The uniqueness check must be redone too: + * the page lock was released, so a conflicting duplicate may have + * been inserted meanwhile. + */ + if (stack) + _bt_freestack(stack); + if (checkingunique && itup_key->heapkeyspace && + !itup_key->anynullkeys) + itup_key->scantid = NULL; + insertstate.buf = InvalidBuffer; + insertstate.bounds_valid = false; + insertstate.postingoff = 0; + goto search; + } } else { @@ -347,9 +366,11 @@ _bt_search_insert(Relation rel, Relation heaprel, BTInsertState insertstate) if (P_RIGHTMOST(opaque) && P_ISLEAF(opaque) && !P_IGNORE(opaque) && + !P_HASPREFIX(opaque) && PageGetFreeSpace(page) > insertstate->itemsz && - PageGetMaxOffsetNumber(page) >= P_HIKEY && - _bt_compare(rel, insertstate->itup_key, page, P_HIKEY) > 0) + PageGetMaxOffsetNumber(page) >= P_FIRSTDATAKEY(opaque) && + _bt_compare(rel, insertstate->itup_key, page, + P_FIRSTDATAKEY(opaque)) > 0) { /* * Caller can use the fastpath optimization because cached @@ -910,12 +931,28 @@ _bt_findinsertloc(Relation rel, /* * If the target page cannot fit newitem, try to avoid splitting the - * page on insert by performing deletion or deduplication now + * page on insert by performing deletion or deduplication now. On a + * prefix page the coded item can exceed the plain tuple by up to + * BTREE_PREFIX_CODE_OVERHEAD, so reserve that slack; otherwise a + * coded PageAddItem could fail after the fit check passed. */ - if (PageGetFreeSpace(page) < insertstate->itemsz) - _bt_delete_or_dedup_one_page(rel, heapRel, insertstate, false, - checkingunique, uniquedup, - indexUnchanged); + { + Size need = insertstate->itemsz; + + if (P_HASPREFIX(opaque)) + need += BTREE_PREFIX_CODE_OVERHEAD; + + /* + * A prefix page also splits once its decoded content nears the + * split-fit limit, often before it is physically full. + */ + if (PageGetFreeSpace(page) < need || + (P_HASPREFIX(opaque) && + _bt_prefix_split_needed(page, insertstate->itemsz))) + _bt_delete_or_dedup_one_page(rel, heapRel, insertstate, false, + checkingunique, uniquedup, + indexUnchanged); + } } else { @@ -1111,9 +1148,12 @@ _bt_stepright(Relation rel, Relation heaprel, BTInsertState insertstate, * inserting to a non-leaf page, 'cbuf' is the left-sibling of the page * we're inserting the downlink for. This function will clear the * INCOMPLETE_SPLIT flag on it, and release the buffer. + * + * Returns false if a prefix leaf was split without placing itup (see + * _bt_split); caller must retry the insertion. Otherwise true. *---------- */ -static void +static bool _bt_insertonpg(Relation rel, Relation heaprel, BTScanInsert itup_key, @@ -1135,6 +1175,11 @@ _bt_insertonpg(Relation rel, IndexTuple oposting = NULL; IndexTuple origitup = NULL; IndexTuple nposting = NULL; + IndexTuple codedposting = NULL; /* nposting coded (prefix leaf) */ + IndexTuple additup; /* tuple actually added (coded or plain) */ + Size additemsz; + bool needsplit; + bool newitemplaced = true; XLogRecPtr recptr; page = BufferGetPage(buf); @@ -1181,7 +1226,13 @@ _bt_insertonpg(Relation rel, * insert or page split critical section. */ Assert(isleaf && itup_key->heapkeyspace && itup_key->allequalimage); - oposting = (IndexTuple) PageGetItem(page, itemid); + if (P_HASPREFIX(opaque)) + { + /* swap on the decoded tuple; recoded below, outside crit section */ + oposting = _bt_prefix_decode_copy(page, newitemoff); + } + else + oposting = (IndexTuple) PageGetItem(page, itemid); /* * postingoff value comes from earlier call to _bt_binsrch_posting(). @@ -1209,18 +1260,57 @@ _bt_insertonpg(Relation rel, nposting = _bt_swap_posting(itup, oposting, postingoff); /* itup now contains rightmost/max TID from oposting */ + if (P_HASPREFIX(opaque)) + { + /* + * The coded post-split posting tuple overwrites the coded + * original in place; it has the same size because the posting + * list only trades one TID. nposting stays plain, which is what + * _bt_split expects since it decodes the page itself. + */ + codedposting = _bt_prefix_recode(page, newitemoff, nposting); + Assert(IndexTupleSize(codedposting) == ItemIdGetLength(itemid)); + pfree(oposting); + oposting = (IndexTuple) PageGetItem(page, itemid); + } + /* Alter offset so that newitem goes after posting list */ newitemoff = OffsetNumberNext(newitemoff); } /* - * Do we need to split the page to fit the item on it? + * On a prefix leaf the new item is stored coded. Code it here, before + * any critical section, because coding pallocs. + */ + if (isleaf && P_HASPREFIX(opaque)) + { + additup = _bt_prefix_encode_insert(page, newitemoff, itup); + additemsz = additup ? MAXALIGN(IndexTupleSize(additup)) : 0; + } + else + { + additup = itup; + additemsz = itemsz; + } + + /* + * Do we need to split the page to fit the item? A prefix leaf also + * splits when the item cannot be coded against the page, or when its + * plain form would exceed the decoded split-fit budget. * * Note: PageGetFreeSpace() subtracts sizeof(ItemIdData) from its result, * so this comparison is correct even though we appear to be accounting * only for the item and not for its line pointer. */ - if (PageGetFreeSpace(page) < itemsz) + if (isleaf && P_HASPREFIX(opaque)) + needsplit = + additup == NULL || + PageGetFreeSpace(page) < additemsz || + _bt_prefix_split_needed(page, itemsz); + else + needsplit = PageGetFreeSpace(page) < itemsz; + + if (needsplit) { Buffer rbuf; @@ -1228,7 +1318,7 @@ _bt_insertonpg(Relation rel, /* split the buffer into left and right halves */ rbuf = _bt_split(rel, heaprel, itup_key, buf, cbuf, newitemoff, itemsz, - itup, origitup, nposting, postingoff); + itup, origitup, nposting, postingoff, &newitemplaced); PredicateLockPageSplit(rel, BufferGetBlockNumber(buf), BufferGetBlockNumber(rbuf)); @@ -1259,6 +1349,19 @@ _bt_insertonpg(Relation rel, #endif _bt_insert_parent(rel, heaprel, buf, rbuf, stack, isroot, isonly); + + if (additup != NULL && additup != itup) + pfree(additup); + + /* be tidy (posting split path) */ + if (postingoff != 0) + { + pfree(nposting); + pfree(itup); + if (codedposting) + pfree(codedposting); + } + return newitemplaced; } else { @@ -1295,11 +1398,17 @@ _bt_insertonpg(Relation rel, START_CRIT_SECTION(); if (postingoff != 0) - memcpy(oposting, nposting, MAXALIGN(IndexTupleSize(nposting))); + { + IndexTuple src = codedposting ? codedposting : nposting; - if (PageAddItem(page, itup, itemsz, newitemoff, false, false) == InvalidOffsetNumber) + memcpy(oposting, src, MAXALIGN(IndexTupleSize(src))); + } + + if (PageAddItem(page, additup, additemsz, newitemoff, false, false) == InvalidOffsetNumber) elog(PANIC, "failed to add new item to block %u in index \"%s\"", BufferGetBlockNumber(buf), RelationGetRelationName(rel)); + if (isleaf && P_HASPREFIX(opaque)) + _bt_prefix_note_insert(page, additup); MarkBufferDirty(buf); @@ -1384,8 +1493,8 @@ _bt_insertonpg(Relation rel, XLogRegisterBuffer(0, buf, REGBUF_STANDARD); if (postingoff == 0) { - /* Just log itup from caller */ - XLogRegisterBufData(0, itup, IndexTupleSize(itup)); + /* Log the tuple as added: coded on a prefix leaf */ + XLogRegisterBufData(0, additup, IndexTupleSize(additup)); } else { @@ -1418,6 +1527,9 @@ _bt_insertonpg(Relation rel, END_CRIT_SECTION(); + if (additup != itup) + pfree(additup); + /* Release subsidiary buffers */ if (BufferIsValid(metabuf)) _bt_relbuf(rel, metabuf); @@ -1453,7 +1565,11 @@ _bt_insertonpg(Relation rel, /* itup is actually a modified copy of caller's original */ pfree(nposting); pfree(itup); + if (codedposting) + pfree(codedposting); } + + return true; } /* @@ -1481,19 +1597,27 @@ _bt_insertonpg(Relation rel, * nbtree/README for details on the design of posting list splits. * * Returns the new right sibling of buf, pinned and write-locked. - * The pin and lock on buf are maintained. + * The pin and lock on buf are maintained. *newitemplaced is set false + * when a coded leaf's decoded items left no legal split point with + * newitem added; the existing items alone are split then, and caller + * must insert newitem afterwards. */ static Buffer _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, Buffer cbuf, OffsetNumber newitemoff, Size newitemsz, IndexTuple newitem, - IndexTuple orignewitem, IndexTuple nposting, uint16 postingoff) + IndexTuple orignewitem, IndexTuple nposting, uint16 postingoff, + bool *newitemplaced) { + bool placenewitem = true; /* false: split existing items only */ + bool leftcoded; /* left half written in BTP_PREFIX form? */ Buffer rbuf; Page origpage; Page leftpage, rightpage; PGAlignedBlock leftpage_buf, rightpage_buf; + Page plainscratch = NULL; /* decoded plain copy of a coded + * origpage, palloc'd */ BlockNumber origpagenumber, rightpagenumber; BTPageOpaque ropaque, @@ -1502,6 +1626,13 @@ _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, Buffer sbuf = InvalidBuffer; Page spage = NULL; BTPageOpaque sopaque = NULL; + bool origprefix = false; /* was origpage a coded prefix page? */ + bool origprefix_array = false; /* using decoded-item array path? */ + Page origbufpage; /* the real buffer page (origpage may be + * scratch) */ + IndexTuple *ditems = NULL; /* decoded data items (prefix split) */ + int nditems = 0; + IndexTuple ditemposting = NULL; /* decoded copy displaced by nposting */ Size itemsz; ItemId itemid; IndexTuple firstright, @@ -1532,12 +1663,59 @@ _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, * only workspace. */ origpage = BufferGetPage(buf); + origbufpage = origpage; oopaque = BTPageGetOpaque(origpage); isleaf = P_ISLEAF(oopaque); isrightmost = P_RIGHTMOST(oopaque); maxoff = PageGetMaxOffsetNumber(origpage); origpagenumber = BufferGetBlockNumber(buf); + /* + * A coded (BTP_PREFIX) leaf is split on its decoded items, and both + * halves are built plain, then coded as whole pages at the end. When the + * decoded items fit one page, split a plain scratch copy, so that + * _bt_findsplitloc and its heap TID tiebreak at duplicate boundaries + * apply unchanged. A heavily compressed page whose decoded items exceed + * BLCKSZ cannot be laid out that way; split an array of the decoded items + * instead, with a size-balanced split point from _bt_prefix_findsplitloc. + */ + if (P_HASPREFIX(oopaque)) + { + Page plain; + + origprefix = true; + + plainscratch = (Page) palloc_aligned(BLCKSZ, PG_IO_ALIGN_SIZE, 0); + plain = _bt_prefix_try_plain_page(rel, origpage, plainscratch); + if (plain != NULL) + { + OffsetNumber codedfirst = P_FIRSTDATAKEY(oopaque); + + origpage = plain; + oopaque = BTPageGetOpaque(origpage); + maxoff = PageGetMaxOffsetNumber(origpage); + origprefix_array = false; + + /* + * newitemoff is in the coded page's offset space, where the + * directory item shifts data items one later; the scratch page + * has no directory. + */ + newitemoff -= (codedfirst - P_FIRSTDATAKEY(oopaque)); + } + else + { + IndexTuple dhikey; + Size dhikeysz; + + nditems = _bt_prefix_decode_items(origpage, &ditems, &dhikey, + &dhikeysz); + if (dhikey) + pfree(dhikey); + origprefix_array = true; + } + } + /* * Choose a point to split origpage at. * @@ -1562,8 +1740,32 @@ _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, * newitem the firstright tuple, though, so this case isn't a special * case. */ - firstrightoff = _bt_findsplitloc(rel, origpage, newitemoff, newitemsz, - newitem, &newitemonleft); + if (origprefix_array) + { + firstrightoff = _bt_prefix_findsplitloc(rel, origpage, ditems, + newitemoff, newitemsz, + &newitemonleft); + if (!OffsetNumberIsValid(firstrightoff)) + { + /* + * No split of the decoded items plus newitem keeps both halves + * within a plain page. Split the existing items alone and let + * caller re-insert newitem. newitemoff is made unreachable so + * the transfer loop below never places newitem. + */ + placenewitem = false; + firstrightoff = _bt_prefix_findsplitloc(rel, origpage, ditems, + InvalidOffsetNumber, 0, + &newitemonleft); + newitemonleft = false; + newitemoff = maxoff + 2; /* past the "goes at end" case too */ + postingoff = 0; /* posting split is part of the deferred + * insert */ + } + } + else + firstrightoff = _bt_findsplitloc(rel, origpage, newitemoff, newitemsz, + newitem, &newitemonleft); /* Use temporary buffer for leftpage */ leftpage = leftpage_buf.data; @@ -1588,7 +1790,7 @@ _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, * updated version of the page. We need this because XLogInsert will * examine the LSN and possibly dump it in a page image. */ - PageSetLSN(leftpage, PageGetLSN(origpage)); + PageSetLSN(leftpage, PageGetLSN(origbufpage)); /* * Determine page offset number of existing overlapped-with-orignewitem @@ -1616,6 +1818,13 @@ _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, &newitem->t_tid) < 0); Assert(BTreeTupleIsPosting(nposting)); origpagepostingoff = OffsetNumberPrev(newitemoff); + if (origprefix_array) + { + int pidx = origpagepostingoff - P_FIRSTDATAKEY(oopaque); + + ditemposting = ditems[pidx]; + ditems[pidx] = nposting; + } } /* @@ -1647,11 +1856,19 @@ _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, else { /* existing item at firstrightoff becomes firstright */ - itemid = PageGetItemId(origpage, firstrightoff); - itemsz = ItemIdGetLength(itemid); - firstright = (IndexTuple) PageGetItem(origpage, itemid); - if (firstrightoff == origpagepostingoff) - firstright = nposting; + if (origprefix_array) + { + firstright = ditems[firstrightoff - P_FIRSTDATAKEY(oopaque)]; + itemsz = IndexTupleSize(firstright); + } + else + { + itemid = PageGetItemId(origpage, firstrightoff); + itemsz = ItemIdGetLength(itemid); + firstright = (IndexTuple) PageGetItem(origpage, itemid); + if (firstrightoff == origpagepostingoff) + firstright = nposting; + } } if (isleaf) @@ -1671,10 +1888,15 @@ _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, /* existing item before firstrightoff becomes lastleft */ lastleftoff = OffsetNumberPrev(firstrightoff); Assert(lastleftoff >= P_FIRSTDATAKEY(oopaque)); - itemid = PageGetItemId(origpage, lastleftoff); - lastleft = (IndexTuple) PageGetItem(origpage, itemid); - if (lastleftoff == origpagepostingoff) - lastleft = nposting; + if (origprefix_array) + lastleft = ditems[lastleftoff - P_FIRSTDATAKEY(oopaque)]; + else + { + itemid = PageGetItemId(origpage, lastleftoff); + lastleft = (IndexTuple) PageGetItem(origpage, itemid); + if (lastleftoff == origpagepostingoff) + lastleft = nposting; + } } lefthighkey = _bt_truncate(rel, lastleft, firstright, itup_key); @@ -1818,12 +2040,20 @@ _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, { IndexTuple dataitem; - itemid = PageGetItemId(origpage, i); - itemsz = ItemIdGetLength(itemid); - dataitem = (IndexTuple) PageGetItem(origpage, itemid); + if (origprefix_array) + { + dataitem = ditems[i - P_FIRSTDATAKEY(oopaque)]; + itemsz = IndexTupleSize(dataitem); + } + else + { + itemid = PageGetItemId(origpage, i); + itemsz = ItemIdGetLength(itemid); + dataitem = (IndexTuple) PageGetItem(origpage, itemid); + } /* replace original item with nposting due to posting split? */ - if (i == origpagepostingoff) + if (!origprefix_array && i == origpagepostingoff) { Assert(BTreeTupleIsPosting(dataitem)); Assert(itemsz == MAXALIGN(IndexTupleSize(nposting))); @@ -1884,7 +2114,7 @@ _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, } /* Handle case where newitem goes at the end of rightpage */ - if (i <= newitemoff) + if (placenewitem && i <= newitemoff) { /* * Can't have newitemonleft here; that would imply we were told to put @@ -1947,6 +2177,26 @@ _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, * not starting the critical section till here because we haven't been * scribbling on the original page yet; see comments above. */ + + /* + * Both halves were built plain but may have inherited BTP_PREFIX from a + * coded original page. Code them here, before the critical section, + * because coding pallocs. + */ + if (isleaf) + { + lopaque->btpo_flags &= ~BTP_PREFIX; + ropaque->btpo_flags &= ~BTP_PREFIX; + if (_bt_prefix_enabled(rel)) + { + _bt_prefix_compress_page(rel, leftpage); + _bt_prefix_compress_page(rel, rightpage); + lopaque = BTPageGetOpaque(leftpage); + ropaque = BTPageGetOpaque(rightpage); + } + } + leftcoded = P_HASPREFIX(lopaque); + START_CRIT_SECTION(); /* @@ -1956,7 +2206,7 @@ _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, * original. We need to do this before writing the WAL record, so that * XLogInsert can WAL log an image of the page if necessary. */ - memcpy(origpage, leftpage, BLCKSZ); + memcpy(origbufpage, leftpage, BLCKSZ); /* leftpage, lopaque must not be used below here */ /* @@ -2005,6 +2255,27 @@ _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, if (postingoff != 0 && origpagepostingoff < firstrightoff) xlrec.postingoff = postingoff; + /* + * A coded original page is described to redo in its decoded offset + * space (see XLH_SPLIT_ORIG_CODED). The plain-scratch path already + * works there; the decoded-array path works in the coded page's + * offsets, one past the directory item. + */ + xlrec.flags = 0; + if (origprefix) + { + xlrec.flags |= XLH_SPLIT_ORIG_CODED; + if (origprefix_array) + { + xlrec.firstrightoff--; + xlrec.newitemoff--; + } + } + if (leftcoded) + xlrec.flags |= XLH_SPLIT_LEFT_CODED; + if (P_HASPREFIX(ropaque)) + xlrec.flags |= XLH_SPLIT_RIGHT_CODED; + XLogBeginInsert(); XLogRegisterData(&xlrec, SizeOfBtreeSplit); @@ -2083,7 +2354,7 @@ _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, else recptr = XLogGetFakeLSN(rel); - PageSetLSN(origpage, recptr); + PageSetLSN(origbufpage, recptr); PageSetLSN(rightpage, recptr); if (!isrightmost) PageSetLSN(spage, recptr); @@ -2103,8 +2374,23 @@ _bt_split(Relation rel, Relation heaprel, BTScanInsert itup_key, Buffer buf, /* be tidy */ if (isleaf) pfree(lefthighkey); + if (ditems) + { + /* nposting belongs to the caller; free the decoded copy it displaced */ + for (int k = 0; k < nditems; k++) + { + if (ditems[k] != nposting) + pfree(ditems[k]); + } + if (ditemposting) + pfree(ditemposting); + pfree(ditems); + } + if (plainscratch) + pfree(plainscratch); /* split's done */ + *newitemplaced = placenewitem; return rbuf; } @@ -2770,7 +3056,10 @@ _bt_delete_or_dedup_one_page(Relation rel, Relation heapRel, insertstate->bounds_valid = false; /* Return when a page split has already been avoided */ - if (PageGetFreeSpace(page) >= insertstate->itemsz) + if (PageGetFreeSpace(page) >= insertstate->itemsz + + (P_HASPREFIX(opaque) ? BTREE_PREFIX_CODE_OVERHEAD : 0) && + (!P_HASPREFIX(opaque) || + !_bt_prefix_split_needed(page, insertstate->itemsz))) return; /* Might as well assume duplicates (if checkingunique) */ diff --git a/src/backend/access/nbtree/nbtpage.c b/src/backend/access/nbtree/nbtpage.c index 83d6d367f8131..9fc8e9f1feac4 100644 --- a/src/backend/access/nbtree/nbtpage.c +++ b/src/backend/access/nbtree/nbtpage.c @@ -1211,6 +1211,7 @@ _bt_delitems_vacuum(Relation rel, Buffer buf, /* Now handle simple deletes of entire tuples */ if (ndeletable > 0) PageIndexMultiDelete(page, deletable, ndeletable); + _bt_prefix_recount(page); /* * We can clear the vacuum cycle ID since this page has certainly been @@ -1331,6 +1332,7 @@ _bt_delitems_delete(Relation rel, Buffer buf, if (ndeletable > 0) PageIndexMultiDelete(page, deletable, ndeletable); + _bt_prefix_recount(page); /* * Unlike _bt_delitems_vacuum, we *must not* clear the vacuum cycle ID at diff --git a/src/backend/access/nbtree/nbtprefix.c b/src/backend/access/nbtree/nbtprefix.c new file mode 100644 index 0000000000000..19ac23f8a06c5 --- /dev/null +++ b/src/backend/access/nbtree/nbtprefix.c @@ -0,0 +1,1292 @@ +/*------------------------------------------------------------------------- + * + * nbtprefix.c + * Leaf key prefix compression for Postgres btrees. + * + * A leaf of an index whose prefix_compression reloption is on may be flagged + * BTP_PREFIX: its data items are stored "coded" against per-page group + * anchors, dropping the leading bytes each shares with its anchor. The + * on-disk format is described at BTP_PREFIX in nbtree.h; the README covers how + * the rest of nbtree uses it. + * + * Everything here works on pages and tuples alone, never the catalog, so WAL + * redo can lay out a coded page exactly as the primary did. A page gets its + * directory when it is written as a whole (CREATE INDEX, either half of a + * split); an insert codes the new tuple against an existing group, sharing + * however much it happens to share, and deduplication re-codes against the + * page's existing directory. + * + * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * IDENTIFICATION + * src/backend/access/nbtree/nbtprefix.c + * + *------------------------------------------------------------------------- + */ +#include "postgres.h" + +#include "access/itup.h" +#include "access/nbtree.h" +#include "access/tupmacs.h" +#include "storage/bufpage.h" +#include "utils/rel.h" + +/* In-memory anchor: the group's first member, as a plain tuple. */ +typedef struct BTPrefixAnchor +{ + IndexTuple rep; /* representative tuple owning the shared + * bytes */ +} BTPrefixAnchor; + +/* In-memory directory of a page being laid out by _bt_prefix_form_page. */ +typedef struct BTPrefixDir +{ + int ngroups; + BTPrefixAnchor anchors[FLEXIBLE_ARRAY_MEMBER]; +} BTPrefixDir; + +/* + * On-disk directory item header. decodedsz and maxdecoded cache the decoded + * (plain) size of the page's data items, each counted with its line pointer: + * their sum and the largest. They make _bt_prefix_split_needed O(1). Every + * change to the data items keeps them exact, through page-only routines that + * WAL redo repeats (_bt_prefix_note_insert, _bt_prefix_recount). + */ +typedef struct BTPrefixDirHdr +{ + IndexTupleData header; /* t_tid invalid; t_info = whole item size */ + uint16 ngroups; + uint16 decodedsz; /* sum of decoded item sizes + line pointers */ + uint16 maxdecoded; /* largest of those */ + uint16 anchoroff[FLEXIBLE_ARRAY_MEMBER]; /* from item start */ + /* then the packed anchors */ +} BTPrefixDirHdr; + +/* One packed anchor in the directory item. */ +typedef struct BTPrefixAnchorDisk +{ + uint16 repsz; /* size of the representative tuple blob */ + /* IndexTupleData rep[repsz] follows, MAXALIGN'd */ +} BTPrefixAnchorDisk; + +/* + * Code header of a coded member, right after its IndexTupleData header. The + * member layout is described at BTP_PREFIX in nbtree.h. + */ +typedef struct BTPrefixCode +{ + uint16 group; /* anchor index in the directory */ + uint16 shared_len; /* leading data-area bytes taken from rep */ + uint16 orig_info; /* original tuple's t_info (size, flags) */ +} BTPrefixCode; + +/* + * A coded member is never larger than its plain form by more than + * BTREE_PREFIX_CODE_OVERHEAD, which _bt_findinsertloc reserves before coding. + * The worst case is a posting tuple, whose body and posting list are each + * MAXALIGN'd: MAXALIGN(code header + key) + MAXALIGN(posting list) exceeds + * the plain MAXALIGN(key + posting list) by at most the code header plus one + * alignment of the posting list. + */ +StaticAssertDecl(BTREE_PREFIX_CODE_OVERHEAD >= + MAXALIGN(sizeof(BTPrefixCode)) + MAXALIGN(sizeof(ItemPointerData)), + "BTREE_PREFIX_CODE_OVERHEAD too small for the coded member header"); + +/* + * _bt_prefix_enabled + * Is prefix compression turned on for this index? + */ +bool +_bt_prefix_enabled(Relation index) +{ + return index->rd_options && + ((BTOptions *) index->rd_options)->prefix_compression; +} + +/* + * Size of a tuple's key part: everything but a posting list. Index tuples are + * MAXALIGN'd, and so is a posting list's offset, so this is MAXALIGN'd too. + */ +static inline Size +_bt_prefix_keysz(IndexTuple itup) +{ + return BTreeTupleIsPosting(itup) ? BTreeTupleGetPostingOffset(itup) : + IndexTupleSize(itup); +} + +/* + * Size of a directory item for `ngroups' groups whose MAXALIGN'd anchor blobs + * total `anchorsz' bytes. + */ +static inline Size +_bt_prefix_diritem_size(int ngroups, Size anchorsz) +{ + return MAXALIGN(offsetof(BTPrefixDirHdr, anchoroff) + + sizeof(uint16) * ngroups) + anchorsz; +} + +/* + * Length of the common prefix of the key-part data areas of `rep' and `itup'. + */ +static Size +_bt_prefix_shared_len(IndexTuple rep, IndexTuple itup) +{ + Size rephoff = IndexInfoFindDataOffset(rep->t_info); + Size hoff = IndexInfoFindDataOffset(itup->t_info); + const char *rp = (const char *) rep + rephoff; + const char *mp = (const char *) itup + hoff; + Size limit = Min(_bt_prefix_keysz(rep) - rephoff, + _bt_prefix_keysz(itup) - hoff); + Size n = 0; + + while (n < limit && rp[n] == mp[n]) + n++; + return n; +} + +/* + * Size of `itup' coded against representative `rep' (what + * _bt_prefix_encode_against would produce), without forming it. + */ +static Size +_bt_prefix_coded_size(IndexTuple rep, IndexTuple itup, Size shared_len) +{ + Size hoff = IndexInfoFindDataOffset(itup->t_info); + Size sz; + + sz = MAXALIGN(sizeof(IndexTupleData) + sizeof(BTPrefixCode) + + (hoff - sizeof(IndexTupleData)) + + (_bt_prefix_keysz(itup) - hoff - shared_len)); + if (BTreeTupleIsPosting(itup)) + sz = MAXALIGN(sz + BTreeTupleGetNPosting(itup) * sizeof(ItemPointerData)); + return sz; +} + +/* + * _bt_prefix_group_start + * Should `itup' start a new group? + * + * `rep' is the current group's representative and `prev' the preceding tuple + * (both NULL for the page's first tuple). Sets *shared to the bytes `itup' + * shares with the representative it ends up under (itself if it starts a + * group). This is the only grouping rule, shared by the CREATE INDEX + * estimate (_bt_prefix_est_add) and the layout (_bt_prefix_choose_groups), so + * the two cannot disagree. + * + * A group starts when `itup' shares nothing with `rep', or shares at least one + * MAXALIGN quantum more with `prev' than with `rep'. The second case keeps a + * long run of tuples that share much among themselves from being locked to a + * short accidental prefix of the page's first tuple (e.g., just a leading + * fixed-width column). The rule looks only backwards and the new group is + * led by `itup', so no earlier tuple is ever regrouped and the estimate stays + * exact tuple by tuple. + */ +static bool +_bt_prefix_group_start(IndexTuple rep, IndexTuple prev, IndexTuple itup, + Size *shared) +{ + Size s_rep; + + if (rep == NULL) + { + *shared = _bt_prefix_shared_len(itup, itup); + return true; + } + + s_rep = _bt_prefix_shared_len(rep, itup); + if (s_rep == 0) + { + *shared = _bt_prefix_shared_len(itup, itup); + return true; + } + + if (prev != NULL && prev != rep) + { + Size s_prev = _bt_prefix_shared_len(prev, itup); + + if (s_prev >= s_rep + MAXIMUM_ALIGNOF) + { + *shared = _bt_prefix_shared_len(itup, itup); + return true; + } + } + + *shared = s_rep; + return false; +} + +/* + * Running size estimate of a BTP_PREFIX page laid out from a sequence of plain + * tuples in key order, as _bt_prefix_form_page would lay it out (same + * grouping, same coded sizes). Used by CREATE INDEX to fill coded pages. + * The tuples passed to _bt_prefix_est_add must stay valid while the estimate + * is in use. + */ +void +_bt_prefix_est_add(BTPrefixPageEst *est, IndexTuple itup) +{ + Size plain = MAXALIGN(IndexTupleSize(itup)) + sizeof(ItemIdData); + Size shared; + + if (_bt_prefix_group_start(est->grouprep, est->prev, itup, &shared)) + { + est->grouprep = itup; + est->ngroups++; + est->anchorsz += MAXALIGN(MAXALIGN(sizeof(BTPrefixAnchorDisk)) + + _bt_prefix_keysz(itup)); + } + est->lastcoded = _bt_prefix_coded_size(est->grouprep, itup, shared) + + sizeof(ItemIdData); + est->maxcoded = Max(est->maxcoded, est->lastcoded - sizeof(ItemIdData)); + est->codedsz += est->lastcoded; + est->plainsz += plain; + est->maxplain = Max(est->maxplain, plain); + est->prev = itup; +} + +/* Bytes (items plus line pointers) the coded page would use */ +Size +_bt_prefix_est_coded(const BTPrefixPageEst *est) +{ + return _bt_prefix_diritem_size(est->ngroups, est->anchorsz) + + sizeof(ItemIdData) + est->codedsz; +} + +/* The directory and each member must fit the IndexTuple size field. */ +bool +_bt_prefix_est_representable(const BTPrefixPageEst *est) +{ + return _bt_prefix_diritem_size(est->ngroups, est->anchorsz) <= INDEX_SIZE_MASK && + est->maxcoded <= INDEX_SIZE_MASK; +} + +/* + * Is a coded page worth having, given its coded and plain sizes? Demand a + * real saving: decoding costs CPU on every access, so a page that would save + * only a few bytes stays plain. + */ +bool +_bt_prefix_worthwhile(Size codedsz, Size plainsz) +{ + return codedsz * 16 <= plainsz * 15; +} + +/* + * _bt_prefix_choose_groups + * Group plain tuples items[0..n-1], in key order, by + * _bt_prefix_group_start. + * + * Returns a palloc'd BTPrefixDir, or NULL when no two tuples share a group. + */ +static BTPrefixDir * +_bt_prefix_choose_groups(IndexTuple *items, int n) +{ + BTPrefixDir *dir; + int ngroups = 0; + + StaticAssertStmt(MaxIndexTuplesPerPage <= BTREE_PREFIX_MAXGROUPS, + "group number must fit in uint16"); + + if (n <= 1) + return NULL; + + dir = palloc(offsetof(BTPrefixDir, anchors) + sizeof(BTPrefixAnchor) * n); + for (int i = 0; i < n; i++) + { + IndexTuple rep = ngroups == 0 ? NULL : dir->anchors[ngroups - 1].rep; + IndexTuple prev = i == 0 ? NULL : items[i - 1]; + Size shared; + + if (_bt_prefix_group_start(rep, prev, items[i], &shared)) + dir->anchors[ngroups++].rep = items[i]; + } + + if (ngroups >= n) + { + pfree(dir); + return NULL; /* every tuple its own group: nothing shared */ + } + + dir->ngroups = ngroups; + return dir; +} + +/* + * Serialize `dir' as a palloc'd directory item, setting *itemsz to its size. + * The cached decoded sizes are left zero for _bt_prefix_recount. + */ +static IndexTuple +_bt_prefix_form_diritem(BTPrefixDir *dir, Size *itemsz) +{ + int ng = dir->ngroups; + Size total = _bt_prefix_diritem_size(ng, 0); + Size *anchoroff = palloc(sizeof(Size) * ng); + char *buf; + IndexTuple item; + BTPrefixDirHdr *hdr; + + for (int g = 0; g < ng; g++) + { + Size repsz = _bt_prefix_keysz(dir->anchors[g].rep); + + anchoroff[g] = total; + total += MAXALIGN(MAXALIGN(sizeof(BTPrefixAnchorDisk)) + repsz); + } + + if (total > INDEX_SIZE_MASK) + elog(ERROR, "nbtree prefix directory too large (%zu bytes)", total); + + buf = palloc0(total); + item = (IndexTuple) buf; + ItemPointerSetInvalid(&item->t_tid); + item->t_info = (unsigned short) total; /* size only; no null/varwidth */ + + hdr = (BTPrefixDirHdr *) buf; + hdr->ngroups = (uint16) ng; + hdr->decodedsz = 0; + hdr->maxdecoded = 0; + for (int g = 0; g < ng; g++) + hdr->anchoroff[g] = (uint16) anchoroff[g]; + + for (int g = 0; g < ng; g++) + { + BTPrefixAnchorDisk *ad = (BTPrefixAnchorDisk *) (buf + anchoroff[g]); + Size repsz = _bt_prefix_keysz(dir->anchors[g].rep); + IndexTuple rep; + + ad->repsz = (uint16) repsz; + /* store the key part only, as a plain non-posting tuple */ + rep = (IndexTuple) ((char *) ad + MAXALIGN(sizeof(BTPrefixAnchorDisk))); + memcpy(rep, dir->anchors[g].rep, repsz); + rep->t_info = (rep->t_info & ~(INDEX_SIZE_MASK | INDEX_ALT_TID_MASK)) | + repsz; + } + + pfree(anchoroff); + *itemsz = total; + return item; +} + +/* The directory item of a BTP_PREFIX page, unchecked. */ +static inline char * +_bt_prefix_diritem(Page page) +{ + BTPageOpaque opaque = BTPageGetOpaque(page); + OffsetNumber off = BTPageGetPrefixOff(opaque); + + Assert(P_HASPREFIX(opaque)); + return (char *) PageGetItem(page, PageGetItemId(page, off)); +} + +/* Pointer to anchor g's on-disk blob within the directory item. */ +static inline BTPrefixAnchorDisk * +_bt_prefix_anchor(char *diritem, int g) +{ + return (BTPrefixAnchorDisk *) (diritem + + ((BTPrefixDirHdr *) diritem)->anchoroff[g]); +} + +/* The representative IndexTuple inside an on-disk anchor blob. */ +static inline IndexTuple +_bt_prefix_anchor_rep(BTPrefixAnchorDisk *ad) +{ + return (IndexTuple) ((char *) ad + MAXALIGN(sizeof(BTPrefixAnchorDisk))); +} + +/* Report a malformed physical representation without interpreting its data. */ +pg_noreturn static void +_bt_prefix_corrupt(OffsetNumber offnum, const char *field) +{ + ereport(ERROR, + (errcode(ERRCODE_INDEX_CORRUPTED), + errmsg_internal("invalid prefix %s at offset %u", field, offnum))); +} + +/* Establish page bounds before using either line pointers or the opaque area. */ +static void +_bt_prefix_check_header(Page page) +{ + PageHeader phdr = (PageHeader) page; + BTPageOpaque opaque; + + if (phdr->pd_special != BLCKSZ - MAXALIGN(sizeof(BTPageOpaqueData)) || + phdr->pd_lower < SizeOfPageHeaderData || + phdr->pd_lower > phdr->pd_upper || + phdr->pd_upper > phdr->pd_special || + (phdr->pd_lower - SizeOfPageHeaderData) % sizeof(ItemIdData) != 0) + _bt_prefix_corrupt(InvalidOffsetNumber, "page header"); + + opaque = BTPageGetOpaque(page); + if (!P_HASPREFIX(opaque) || !P_ISLEAF(opaque) || P_IGNORE(opaque) || + P_ISMETA(opaque) || opaque->btpo_level != 0 || + PageGetMaxOffsetNumber(page) < P_FIRSTDATAKEY(opaque)) + _bt_prefix_corrupt(InvalidOffsetNumber, "page layout"); +} + +/* The caller has checked the page header, but not the line pointer. */ +static IndexTuple +_bt_prefix_checked_item(Page page, OffsetNumber offnum, Size minsize) +{ + ItemId itemid; + Size offset; + Size len; + IndexTuple itup; + + if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page)) + _bt_prefix_corrupt(offnum, "item offset"); + itemid = PageGetItemId(page, offnum); + offset = ItemIdGetOffset(itemid); + len = ItemIdGetLength(itemid); + if ((!ItemIdIsNormal(itemid) && !ItemIdIsDead(itemid)) || + offset != MAXALIGN(offset) || + offset < ((PageHeader) page)->pd_upper || + offset > ((PageHeader) page)->pd_special || + len > ((PageHeader) page)->pd_special - offset || len < minsize) + _bt_prefix_corrupt(offnum, "line pointer"); + itup = (IndexTuple) PageGetItem(page, itemid); + if (IndexTupleSize(itup) != len || len != MAXALIGN(len)) + _bt_prefix_corrupt(offnum, "tuple size"); + return itup; +} + +/* Check the directory header and offset array, without visiting any anchor. */ +static BTPrefixDirHdr * +_bt_prefix_checked_directory(Page page) +{ + OffsetNumber offnum = BTPageGetPrefixOff(BTPageGetOpaque(page)); + BTPrefixDirHdr *hdr = (BTPrefixDirHdr *) + _bt_prefix_checked_item(page, offnum, offsetof(BTPrefixDirHdr, anchoroff)); + Size len = IndexTupleSize(&hdr->header); + + if (hdr->header.t_info != len || + ItemPointerIsValid(&hdr->header.t_tid) || + ItemIdIsDead(PageGetItemId(page, offnum)) || + hdr->ngroups == 0 || hdr->ngroups > BTREE_PREFIX_MAXGROUPS || + _bt_prefix_diritem_size(hdr->ngroups, 0) > len) + _bt_prefix_corrupt(offnum, "directory header"); + return hdr; +} + +/* Validate just the selected anchor; never follow an unchecked byte offset. */ +static IndexTuple +_bt_prefix_checked_anchor(BTPrefixDirHdr *hdr, int group, OffsetNumber offnum) +{ + Size len = IndexTupleSize(&hdr->header); + Size offset; + BTPrefixAnchorDisk *ad; + IndexTuple rep; + + if (group >= hdr->ngroups) + _bt_prefix_corrupt(offnum, "group number"); + offset = hdr->anchoroff[group]; + if (offset != MAXALIGN(offset) || + offset < _bt_prefix_diritem_size(hdr->ngroups, 0) || + offset > len || + MAXALIGN(sizeof(BTPrefixAnchorDisk)) + sizeof(IndexTupleData) > len - offset) + _bt_prefix_corrupt(offnum, "anchor offset"); + ad = (BTPrefixAnchorDisk *) ((char *) hdr + offset); + if (ad->repsz < sizeof(IndexTupleData) || + ad->repsz > len - offset - MAXALIGN(sizeof(BTPrefixAnchorDisk))) + _bt_prefix_corrupt(offnum, "anchor size"); + rep = _bt_prefix_anchor_rep(ad); + if (IndexTupleSize(rep) != ad->repsz || + ad->repsz != MAXALIGN(ad->repsz) || + (rep->t_info & INDEX_ALT_TID_MASK) != 0 || + ad->repsz < IndexInfoFindDataOffset(rep->t_info)) + _bt_prefix_corrupt(offnum, "anchor tuple header"); + return rep; +} + +/* Check every source and destination extent used by the decoder. */ +static Size +_bt_prefix_check_member(BTPrefixDirHdr *hdr, IndexTuple coded, + OffsetNumber offnum, IndexTuple *repp) +{ + BTPrefixCode *code = (BTPrefixCode *) ((char *) coded + sizeof(IndexTupleData)); + IndexTuple rep = _bt_prefix_checked_anchor(hdr, code->group, offnum); + Size keysz = code->orig_info & INDEX_SIZE_MASK; + Size hoff = IndexInfoFindDataOffset(code->orig_info); + Size rephoff = IndexInfoFindDataOffset(rep->t_info); + Size bodysz; + Size plainsz = keysz; + Size codesz = IndexTupleSize(coded); + + if ((code->orig_info & INDEX_ALT_TID_MASK) != 0 || + keysz < hoff || keysz != MAXALIGN(keysz) || + (coded->t_info & (INDEX_NULL_MASK | INDEX_VAR_MASK)) != 0 || + BTreeTupleIsPivot(coded)) + _bt_prefix_corrupt(offnum, "member header"); + if (code->shared_len > keysz - hoff || + code->shared_len > IndexTupleSize(rep) - rephoff) + _bt_prefix_corrupt(offnum, "shared length"); + bodysz = MAXALIGN(sizeof(BTPrefixCode) + keysz - code->shared_len); + if (bodysz > codesz) + _bt_prefix_corrupt(offnum, "residual extent"); + if (BTreeTupleIsPosting(coded)) + { + Size listsz = BTreeTupleGetNPosting(coded) * sizeof(ItemPointerData); + + if (BTreeTupleGetNPosting(coded) < 2 || + (ItemPointerGetOffsetNumberNoCheck(&coded->t_tid) & + BT_STATUS_OFFSET_MASK) != BT_IS_POSTING || + BTreeTupleGetPostingOffset(coded) != bodysz || + listsz > codesz - bodysz || MAXALIGN(bodysz + listsz) != codesz) + _bt_prefix_corrupt(offnum, "posting list extent"); + plainsz = MAXALIGN(keysz + listsz); + } + else if (bodysz != codesz) + _bt_prefix_corrupt(offnum, "residual extent"); + if (plainsz > INDEX_SIZE_MASK || plainsz > BLCKSZ) + _bt_prefix_corrupt(offnum, "decoded tuple size"); + if (repp != NULL) + *repp = rep; + return plainsz; +} + +/* + * _bt_prefix_check + * Validate a whole BTP_PREFIX page; ERROR if it is malformed. + * + * For amcheck and pageinspect, before they read the page's tuples. Unlike + * decode, this also visits unused anchors and checks the cached decoded sizes + * against the split-fit invariant (see _bt_prefix_split_needed). + */ +void +_bt_prefix_check(Page page) +{ + BTPageOpaque opaque; + BTPrefixDirHdr *hdr; + OffsetNumber diroff; + Size end; + Size total = 0; + Size maxitem = 0; + Size hikeysz = 0; + Size usable = BLCKSZ - SizeOfPageHeaderData - MAXALIGN(sizeof(BTPageOpaqueData)); + + _bt_prefix_check_header(page); + opaque = BTPageGetOpaque(page); + diroff = BTPageGetPrefixOff(opaque); + hdr = _bt_prefix_checked_directory(page); + end = _bt_prefix_diritem_size(hdr->ngroups, 0); + for (int g = 0; g < hdr->ngroups; g++) + { + IndexTuple rep = _bt_prefix_checked_anchor(hdr, g, diroff); + + if (hdr->anchoroff[g] != end) + _bt_prefix_corrupt(diroff, "anchor layout"); + end += MAXALIGN(sizeof(BTPrefixAnchorDisk)) + IndexTupleSize(rep); + } + if (end != IndexTupleSize(&hdr->header)) + _bt_prefix_corrupt(diroff, "directory size"); + for (OffsetNumber off = P_FIRSTDATAKEY(opaque); + off <= PageGetMaxOffsetNumber(page); off++) + { + IndexTuple coded = _bt_prefix_checked_item(page, off, + sizeof(IndexTupleData) + sizeof(BTPrefixCode)); + Size sz = _bt_prefix_check_member(hdr, coded, off, NULL) + sizeof(ItemIdData); + + total += sz; + maxitem = Max(maxitem, sz); + } + if (total != hdr->decodedsz || maxitem != hdr->maxdecoded) + _bt_prefix_corrupt(diroff, "directory decoded size"); + if (!P_RIGHTMOST(opaque)) + { + IndexTuple hikey = _bt_prefix_checked_item(page, P_HIKEY, sizeof(IndexTupleData)); + + hikeysz = IndexTupleSize(hikey) + sizeof(ItemIdData); + } + if (total + hikeysz + 2 * maxitem + MAXALIGN(sizeof(ItemPointerData)) > 2 * usable) + _bt_prefix_corrupt(diroff, "decoded split budget"); +} + +/* + * Code plain tuple `itup' against group `group', whose representative is + * `rep'. Returns a palloc'd coded tuple, or NULL if its size does not fit + * INDEX_SIZE_MASK. + */ +static IndexTuple +_bt_prefix_encode_against(IndexTuple rep, IndexTuple itup, int group) +{ + Size hoff = IndexInfoFindDataOffset(itup->t_info); + Size keysz = _bt_prefix_keysz(itup); + bool posting = BTreeTupleIsPosting(itup); + Size shared_len; /* bytes of the data area taken from rep */ + Size residual; + Size bodysz; + Size codesz; + char *buf; + IndexTuple coded; + BTPrefixCode *code; + + shared_len = _bt_prefix_shared_len(rep, itup); + + residual = keysz - hoff - shared_len; + bodysz = MAXALIGN(sizeof(IndexTupleData) + sizeof(BTPrefixCode) + + (hoff - sizeof(IndexTupleData)) + residual); + codesz = bodysz; + if (posting) + codesz = MAXALIGN(bodysz + BTreeTupleGetNPosting(itup) * + sizeof(ItemPointerData)); + if (codesz > INDEX_SIZE_MASK) + return NULL; + + buf = palloc0(codesz); + coded = (IndexTuple) buf; + coded->t_tid = itup->t_tid; + coded->t_info = (unsigned short) codesz; + + code = (BTPrefixCode *) (buf + sizeof(IndexTupleData)); + code->group = (uint16) group; + code->shared_len = (uint16) shared_len; + /* flags and key-part size of the original; posting-ness is the coded's */ + code->orig_info = (itup->t_info & ~(INDEX_SIZE_MASK | INDEX_ALT_TID_MASK)) | + keysz; + + /* copy the original's null bitmap (bytes between header and data area) */ + memcpy(buf + sizeof(IndexTupleData) + sizeof(BTPrefixCode), + (char *) itup + sizeof(IndexTupleData), + hoff - sizeof(IndexTupleData)); + + /* copy the residual: the original's data-area bytes from shared_len on */ + memcpy(buf + sizeof(IndexTupleData) + sizeof(BTPrefixCode) + + (hoff - sizeof(IndexTupleData)), + (char *) itup + hoff + shared_len, residual); + + /* + * A posting list stays uncoded, in the standard posting tuple layout, so + * code that only reads heap TIDs (VACUUM, LP_DEAD hinting, deletion, + * posting list splits) works on the coded tuple as is. + */ + if (posting) + { + int nhtids = BTreeTupleGetNPosting(itup); + + BTreeTupleSetPosting(coded, nhtids, bodysz); + memcpy(BTreeTupleGetPosting(coded), BTreeTupleGetPosting(itup), + nhtids * sizeof(ItemPointerData)); + } + + return coded; +} + +/* + * _bt_prefix_decode + * Decode the data item at `offnum' on BTP_PREFIX page `page' into `buf'. + * + * Returns a pointer into `buf'. Every extent the copy reads or writes is + * validated first, so a corrupt page raises ERROR rather than reading past + * the page or overrunning `buf'. + */ +IndexTuple +_bt_prefix_decode(Page page, OffsetNumber offnum, BTItemBuf *buf) +{ + IndexTuple coded; + BTPrefixDirHdr *hdr; + BTPrefixCode *code; + IndexTuple rep; + Size rephoff; + Size hoff; + Size bitmaplen; + char *codebody; + Size residual; + char *out = buf->data; + IndexTuple plain = (IndexTuple) out; + Size keysz; + + _bt_prefix_check_header(page); + hdr = _bt_prefix_checked_directory(page); + coded = _bt_prefix_checked_item(page, offnum, + sizeof(IndexTupleData) + sizeof(BTPrefixCode)); + _bt_prefix_check_member(hdr, coded, offnum, &rep); + code = (BTPrefixCode *) ((char *) coded + sizeof(IndexTupleData)); + rephoff = IndexInfoFindDataOffset(rep->t_info); + hoff = IndexInfoFindDataOffset(code->orig_info); + bitmaplen = hoff - sizeof(IndexTupleData); + codebody = (char *) code + sizeof(BTPrefixCode); + + /* + * The original's key-part size is in orig_info; derive the residual + * length from it, not from the coded tuple's size (which has its own + * padding and any posting list). + */ + keysz = (code->orig_info & INDEX_SIZE_MASK); + residual = keysz - hoff - code->shared_len; + + /* header + null bitmap from the original */ + plain->t_tid = coded->t_tid; + plain->t_info = code->orig_info; + memcpy(out + sizeof(IndexTupleData), codebody, bitmaplen); + /* shared leading data bytes from the representative */ + memcpy(out + hoff, (char *) rep + rephoff, code->shared_len); + /* the member's own residual */ + memcpy(out + hoff + code->shared_len, codebody + bitmaplen, residual); + + if (BTreeTupleIsPosting(coded)) + { + int nhtids = BTreeTupleGetNPosting(coded); + Size listsz = nhtids * sizeof(ItemPointerData); + Size plainsz = MAXALIGN(keysz + listsz); + + Assert(plainsz <= BLCKSZ); + plain->t_info = (code->orig_info & ~INDEX_SIZE_MASK) | plainsz; + BTreeTupleSetPosting(plain, nhtids, keysz); + memcpy(out + keysz, BTreeTupleGetPosting(coded), listsz); + memset(out + keysz + listsz, 0, plainsz - keysz - listsz); + } + + return plain; +} + +/* + * _bt_prefix_form_page + * Lay out a BTP_PREFIX leaf from `hikey' and items[0..n-1]. + * + * `newpage' must be _bt_pageinit'd with its opaque area set; `hikey' is NULL + * on a rightmost page, and the items are plain and in key order. Returns + * false, leaving `newpage' unspecified, if coding does not pay off (unless + * `force'), the directory or a coded member exceeds INDEX_SIZE_MASK, or the + * coded items do not fit one page. The caller sets LSN and prune XID. + */ +bool +_bt_prefix_form_page(Page newpage, IndexTuple hikey, IndexTuple *items, int n, + bool force) +{ + BTPrefixPageEst est; + BTPrefixDir *dir; + IndexTuple diritem; + Size diritemsz; + OffsetNumber newoff; + bool ok = true; + + if (n <= 0) + return false; + + /* Is it worth it? The estimate is exact: same grouping, same sizes. */ + memset(&est, 0, sizeof(est)); + for (int i = 0; i < n; i++) + _bt_prefix_est_add(&est, items[i]); + if (!_bt_prefix_est_representable(&est) || + (!force && !_bt_prefix_worthwhile(_bt_prefix_est_coded(&est), + est.plainsz))) + return false; + + dir = _bt_prefix_choose_groups(items, n); + if (dir == NULL) + { + Assert(!force || n == 1); + return false; /* nothing shared */ + } + + if (hikey && + PageAddItem(newpage, hikey, MAXALIGN(IndexTupleSize(hikey)), P_HIKEY, + false, false) == InvalidOffsetNumber) + elog(ERROR, "could not add high key during prefix compression"); + + diritem = _bt_prefix_form_diritem(dir, &diritemsz); + if (PageAddItem(newpage, diritem, diritemsz, + BTPageGetPrefixOff(BTPageGetOpaque(newpage)), + false, false) == InvalidOffsetNumber) + ok = false; + newoff = OffsetNumberNext(BTPageGetPrefixOff(BTPageGetOpaque(newpage))); + + for (int i = 0, g = 0; ok && i < n; i++) + { + IndexTuple coded; + + while (g + 1 < dir->ngroups && items[i] == dir->anchors[g + 1].rep) + g++; + + coded = _bt_prefix_encode_against(dir->anchors[g].rep, items[i], g); + Assert(coded != NULL); + if (PageAddItem(newpage, coded, IndexTupleSize(coded), newoff, + false, false) == InvalidOffsetNumber) + ok = false; /* the coded items do not fit one page */ + newoff = OffsetNumberNext(newoff); + pfree(coded); + } + + pfree(diritem); + pfree(dir); + if (!ok) + return false; + + BTPageGetOpaque(newpage)->btpo_flags |= BTP_PREFIX; + _bt_prefix_recount(newpage); + +#ifdef USE_ASSERT_CHECKING + /* decode must reproduce every plain tuple byte for byte */ + for (int i = 0; i < n; i++) + { + BTItemBuf chk; + IndexTuple d = _bt_getitem(newpage, + P_FIRSTDATAKEY(BTPageGetOpaque(newpage)) + i, + &chk); + + Assert(IndexTupleSize(d) == IndexTupleSize(items[i]) && + memcmp(d, items[i], IndexTupleSize(d)) == 0); + } +#endif + + return true; +} + +/* + * _bt_prefix_compress_page + * Rewrite plain leaf `page' in BTP_PREFIX form, in place, if that pays + * off; otherwise leave it unchanged. + */ +void +_bt_prefix_compress_page(Relation index, Page page) +{ + BTPageOpaque opaque = BTPageGetOpaque(page); + OffsetNumber minoff, + maxoff; + int n; + IndexTuple *items; + IndexTuple hikey = NULL; + Page newpage; + + if (!_bt_prefix_enabled(index) || !P_ISLEAF(opaque) || P_HASPREFIX(opaque)) + return; + + minoff = P_FIRSTDATAKEY(opaque); + maxoff = PageGetMaxOffsetNumber(page); + if (maxoff < minoff) + return; /* empty page */ + n = maxoff - minoff + 1; + + if (!P_RIGHTMOST(opaque)) + hikey = (IndexTuple) PageGetItem(page, PageGetItemId(page, P_HIKEY)); + + items = palloc(sizeof(IndexTuple) * n); + for (int i = 0; i < n; i++) + items[i] = (IndexTuple) PageGetItem(page, + PageGetItemId(page, minoff + i)); + + /* Heap-allocated: this runs inside _bt_split, already two pages deep. */ + newpage = (Page) palloc_aligned(BLCKSZ, PG_IO_ALIGN_SIZE, 0); + _bt_pageinit(newpage, BLCKSZ); + memcpy(BTPageGetOpaque(newpage), opaque, sizeof(BTPageOpaqueData)); + if (_bt_prefix_form_page(newpage, hikey, items, n, false)) + { + PageSetLSN(newpage, PageGetLSN(page)); + ((PageHeader) newpage)->pd_prune_xid = ((PageHeader) page)->pd_prune_xid; + memcpy(page, newpage, BLCKSZ); + } + pfree(newpage); + pfree(items); +} + +/* + * _bt_prefix_encode_insert + * Code plain tuple `itup' for insertion at `newitemoff' on BTP_PREFIX + * page `page'. + * + * The tuple joins the group of the item it displaces (or of the last item, + * when appended), sharing however much it happens to share, possibly nothing. + * The result is at most BTREE_PREFIX_CODE_OVERHEAD larger than `itup'. + * Returns a palloc'd coded tuple, or NULL when it exceeds INDEX_SIZE_MASK and + * the page must split. NB: pallocs, so call it before the critical section. + */ +IndexTuple +_bt_prefix_encode_insert(Page page, OffsetNumber newitemoff, IndexTuple itup) +{ + BTPageOpaque opaque = BTPageGetOpaque(page); + char *diritem = _bt_prefix_diritem(page); + OffsetNumber maxoff = PageGetMaxOffsetNumber(page); + OffsetNumber neighbor; + IndexTuple ncoded; + BTPrefixCode *ncode; + BTPrefixAnchorDisk *ad; + IndexTuple rep; + int group; + + Assert(P_HASPREFIX(opaque)); + + if (newitemoff <= maxoff && newitemoff >= P_FIRSTDATAKEY(opaque)) + neighbor = newitemoff; + else if (maxoff >= P_FIRSTDATAKEY(opaque)) + neighbor = maxoff; + else + { + /* no data items: use group 0 */ + ad = _bt_prefix_anchor(diritem, 0); + return _bt_prefix_encode_against(_bt_prefix_anchor_rep(ad), itup, 0); + } + + ncoded = (IndexTuple) PageGetItem(page, PageGetItemId(page, neighbor)); + ncode = (BTPrefixCode *) ((char *) ncoded + sizeof(IndexTupleData)); + group = ncode->group; + ad = _bt_prefix_anchor(diritem, group); + rep = _bt_prefix_anchor_rep(ad); + + return _bt_prefix_encode_against(rep, itup, group); +} + +/* + * _bt_prefix_recode + * Code plain tuple `itup' against the group of the item at `offnum' on + * BTP_PREFIX page `page', returning a palloc'd coded tuple. + * + * For a tuple with the same key as that item (a split or merged posting + * list), which therefore codes the same way. NB: pallocs, so call it before + * the critical section. + */ +IndexTuple +_bt_prefix_recode(Page page, OffsetNumber offnum, IndexTuple itup) +{ + IndexTuple ncoded = (IndexTuple) PageGetItem(page, PageGetItemId(page, offnum)); + BTPrefixCode *ncode = (BTPrefixCode *) ((char *) ncoded + + sizeof(IndexTupleData)); + BTPrefixAnchorDisk *ad = _bt_prefix_anchor(_bt_prefix_diritem(page), + ncode->group); + IndexTuple rep = _bt_prefix_anchor_rep(ad); + IndexTuple coded; + + coded = _bt_prefix_encode_against(rep, itup, ncode->group); + if (coded == NULL) + elog(ERROR, "coded nbtree posting tuple too large"); + return coded; +} + +/* + * _bt_prefix_decode_copy + * Return a palloc'd decoded copy of the item at `offnum' on BTP_PREFIX + * page `page'. + * + * The BLCKSZ decode buffer lives in this frame, so hot-path callers need not + * reserve one on their own stack for a case that arises only on coded pages. + */ +IndexTuple +_bt_prefix_decode_copy(Page page, OffsetNumber offnum) +{ + BTItemBuf decbuf; + + return CopyIndexTuple(_bt_prefix_decode(page, offnum, &decbuf)); +} + +/* + * _bt_prefix_decode_items + * Decode every data item of BTP_PREFIX page `page'. + * + * Sets *items_out to a palloc'd array of palloc'd plain tuples and returns + * its length. *hikey gets a palloc'd copy of the high key and *hikeysz its + * line pointer length (NULL and 0 on a rightmost page). The caller frees all + * of it. + */ +int +_bt_prefix_decode_items(Page page, IndexTuple **items_out, + IndexTuple *hikey, Size *hikeysz) +{ + BTPageOpaque opaque = BTPageGetOpaque(page); + OffsetNumber minoff = P_FIRSTDATAKEY(opaque); + OffsetNumber maxoff = PageGetMaxOffsetNumber(page); + int n = (maxoff >= minoff) ? (maxoff - minoff + 1) : 0; + IndexTuple *items = n ? palloc(sizeof(IndexTuple) * n) : NULL; + BTItemBuf decbuf; + int k = 0; + + if (!P_RIGHTMOST(opaque)) + { + ItemId hii = PageGetItemId(page, P_HIKEY); + + *hikey = CopyIndexTuple((IndexTuple) PageGetItem(page, hii)); + *hikeysz = ItemIdGetLength(hii); + } + else + { + *hikey = NULL; + *hikeysz = 0; + } + + for (OffsetNumber off = minoff; off <= maxoff; off = OffsetNumberNext(off)) + { + items[k++] = CopyIndexTuple(_bt_prefix_decode(page, off, &decbuf)); + } + *items_out = items; + return n; +} + +/* + * _bt_prefix_try_plain_page + * Write a plain copy of BTP_PREFIX page `page' into BLCKSZ buffer `out'. + * + * Returns `out', or NULL if the decoded content does not fit one page, in + * which case `out' is left partly written. + */ +Page +_bt_prefix_try_plain_page(Relation rel, Page page, Page out) +{ + BTPageOpaque opaque = BTPageGetOpaque(page); + OffsetNumber minoff = P_FIRSTDATAKEY(opaque); + OffsetNumber maxoff = PageGetMaxOffsetNumber(page); + OffsetNumber newoff; + BTItemBuf decbuf; + + _bt_pageinit(out, BLCKSZ); + memcpy(BTPageGetOpaque(out), opaque, sizeof(BTPageOpaqueData)); + BTPageGetOpaque(out)->btpo_flags &= ~BTP_PREFIX; + + if (!P_RIGHTMOST(opaque)) + { + ItemId hii = PageGetItemId(page, P_HIKEY); + + if (PageAddItem(out, PageGetItem(page, hii), ItemIdGetLength(hii), + P_HIKEY, false, false) == InvalidOffsetNumber) + return NULL; + } + + newoff = P_FIRSTDATAKEY(BTPageGetOpaque(out)); + for (OffsetNumber off = minoff; off <= maxoff; off = OffsetNumberNext(off)) + { + IndexTuple pt = _bt_prefix_decode(page, off, &decbuf); + + if (PageAddItem(out, pt, IndexTupleSize(pt), newoff, false, false) == + InvalidOffsetNumber) + return NULL; /* decoded content exceeds a page */ + newoff = OffsetNumberNext(newoff); + } + + return out; +} + +/* + * MAXALIGN'd size of coded member `coded' once decoded, from its header alone. + * + * NB: the split-fit invariant (see _bt_prefix_split_needed) needs this to be + * the same unit _bt_prefix_findsplitloc and the CREATE INDEX estimate use, + * MAXALIGN(IndexTupleSize()) of the plain tuple. + */ +static inline Size +_bt_prefix_plain_size(IndexTuple coded) +{ + BTPrefixCode *code = (BTPrefixCode *) ((char *) coded + + sizeof(IndexTupleData)); + Size keysz = code->orig_info & INDEX_SIZE_MASK; + + if (BTreeTupleIsPosting(coded)) + return MAXALIGN(keysz + BTreeTupleGetNPosting(coded) * + sizeof(ItemPointerData)); + return MAXALIGN(keysz); +} + +/* + * _bt_prefix_split_needed + * Must inserting a plain tuple of (MAXALIGN'd) size `newitemsz' into + * BTP_PREFIX page `page' split it first? + * + * The split-fit guarantee. A coded page may hold more decoded content than a + * plain page, but its decoded items must always split into two plain pages. + * Each coded page keeps + * + * T + hikey + 2 * m + heap TID <= 2 * usable (*) + * + * where T is the decoded size of its data items (including line pointers) and + * m the largest. Under (*) a split of the page plus a new item x always has a + * legal point when x was admitted by this test, because admitting x requires + * (*) to hold with x counted in T and m. Proof: take the leftmost point whose + * right half (items plus the old high key) fits. The point before it did + * not, so the left items before it total less than T - (usable - hikey); + * adding one more item and the new high key (a truncated copy of firstright + * plus a heap TID) gives a left half under T - usable + hikey + 2m + heap TID, + * at most usable by (*). + * + * So insert splits a page before it would break (*). _bt_split's split then + * places the new item too: (*) with the new item counted is exactly what + * failed, but the page without it satisfied (*), and a page that a plain + * split would handle (decoded content at most one page) always has a legal + * point by the usual one-third-of-a-page item size rule; the remaining case + * (content between one and two pages, new item large) is handled by + * _bt_prefix_findsplitloc trying the split without the new item first. + */ +bool +_bt_prefix_split_needed(Page page, Size newitemsz) +{ + BTPageOpaque opaque = BTPageGetOpaque(page); + BTPrefixDirHdr *hdr = (BTPrefixDirHdr *) _bt_prefix_diritem(page); + Size usable = BLCKSZ - SizeOfPageHeaderData - + MAXALIGN(sizeof(BTPageOpaqueData)); + Size newsz = MAXALIGN(newitemsz) + sizeof(ItemIdData); + Size total = hdr->decodedsz + newsz; + Size maxitem = Max((Size) hdr->maxdecoded, newsz); + Size hikeysz = 0; + + if (!P_RIGHTMOST(opaque)) + hikeysz = MAXALIGN(ItemIdGetLength(PageGetItemId(page, P_HIKEY))) + + sizeof(ItemIdData); + + return total + hikeysz + 2 * maxitem + MAXALIGN(sizeof(ItemPointerData)) > + 2 * usable; +} + +/* + * _bt_prefix_recount + * Recompute the directory's cached decoded sizes after a change to the + * page's data items (deletion, posting list update, a rebuilt page), or + * drop the directory if no data items remain. Page-only, so WAL redo + * calls it after replaying the same change and reproduces the page. + */ +void +_bt_prefix_recount(Page page) +{ + BTPageOpaque opaque = BTPageGetOpaque(page); + OffsetNumber minoff, + maxoff; + BTPrefixDirHdr *hdr; + Size total = 0, + maxitem = 0; + + if (!P_HASPREFIX(opaque)) + return; + + minoff = P_FIRSTDATAKEY(opaque); + maxoff = PageGetMaxOffsetNumber(page); + if (maxoff < minoff) + { + /* + * An emptied leaf holds only its high key (page deletion relies on + * that): drop the directory and become a plain page. + */ + PageIndexTupleDelete(page, BTPageGetPrefixOff(opaque)); + opaque->btpo_flags &= ~BTP_PREFIX; + return; + } + + for (OffsetNumber off = minoff; off <= maxoff; off = OffsetNumberNext(off)) + { + IndexTuple coded = (IndexTuple) PageGetItem(page, PageGetItemId(page, off)); + Size sz = _bt_prefix_plain_size(coded) + sizeof(ItemIdData); + + total += sz; + maxitem = Max(maxitem, sz); + } + Assert(total <= PG_UINT16_MAX); + hdr = (BTPrefixDirHdr *) _bt_prefix_diritem(page); + hdr->decodedsz = (uint16) total; + hdr->maxdecoded = (uint16) maxitem; +} + +/* + * _bt_prefix_note_insert + * Account for coded item `coded' just added to BTP_PREFIX page `page'. + * Page-only; insert redo calls it too. + */ +void +_bt_prefix_note_insert(Page page, IndexTuple coded) +{ + BTPrefixDirHdr *hdr = (BTPrefixDirHdr *) _bt_prefix_diritem(page); + Size sz = _bt_prefix_plain_size(coded) + sizeof(ItemIdData); + + Assert(hdr->decodedsz + sz <= PG_UINT16_MAX); + hdr->decodedsz += (uint16) sz; + hdr->maxdecoded = (uint16) Max((Size) hdr->maxdecoded, sz); +} + +/* + * _bt_prefix_findsplitloc + * Choose a split point for coded leaf `page' from its decoded items. + * + * ditems[] holds one plain tuple per data item. Returns firstrightoff and + * sets *newitemonleft, as _bt_findsplitloc does. With newitemoff valid the + * new item, of plain size newitemsz, is placed there, and the result is + * InvalidOffsetNumber if no point keeps both halves within a page. With + * newitemoff invalid only the existing items are split, and the split-fit + * invariant (see _bt_prefix_split_needed) guarantees a legal point. + * + * Each candidate is checked against the real sizes of both plain halves: the + * left half's new high key is charged as firstright plus a heap TID, as + * _bt_findsplitloc does, and the right half keeps the old high key. The most + * even legal point wins, except on a rightmost page, where points are ranked + * by leaf fillfactor as _bt_findsplitloc ranks them, so ascending inserts + * leave fillfactor-full left pages behind. + */ +OffsetNumber +_bt_prefix_findsplitloc(Relation rel, Page page, IndexTuple *ditems, + OffsetNumber newitemoff, Size newitemsz, + bool *newitemonleft) +{ + BTPageOpaque opaque = BTPageGetOpaque(page); + OffsetNumber mn = P_FIRSTDATAKEY(opaque); + OffsetNumber maxoff = PageGetMaxOffsetNumber(page); + bool hasnew = OffsetNumberIsValid(newitemoff); + int n = maxoff - mn + 1; /* existing items */ + int nall = n + (hasnew ? 1 : 0); + int newpos = hasnew ? newitemoff - mn : -1; + Size usable = BLCKSZ - SizeOfPageHeaderData - + MAXALIGN(sizeof(BTPageOpaqueData)); + Size hikeysz = 0; + Size *sz = palloc(sizeof(Size) * nall); + Size total = 0, + acc = 0; + int best = -1; + Size bestdelta = SIZE_MAX; + + if (!P_RIGHTMOST(opaque)) + hikeysz = MAXALIGN(ItemIdGetLength(PageGetItemId(page, P_HIKEY))) + + sizeof(ItemIdData); + + /* sizes of the combined sequence, new item spliced in at newpos */ + for (int k = 0, i = 0; k < nall; k++) + { + if (k == newpos) + sz[k] = MAXALIGN(newitemsz) + sizeof(ItemIdData); + else + sz[k] = MAXALIGN(IndexTupleSize(ditems[i++])) + sizeof(ItemIdData); + total += sz[k]; + } + + /* split before position k: left = [0,k), right = [k,nall) */ + for (int k = 1; k < nall; k++) + { + Size left, + right; + + acc += sz[k - 1]; + left = acc + sz[k] + MAXALIGN(sizeof(ItemPointerData)); + right = (total - acc) + hikeysz; + if (left <= usable && right <= usable) + { + Size delta = left > right ? left - right : right - left; + + if (P_RIGHTMOST(opaque)) + { + double fillfactormult = BTGetFillFactor(rel) / 100.0; + int16 weighteddelta; + + weighteddelta = fillfactormult * (usable - left) - + (1.0 - fillfactormult) * (usable - right); + delta = abs(weighteddelta); + } + + if (delta < bestdelta) + { + bestdelta = delta; + best = k; + } + } + } + pfree(sz); + + /* + * With a new item there may be no legal point (the item is large and the + * page dense); the caller then splits the existing items alone. + */ + if (best < 0) + { + if (hasnew) + return InvalidOffsetNumber; + elog(ERROR, "could not find a legal split point for prefix-compressed page in index \"%s\"", + RelationGetRelationName(rel)); + } + + /* map combined position back to (firstrightoff, newitemonleft) */ + if (!hasnew || best <= newpos) + { + *newitemonleft = false; + return mn + best; + } + *newitemonleft = true; + return mn + best - 1; +} diff --git a/src/backend/access/nbtree/nbtreadpage.c b/src/backend/access/nbtree/nbtreadpage.c index 55722fd8791bd..eb5a83233a997 100644 --- a/src/backend/access/nbtree/nbtreadpage.c +++ b/src/backend/access/nbtree/nbtreadpage.c @@ -22,6 +22,7 @@ #include "access/relscan.h" #include "storage/predicate.h" #include "utils/datum.h" +#include "utils/memutils.h" #include "utils/rel.h" @@ -110,6 +111,27 @@ static bool _bt_verify_keys_with_arraykeys(IndexScanDesc scan); #endif +/* + * _bt_scan_skip_key -- can _bt_readpage skip decoding the current item? + * + * Decoding a coded item costs a copy, wasted when (a) this is not an + * index-only scan, so only the heap TID or posting list is needed, and coding + * leaves both in place; and (b) _bt_checkkeys would read no key attribute, + * because startikey has passed every scan key and there are no array keys + * (array-key advancement reads the key regardless of startikey). The caller + * then treats the item as a match and reads it raw. + * + * NB: the _bt_checkkeys call must be skipped, not just the decode. In + * assert-enabled builds it re-runs _bt_check_compare from ikey 0 to verify + * startikey, which would read the still-coded key. + */ +static inline bool +_bt_scan_skip_key(BTScanOpaque so, BTReadPageState *pstate, bool arrayKeys) +{ + return so->currTuples == NULL && !arrayKeys && + pstate->startikey >= so->numberOfKeys; +} + /* * _bt_readpage() -- Load data from current index page into so->currPos * @@ -141,6 +163,8 @@ _bt_readpage(IndexScanDesc scan, ScanDirection dir, OffsetNumber offnum, OffsetNumber minoff; OffsetNumber maxoff; BTReadPageState pstate; + BTItemBuf itupbuf; /* decode workspace for a loop's current item */ + BTItemBuf finalbuf; /* decode workspace for finaltup */ bool arrayKeys, ignore_killed_tuples = scan->ignore_killed_tuples; int itemIndex, @@ -156,6 +180,26 @@ _bt_readpage(IndexScanDesc scan, ScanDirection dir, OffsetNumber offnum, pstate.dir = so->currPos.dir = dir; so->currPos.nextTupleOffset = 0; + /* + * A prefix-compressed leaf can decode to up to two pages of tuples (see + * _bt_prefix_split_needed), more than the BLCKSZ index-only scan + * workspaces hold. Grow them the first time such a page is read. + */ + if (unlikely(P_HASPREFIX(opaque)) && so->currTuples && !so->bigTuples) + { + char *big; + + big = MemoryContextAlloc(GetMemoryChunkContext(so->currTuples), + 4 * BLCKSZ); + if (BTScanPosIsValid(so->markPos)) + memcpy(big + 2 * BLCKSZ, so->markTuples, + so->markPos.nextTupleOffset); + pfree(so->currTuples); + so->currTuples = big; + so->markTuples = big + 2 * BLCKSZ; + so->bigTuples = true; + } + /* either moreRight or moreLeft should be set now (may be unset later) */ Assert(ScanDirectionIsForward(dir) ? so->currPos.moreRight : so->currPos.moreLeft); @@ -252,12 +296,23 @@ _bt_readpage(IndexScanDesc scan, ScanDirection dir, OffsetNumber offnum, continue; } - itup = (IndexTuple) PageGetItem(page, iid); - Assert(!BTreeTupleIsPivot(itup)); + if (_bt_scan_skip_key(so, &pstate, arrayKeys)) + { + /* only the heap TID(s) are needed: read the item raw */ + itup = (IndexTuple) PageGetItem(page, iid); + Assert(!BTreeTupleIsPivot(itup)); + pstate.offnum = offnum; + passes_quals = true; + } + else + { + itup = _bt_getitem(page, offnum, &itupbuf); + Assert(!BTreeTupleIsPivot(itup)); - pstate.offnum = offnum; - passes_quals = _bt_checkkeys(scan, &pstate, arrayKeys, - itup, indnatts); + pstate.offnum = offnum; + passes_quals = _bt_checkkeys(scan, &pstate, arrayKeys, + itup, indnatts); + } /* * Check if we need to skip ahead to a later tuple (only possible @@ -353,9 +408,7 @@ _bt_readpage(IndexScanDesc scan, ScanDirection dir, OffsetNumber offnum, { if (minoff <= maxoff && !P_LEFTMOST(opaque)) { - ItemId iid = PageGetItemId(page, minoff); - - pstate.finaltup = (IndexTuple) PageGetItem(page, iid); + pstate.finaltup = _bt_getitem(page, minoff, &finalbuf); if (unlikely(so->scanBehind) && !_bt_scanbehind_checkkeys(scan, dir, pstate.finaltup)) @@ -415,19 +468,36 @@ _bt_readpage(IndexScanDesc scan, ScanDirection dir, OffsetNumber offnum, else tuple_alive = true; - itup = (IndexTuple) PageGetItem(page, iid); - Assert(!BTreeTupleIsPivot(itup)); - pstate.offnum = offnum; - if (arrayKeys && offnum == minoff && pstate.forcenonrequired) + if (_bt_scan_skip_key(so, &pstate, arrayKeys)) { - /* Reset arrays, per _bt_set_startikey contract */ - pstate.forcenonrequired = false; - pstate.startikey = 0; - _bt_start_array_keys(scan, dir); + /* only the heap TID(s) are needed: read the item raw */ + itup = (IndexTuple) PageGetItem(page, iid); + Assert(!BTreeTupleIsPivot(itup)); + passes_quals = true; + } + else + { + /* + * Reuse finaltup's decoded copy at minoff, so that + * _bt_advance_array_keys still recognizes it by pointer. + */ + if (offnum == minoff && pstate.finaltup) + itup = pstate.finaltup; + else + itup = _bt_getitem(page, offnum, &itupbuf); + Assert(!BTreeTupleIsPivot(itup)); + + if (arrayKeys && offnum == minoff && pstate.forcenonrequired) + { + /* Reset arrays, per _bt_set_startikey contract */ + pstate.forcenonrequired = false; + pstate.startikey = 0; + _bt_start_array_keys(scan, dir); + } + passes_quals = _bt_checkkeys(scan, &pstate, arrayKeys, + itup, indnatts); } - passes_quals = _bt_checkkeys(scan, &pstate, arrayKeys, - itup, indnatts); if (arrayKeys && so->scanBehind) { @@ -596,7 +666,8 @@ _bt_set_startikey(IndexScanDesc scan, BTReadPageState *pstate) BTScanOpaque so = (BTScanOpaque) scan->opaque; Relation rel = scan->indexRelation; TupleDesc tupdesc = RelationGetDescr(rel); - ItemId iid; + BTItemBuf firstbuf, + lastbuf; IndexTuple firsttup, lasttup; int startikey = 0, @@ -616,12 +687,10 @@ _bt_set_startikey(IndexScanDesc scan, BTReadPageState *pstate) return; /* minoff is an offset to the lowest non-pivot tuple on the page */ - iid = PageGetItemId(pstate->page, pstate->minoff); - firsttup = (IndexTuple) PageGetItem(pstate->page, iid); + firsttup = _bt_getitem(pstate->page, pstate->minoff, &firstbuf); /* maxoff is an offset to the highest non-pivot tuple on the page */ - iid = PageGetItemId(pstate->page, pstate->maxoff); - lasttup = (IndexTuple) PageGetItem(pstate->page, iid); + lasttup = _bt_getitem(pstate->page, pstate->maxoff, &lastbuf); /* Determine the first attribute whose values change on caller's page */ firstchangingattnum = _bt_keep_natts_fast(rel, firsttup, lasttup); @@ -2053,6 +2122,7 @@ _bt_checkkeys_look_ahead(IndexScanDesc scan, BTReadPageState *pstate, ScanDirection dir = pstate->dir; OffsetNumber aheadoffnum; IndexTuple ahead; + BTItemBuf aheadbuf; Assert(!pstate->forcenonrequired); @@ -2088,8 +2158,7 @@ _bt_checkkeys_look_ahead(IndexScanDesc scan, BTReadPageState *pstate, aheadoffnum = Max((int) pstate->minoff, (int) pstate->offnum - pstate->targetdistance); - ahead = (IndexTuple) PageGetItem(pstate->page, - PageGetItemId(pstate->page, aheadoffnum)); + ahead = _bt_getitem(pstate->page, aheadoffnum, &aheadbuf); if (_bt_tuple_before_array_skeys(scan, dir, ahead, tupdesc, tupnatts, false, 0, NULL)) { diff --git a/src/backend/access/nbtree/nbtree.c b/src/backend/access/nbtree/nbtree.c index ef9ed290caea8..a3a8de477a27f 100644 --- a/src/backend/access/nbtree/nbtree.c +++ b/src/backend/access/nbtree/nbtree.c @@ -379,6 +379,7 @@ btbeginscan(Relation rel, int nkeys, int norderbys) * scan->xs_itupdesc whether we'll need it or not, since that's so cheap. */ so->currTuples = so->markTuples = NULL; + so->bigTuples = false; scan->xs_itupdesc = RelationGetDescr(rel); diff --git a/src/backend/access/nbtree/nbtsearch.c b/src/backend/access/nbtree/nbtsearch.c index 61f63251c6f31..7eaf626e8f1ac 100644 --- a/src/backend/access/nbtree/nbtsearch.c +++ b/src/backend/access/nbtree/nbtsearch.c @@ -33,6 +33,11 @@ static Buffer _bt_moveright(Relation rel, Relation heaprel, BTScanInsert key, Buffer buf, bool forupdate, BTStack stack, int access); static OffsetNumber _bt_binsrch(Relation rel, BTScanInsert key, Buffer buf); +static int32 _bt_compare_coded(Relation rel, BTScanInsert key, Page page, + OffsetNumber offnum); +static inline int32 _bt_compare_tuple(Relation rel, BTScanInsert key, + Page page, OffsetNumber offnum, + IndexTuple itup); static int _bt_binsrch_posting(BTScanInsert key, Page page, OffsetNumber offnum); static inline void _bt_returnitem(IndexScanDesc scan, BTScanOpaque so); @@ -692,17 +697,54 @@ _bt_compare(Relation rel, BTScanInsert key, Page page, OffsetNumber offnum) +{ + BTPageOpaque opaque = BTPageGetOpaque(page); + + if (unlikely(P_HASPREFIX(opaque)) && offnum > BTPageGetPrefixOff(opaque)) + return _bt_compare_coded(rel, key, page, offnum); + + Assert(_bt_check_natts(rel, key->heapkeyspace, page, offnum)); + return _bt_compare_tuple(rel, key, page, offnum, + (IndexTuple) PageGetItem(page, + PageGetItemId(page, offnum))); +} + +/* + * _bt_compare_coded() -- _bt_compare() for a coded prefix-compressed leaf item. + * + * Kept out of line so that only these comparisons pay for the decode buffer, + * which is a whole BLCKSZ; _bt_compare() on a plain page uses no stack for it. + */ +static pg_noinline int32 +_bt_compare_coded(Relation rel, BTScanInsert key, Page page, + OffsetNumber offnum) +{ + BTItemBuf prefixbuf; + + /* Decode (and so validate) the member before assertions inspect it. */ + IndexTuple itup = _bt_prefix_decode(page, offnum, &prefixbuf); + + Assert(_bt_check_natts(rel, key->heapkeyspace, page, offnum)); + return _bt_compare_tuple(rel, key, page, offnum, itup); +} + +/* + * _bt_compare_tuple() -- body of _bt_compare(), given the item at offnum. + * + * itup is either the tuple on the page or its decoded copy. + */ +static inline int32 +_bt_compare_tuple(Relation rel, BTScanInsert key, Page page, + OffsetNumber offnum, IndexTuple itup) { TupleDesc itupdesc = RelationGetDescr(rel); BTPageOpaque opaque = BTPageGetOpaque(page); - IndexTuple itup; ItemPointer heapTid; ScanKey scankey; int ncmpkey; int ntupatts; int32 result; - Assert(_bt_check_natts(rel, key->heapkeyspace, page, offnum)); Assert(key->keysz <= IndexRelationGetNumberOfKeyAttributes(rel)); Assert(key->heapkeyspace || key->scantid == NULL); @@ -713,7 +755,6 @@ _bt_compare(Relation rel, if (!P_ISLEAF(opaque) && offnum == P_FIRSTDATAKEY(opaque)) return 1; - itup = (IndexTuple) PageGetItem(page, PageGetItemId(page, offnum)); ntupatts = BTreeTupleGetNAtts(itup, rel); /* diff --git a/src/backend/access/nbtree/nbtsort.c b/src/backend/access/nbtree/nbtsort.c index 756dfa3dcf47e..51fd7942261d2 100644 --- a/src/backend/access/nbtree/nbtsort.c +++ b/src/backend/access/nbtree/nbtsort.c @@ -242,6 +242,17 @@ typedef struct BTPageState uint32 btps_level; /* tree level (0 = leaf) */ Size btps_full; /* "full" if less than this much free space */ struct BTPageState *btps_next; /* link to parent level, if any */ + + /* + * Leaf level of a prefix_compression build: tuples are collected here + * instead of on btps_buf, and laid out as a leaf, coded or plain, when + * the next tuple would overfill it. See _bt_buildadd_coded. + */ + IndexTuple *btps_items; /* pending leaf tuples, palloc'd copies */ + int btps_nitems; + int btps_maxitems; + BTPrefixPageEst btps_est; /* coded estimate of btps_items */ + Size btps_lastkey; /* worst-case high key from the last item */ } BTPageState; /* @@ -268,6 +279,10 @@ static void _bt_build_callback(Relation index, ItemPointer tid, Datum *values, static BulkWriteBuffer _bt_blnewpage(BTWriteState *wstate, uint32 level); static BTPageState *_bt_pagestate(BTWriteState *wstate, uint32 level); static void _bt_slideleft(Page rightmostpage); +static void _bt_buildadd_coded(BTWriteState *wstate, BTPageState *state, + IndexTuple itup, Size truncextra); +static void _bt_flush_coded(BTWriteState *wstate, BTPageState *state, + bool last); static void _bt_sortaddtup(Page page, Size itemsize, const IndexTupleData *itup, OffsetNumber itup_off, bool newfirstdataitem); @@ -804,6 +819,12 @@ _bt_buildadd(BTWriteState *wstate, BTPageState *state, IndexTuple itup, */ CHECK_FOR_INTERRUPTS(); + if (state->btps_level == 0 && _bt_prefix_enabled(wstate->index)) + { + _bt_buildadd_coded(wstate, state, itup, truncextra); + return; + } + nbuf = state->btps_buf; npage = (Page) nbuf; nblkno = state->btps_blkno; @@ -1022,6 +1043,254 @@ _bt_buildadd(BTWriteState *wstate, BTPageState *state, IndexTuple itup, state->btps_lastoff = last_off; } +/* + * _bt_buildadd_coded -- add a leaf tuple to a prefix_compression index build. + * + * Leaf tuples are collected in state->btps_items with a running estimate of + * the page they would make when coded (BTPrefixPageEst). Before adding itup, + * the pending leaf is laid out and written if itup would push it past either + * limit: + * + * - the leaf fillfactor, applied to the coded (on-disk) size, so a coded + * leaf leaves the same insert headroom that a plain one does; and + * - the split-fit budget (see _bt_prefix_split_needed): the decoded items of + * a coded page must still split into two plain pages. + * + * A pending leaf that cannot be coded, or would not compress enough to be + * worthwhile, is laid out plain and capped at what a plain page holds, exactly + * as in a non-prefix build. + */ +static void +_bt_buildadd_coded(BTWriteState *wstate, BTPageState *state, IndexTuple itup, + Size truncextra) +{ + Size usable = BLCKSZ - SizeOfPageHeaderData - + MAXALIGN(sizeof(BTPageOpaqueData)); + Size fillsz = usable - state->btps_full; + Size itupsz = MAXALIGN(IndexTupleSize(itup)); + BTPrefixPageEst est; + + CHECK_FOR_INTERRUPTS(); + + if (unlikely(itupsz > BTMaxItemSize)) + _bt_check_third_page(wstate->index, wstate->heap, true, + (Page) state->btps_buf, itup); + + if (state->btps_items == NULL) + { + state->btps_maxitems = 2 * MaxIndexTuplesPerPage; + state->btps_items = palloc_array(IndexTuple, state->btps_maxitems); + } + + /* + * Mirror _bt_buildadd's two tests, in terms of the leaf the pending + * tuples would make. A finished leaf keeps all pending tuples but the + * last, which moves to the next leaf and supplies the new high key (at + * most its key part plus a heap TID, stored plain). The soft limit + * finishes the leaf once it is fillfactor-full as it stands. The hard + * limit finishes it if admitting itup could leave it unable to hold its + * tuples and high key, or (coded) beyond the split-fit budget, or out of + * line pointers. Sizes are coded when coding is worthwhile and plain + * otherwise, so a build that does not compress fills leaves exactly as a + * plain one. + * + * Copy itup before estimating: the running estimate keeps a pointer to + * its group's anchor tuple, which may be this one, so it must point at + * the copy that is kept. + */ + itup = CopyIndexTuple(itup); + est = state->btps_est; + _bt_prefix_est_add(&est, itup); + + if (state->btps_nitems >= 2) + { + BTPrefixPageEst *pend = &state->btps_est; + Size lastplain = MAXALIGN(IndexTupleSize(state->btps_items[state->btps_nitems - 1])) + + sizeof(ItemIdData); + Size itupplain = itupsz + sizeof(ItemIdData); + Size itupkey = itupsz - truncextra + + MAXALIGN(sizeof(ItemPointerData)) + sizeof(ItemIdData); + Size leafnow, + leafwith; + bool full; + + if (_bt_prefix_est_representable(pend) && + _bt_prefix_worthwhile(_bt_prefix_est_coded(pend), pend->plainsz)) + leafnow = _bt_prefix_est_coded(pend) - pend->lastcoded + + state->btps_lastkey; + else + leafnow = pend->plainsz - lastplain + state->btps_lastkey; + full = leafnow > fillsz; + + if (!full) + { + if (_bt_prefix_est_representable(&est) && + _bt_prefix_worthwhile(_bt_prefix_est_coded(&est), est.plainsz)) + { + leafwith = _bt_prefix_est_coded(&est) - est.lastcoded + itupkey; + + /* + * The final leaf keeps the last item, including its posting + * list. + */ + full = est.plainsz - itupplain + Max(itupplain, itupkey) + + 2 * est.maxplain + MAXALIGN(sizeof(ItemPointerData)) > 2 * usable || + _bt_prefix_est_coded(&est) > usable; + } + else + { + leafwith = est.plainsz - itupplain + itupkey; + /* The whole set must also fit if this is the final leaf. */ + full = est.plainsz > usable; + } + full = full || leafwith > usable || + state->btps_nitems >= MaxIndexTuplesPerPage - 2; + } + + if (full) + { + /* itup starts the next leaf: its estimate starts over */ + _bt_flush_coded(wstate, state, false); + est = state->btps_est; + _bt_prefix_est_add(&est, itup); + } + } + + if (state->btps_nitems >= state->btps_maxitems) + { + state->btps_maxitems *= 2; + state->btps_items = repalloc_array(state->btps_items, IndexTuple, + state->btps_maxitems); + } + state->btps_items[state->btps_nitems++] = itup; + state->btps_est = est; + state->btps_lastkey = itupsz - truncextra + + MAXALIGN(sizeof(ItemPointerData)) + sizeof(ItemIdData); +} + +/* + * _bt_flush_coded -- lay out and write the pending leaf of a coded build. + * + * All pending tuples but the last go on the leaf (the last one starts the next + * leaf and supplies the new high key, as in _bt_buildadd). When `last' the + * whole pending set makes the final, rightmost leaf, which is left in + * state->btps_buf for _bt_uppershutdown to write. + */ +static void +_bt_flush_coded(BTWriteState *wstate, BTPageState *state, bool last) +{ + Page page = (Page) state->btps_buf; + BTPageOpaque opaque = BTPageGetOpaque(page); + int nleaf = last ? state->btps_nitems : state->btps_nitems - 1; + IndexTuple firstright = last ? NULL : state->btps_items[nleaf]; + IndexTuple hikey = NULL; + BTPageOpaqueData saveopaque; + Size usable = BLCKSZ - SizeOfPageHeaderData - + MAXALIGN(sizeof(BTPageOpaqueData)); + Size plainsz; + bool trycode; + BulkWriteBuffer nbuf = NULL; + BlockNumber nblkno = InvalidBlockNumber; + + Assert(nleaf >= 1); + + /* + * A finished leaf is not rightmost: link it to the next leaf before + * laying it out, since the layout (high key, directory offset) depends on + * that. + */ + if (!last) + { + nbuf = _bt_blnewpage(wstate, 0); + nblkno = wstate->btws_pages_alloced++; + opaque->btpo_next = nblkno; + BTPageGetOpaque((Page) nbuf)->btpo_prev = state->btps_blkno; + } + saveopaque = *opaque; + + if (!last) + hikey = _bt_truncate(wstate->index, state->btps_items[nleaf - 1], + firstright, wstate->inskey); + + /* + * Lay out the leaf: coded if worthwhile, else plain. The running + * estimate covers all pending tuples, so leaving out the last one can tip + * the worthwhile test; if the plain layout would then overflow a page, + * code it anyway (admission in _bt_buildadd_coded guaranteed the coded + * layout fits). When the estimate says coding does not pay and plain + * fits, the common case for an incompressible index, skip the coding + * attempt and its second pass over the tuples. + */ + plainsz = hikey ? MAXALIGN(IndexTupleSize(hikey)) + sizeof(ItemIdData) : 0; + for (int i = 0; i < nleaf; i++) + plainsz += MAXALIGN(IndexTupleSize(state->btps_items[i])) + + sizeof(ItemIdData); + trycode = plainsz > usable || + (_bt_prefix_est_representable(&state->btps_est) && + _bt_prefix_worthwhile(_bt_prefix_est_coded(&state->btps_est), + state->btps_est.plainsz)); + _bt_pageinit(page, BLCKSZ); + *BTPageGetOpaque(page) = saveopaque; + opaque = BTPageGetOpaque(page); + if (!trycode || + !_bt_prefix_form_page(page, hikey, state->btps_items, + nleaf, plainsz > usable)) + { + OffsetNumber off = P_FIRSTKEY; + + if (plainsz > usable) + elog(ERROR, "could not lay out prefix-compressed leaf during build of index \"%s\"", + RelationGetRelationName(wstate->index)); + + _bt_pageinit(page, BLCKSZ); + *BTPageGetOpaque(page) = saveopaque; + opaque = BTPageGetOpaque(page); + if (hikey) + _bt_sortaddtup(page, IndexTupleSize(hikey), hikey, P_HIKEY, false); + else + off = P_HIKEY; /* rightmost: no high key */ + for (int i = 0; i < nleaf; i++, off = OffsetNumberNext(off)) + _bt_sortaddtup(page, MAXALIGN(IndexTupleSize(state->btps_items[i])), + state->btps_items[i], off, false); + } + + /* minus infinity low key for the leftmost leaf */ + if (state->btps_lowkey == NULL) + { + state->btps_lowkey = palloc0_object(IndexTupleData); + state->btps_lowkey->t_info = sizeof(IndexTupleData); + BTreeTupleSetNAtts(state->btps_lowkey, 0, false); + } + + if (!last) + { + /* link the finished leaf into its parent, using its low key */ + if (state->btps_next == NULL) + state->btps_next = _bt_pagestate(wstate, 1); + BTreeTupleSetDownLink(state->btps_lowkey, state->btps_blkno); + _bt_buildadd(wstate, state->btps_next, state->btps_lowkey, 0); + pfree(state->btps_lowkey); + state->btps_lowkey = hikey; /* the next leaf's low key */ + + _bt_blwritepage(wstate, state->btps_buf, state->btps_blkno); + state->btps_buf = nbuf; + state->btps_blkno = nblkno; + } + + /* keep only the carried-over first tuple of the next leaf */ + for (int i = 0; i < nleaf; i++) + pfree(state->btps_items[i]); + state->btps_nitems = 0; + memset(&state->btps_est, 0, sizeof(BTPrefixPageEst)); + if (!last) + { + state->btps_items[0] = firstright; + state->btps_nitems = 1; + _bt_prefix_est_add(&state->btps_est, firstright); + /* btps_lastkey still describes firstright */ + } +} + /* * Finalize pending posting list tuple, and add it to the index. Final tuple * is based on saved base tuple, and saved list of heap TIDs. @@ -1071,6 +1340,10 @@ _bt_uppershutdown(BTWriteState *wstate, BTPageState *state) uint32 rootlevel = 0; BulkWriteBuffer metabuf; + /* lay out the final leaf of a prefix_compression build */ + if (state != NULL && state->btps_items != NULL) + _bt_flush_coded(wstate, state, true); + /* * Each iteration of this loop completes one more level of the tree. */ @@ -1114,7 +1387,8 @@ _bt_uppershutdown(BTWriteState *wstate, BTPageState *state) * This is the rightmost page, so the ItemId array needs to be slid * back one slot. Then we can dump out the page. */ - _bt_slideleft((Page) s->btps_buf); + if (s->btps_items == NULL) /* coded-build leaves are laid out exactly */ + _bt_slideleft((Page) s->btps_buf); _bt_blwritepage(wstate, s->btps_buf, s->btps_blkno); s->btps_buf = NULL; /* writepage took ownership of the buffer */ } diff --git a/src/backend/access/nbtree/nbtsplitloc.c b/src/backend/access/nbtree/nbtsplitloc.c index de9eca3c8b2ea..a6be84f19778d 100644 --- a/src/backend/access/nbtree/nbtsplitloc.c +++ b/src/backend/access/nbtree/nbtsplitloc.c @@ -459,6 +459,13 @@ _bt_recsplitloc(FindSplitData *state, Size postingsz = 0; bool newitemisfirstright; + /* + * Reject an empty left half. A prefix representation limit can force a + * split of a sparse page, where the space checks below would accept one. + */ + if (olddataitemstoleft == 0 && !newitemonleft) + return; + /* Is the new item going to be split point's firstright tuple? */ newitemisfirstright = (firstrightoff == state->newitemoff && !newitemonleft); diff --git a/src/backend/access/nbtree/nbtutils.c b/src/backend/access/nbtree/nbtutils.c index 85c1b6325224b..5dc2b2f305041 100644 --- a/src/backend/access/nbtree/nbtutils.c +++ b/src/backend/access/nbtree/nbtutils.c @@ -602,7 +602,9 @@ btoptions(Datum reloptions, bool validate) {"vacuum_cleanup_index_scale_factor", RELOPT_TYPE_REAL, offsetof(BTOptions, vacuum_cleanup_index_scale_factor)}, {"deduplicate_items", RELOPT_TYPE_BOOL, - offsetof(BTOptions, deduplicate_items)} + offsetof(BTOptions, deduplicate_items)}, + {"prefix_compression", RELOPT_TYPE_BOOL, + offsetof(BTOptions, prefix_compression)} }; return (bytea *) build_reloptions(reloptions, validate, diff --git a/src/backend/access/nbtree/nbtxlog.c b/src/backend/access/nbtree/nbtxlog.c index dff7d286fc834..070374f0089ff 100644 --- a/src/backend/access/nbtree/nbtxlog.c +++ b/src/backend/access/nbtree/nbtxlog.c @@ -186,6 +186,11 @@ btree_xlog_insert(bool isleaf, bool ismeta, bool posting, /* Simple retail insertion */ if (PageAddItem(page, datapos, datalen, xlrec->offnum, false, false) == InvalidOffsetNumber) elog(PANIC, "failed to add new item"); + /* the logged item is the coded one on a prefix leaf */ + if (isleaf && P_HASPREFIX(BTPageGetOpaque(page))) + _bt_prefix_note_insert(page, + (IndexTuple) PageGetItem(page, + PageGetItemId(page, xlrec->offnum))); } else { @@ -215,15 +220,45 @@ btree_xlog_insert(bool isleaf, bool ismeta, bool posting, /* Use mutable, aligned newitem copy in _bt_swap_posting() */ Assert(isleaf && postingoff > 0); newitem = CopyIndexTuple((IndexTuple) datapos); - nposting = _bt_swap_posting(newitem, oposting, postingoff); - /* Replace existing posting list with post-split version */ - memcpy(oposting, nposting, MAXALIGN(IndexTupleSize(nposting))); + if (P_HASPREFIX(BTPageGetOpaque(page))) + { + /* + * Coded leaf: repeat _bt_insertonpg's exact steps. Swap on + * the decoded posting list, then code both results against + * the page; coding needs no catalog access. + */ + BTItemBuf pbuf; + IndexTuple plainpost = CopyIndexTuple(_bt_getitem(page, + OffsetNumberPrev(xlrec->offnum), + &pbuf)); + IndexTuple codedpost; + IndexTuple codednew; + + nposting = _bt_swap_posting(newitem, plainpost, postingoff); + codedpost = _bt_prefix_recode(page, + OffsetNumberPrev(xlrec->offnum), + nposting); + Assert(IndexTupleSize(codedpost) == ItemIdGetLength(itemid)); + memcpy(oposting, codedpost, MAXALIGN(IndexTupleSize(codedpost))); + codednew = _bt_prefix_encode_insert(page, xlrec->offnum, newitem); + if (PageAddItem(page, codednew, MAXALIGN(IndexTupleSize(codednew)), + xlrec->offnum, false, false) == InvalidOffsetNumber) + elog(PANIC, "failed to add posting split new item"); + _bt_prefix_note_insert(page, codednew); + } + else + { + nposting = _bt_swap_posting(newitem, oposting, postingoff); - /* Insert "final" new item (not orignewitem from WAL stream) */ - Assert(IndexTupleSize(newitem) == datalen); - if (PageAddItem(page, newitem, datalen, xlrec->offnum, false, false) == InvalidOffsetNumber) - elog(PANIC, "failed to add posting split new item"); + /* Replace existing posting list with post-split version */ + memcpy(oposting, nposting, MAXALIGN(IndexTupleSize(nposting))); + + /* Insert "final" new item (not orignewitem from WAL stream) */ + Assert(IndexTupleSize(newitem) == datalen); + if (PageAddItem(page, newitem, datalen, xlrec->offnum, false, false) == InvalidOffsetNumber) + elog(PANIC, "failed to add posting split new item"); + } } PageSetLSN(page, lsn); @@ -280,7 +315,11 @@ btree_xlog_split(bool newitemonleft, XLogReaderState *record) if (!isleaf) _bt_clear_incomplete_split(record, 3); - /* Reconstruct right (new) sibling page from scratch */ + /* + * Reconstruct right (new) sibling page from scratch. A coded right half + * was logged as its coded items, directory included, which + * _bt_restore_page lays out exactly as the primary did. + */ rbuf = XLogInitBufferForRedo(record, 1); datapos = XLogRecGetBlockData(record, 1, &datalen); rpage = BufferGetPage(rbuf); @@ -292,6 +331,8 @@ btree_xlog_split(bool newitemonleft, XLogReaderState *record) ropaque->btpo_next = spagenumber; ropaque->btpo_level = xlrec->level; ropaque->btpo_flags = isleaf ? BTP_LEAF : 0; + if (xlrec->flags & XLH_SPLIT_RIGHT_CODED) + ropaque->btpo_flags |= BTP_PREFIX; ropaque->btpo_cycleid = 0; _bt_restore_page(rpage, datapos, datalen); @@ -320,7 +361,35 @@ btree_xlog_split(bool newitemonleft, XLogReaderState *record) left_hikeysz = 0; Page leftpage; OffsetNumber leftoff, + firstdata, replacepostingoff = InvalidOffsetNumber; + IndexTuple *ditems = NULL; /* decoded items of a coded origpage */ + IndexTuple *litems; /* the left half's items, in order */ + int nlitems = 0; + + /* + * The original page's data items, as plain tuples. For a coded page + * (XLH_SPLIT_ORIG_CODED) the record's offsets are into the decoded + * sequence, which starts at the prefix directory's offset. + */ + if (xlrec->flags & XLH_SPLIT_ORIG_CODED) + { + IndexTuple dhikey; + Size dhikeysz; + + Assert(P_HASPREFIX(oopaque)); + (void) _bt_prefix_decode_items(origpage, &ditems, &dhikey, + &dhikeysz); + if (dhikey) + pfree(dhikey); + firstdata = BTPageGetPrefixOff(oopaque); + } + else + firstdata = P_FIRSTDATAKEY(oopaque); + +#define ORIG_ITEM(o) \ + (ditems ? ditems[(o) - firstdata] : \ + (IndexTuple) PageGetItem(origpage, PageGetItemId(origpage, (o)))) datapos = XLogRecGetBlockData(record, 0, &datalen); @@ -333,7 +402,6 @@ btree_xlog_split(bool newitemonleft, XLogReaderState *record) if (xlrec->postingoff != 0) { - ItemId itemid; IndexTuple oposting; /* Posting list must be at offset number before new item's */ @@ -341,8 +409,7 @@ btree_xlog_split(bool newitemonleft, XLogReaderState *record) /* Use mutable, aligned newitem copy in _bt_swap_posting() */ newitem = CopyIndexTuple(newitem); - itemid = PageGetItemId(origpage, replacepostingoff); - oposting = (IndexTuple) PageGetItem(origpage, itemid); + oposting = ORIG_ITEM(replacepostingoff); nposting = _bt_swap_posting(newitem, oposting, xlrec->postingoff); } @@ -360,64 +427,86 @@ btree_xlog_split(bool newitemonleft, XLogReaderState *record) Assert(datalen == 0); - leftpage = PageGetTempPageCopySpecial(origpage); - - /* Add high key tuple from WAL record to temp page */ - leftoff = P_HIKEY; - if (PageAddItem(leftpage, left_hikey, left_hikeysz, P_HIKEY, false, false) == InvalidOffsetNumber) - elog(ERROR, "failed to add high key to left page after split"); - leftoff = OffsetNumberNext(leftoff); - - for (off = P_FIRSTDATAKEY(oopaque); off < xlrec->firstrightoff; off++) + /* Collect the left half's items, in item number order */ + litems = palloc(sizeof(IndexTuple) * (MaxIndexTuplesPerPage * 2 + 1)); + for (off = firstdata; off < xlrec->firstrightoff; off++) { - ItemId itemid; - Size itemsz; - IndexTuple item; - /* Add replacement posting list when required */ if (off == replacepostingoff) { Assert(newitemonleft || xlrec->firstrightoff == xlrec->newitemoff); - if (PageAddItem(leftpage, nposting, MAXALIGN(IndexTupleSize(nposting)), leftoff, false, false) == InvalidOffsetNumber) - elog(ERROR, "failed to add new posting list item to left page after split"); - leftoff = OffsetNumberNext(leftoff); + litems[nlitems++] = nposting; continue; /* don't insert oposting */ } /* add the new item if it was inserted on left page */ else if (newitemonleft && off == xlrec->newitemoff) - { - if (PageAddItem(leftpage, newitem, newitemsz, leftoff, false, false) == InvalidOffsetNumber) - elog(ERROR, "failed to add new item to left page after split"); - leftoff = OffsetNumberNext(leftoff); - } + litems[nlitems++] = newitem; - itemid = PageGetItemId(origpage, off); - itemsz = ItemIdGetLength(itemid); - item = (IndexTuple) PageGetItem(origpage, itemid); - if (PageAddItem(leftpage, item, itemsz, leftoff, false, false) == InvalidOffsetNumber) - elog(ERROR, "failed to add old item to left page after split"); - leftoff = OffsetNumberNext(leftoff); + litems[nlitems++] = ORIG_ITEM(off); } /* cope with possibility that newitem goes at the end */ if (newitemonleft && off == xlrec->newitemoff) - { - if (PageAddItem(leftpage, newitem, newitemsz, leftoff, false, false) == InvalidOffsetNumber) - elog(ERROR, "failed to add new item to left page after split"); - leftoff = OffsetNumberNext(leftoff); - } + litems[nlitems++] = newitem; +#undef ORIG_ITEM - PageRestoreTempPage(leftpage, origpage); + /* + * The left half holds one item per original offset in [firstdata, + * firstrightoff), plus newitem when it landed on the left; a replaced + * posting list does not change the count. A mismatch means redo + * disagrees with the primary about the split. + */ + Assert(nlitems == (xlrec->firstrightoff - firstdata) + + (newitemonleft ? 1 : 0)); - /* Fix opaque fields */ + /* + * To retain the same physical order of the tuples that they had, we + * initialize a temporary empty page for the left page and add all the + * items to that in item number order. This mirrors how _bt_split() + * works. Retaining the same physical order makes WAL consistency + * checking possible. See also _bt_restore_page(), which does the + * same for the right page. + */ + leftpage = PageGetTempPageCopySpecial(origpage); + + /* Fix opaque fields (the layout of a coded page depends on them) */ + oopaque = BTPageGetOpaque(leftpage); oopaque->btpo_flags = BTP_INCOMPLETE_SPLIT; if (isleaf) oopaque->btpo_flags |= BTP_LEAF; oopaque->btpo_next = rightpagenumber; oopaque->btpo_cycleid = 0; + if (xlrec->flags & XLH_SPLIT_LEFT_CODED) + { + /* lay out the coded left half exactly as _bt_split did */ + if (!_bt_prefix_form_page(leftpage, left_hikey, litems, nlitems, + true)) + elog(ERROR, "failed to lay out prefix-compressed left page after split"); + } + else + { + /* Add high key tuple from WAL record to temp page */ + if (PageAddItem(leftpage, left_hikey, left_hikeysz, P_HIKEY, false, false) == InvalidOffsetNumber) + elog(ERROR, "failed to add high key to left page after split"); + leftoff = OffsetNumberNext(P_HIKEY); + + for (int i = 0; i < nlitems; i++) + { + if (PageAddItem(leftpage, litems[i], + MAXALIGN(IndexTupleSize(litems[i])), leftoff, + false, false) == InvalidOffsetNumber) + elog(ERROR, "failed to add item to left page after split"); + leftoff = OffsetNumberNext(leftoff); + } + } + + /* btree_redo resets opCtx per record, freeing the decoded items */ + PageRestoreTempPage(leftpage, origpage); + pfree(litems); + PageSetLSN(origpage, lsn); MarkBufferDirty(buf); } @@ -468,6 +557,8 @@ btree_xlog_dedup(XLogReaderState *record) BTDedupState state; BTDedupInterval *intervals; Page newpage; + bool coded = P_HASPREFIX(opaque); + IndexTuple *ditems = NULL; state = palloc_object(BTDedupStateData); state->deduplicate = true; /* unused */ @@ -497,13 +588,33 @@ btree_xlog_dedup(XLogReaderState *record) elog(ERROR, "deduplication failed to add highkey"); } + /* + * A prefix-compressed page is deduplicated on decoded copies of its + * items and keeps its directory, as in _bt_dedup_pass. + */ + if (coded) + { + OffsetNumber prefixoff = BTPageGetPrefixOff(opaque); + ItemId diritemid = PageGetItemId(page, prefixoff); + IndexTuple dummyhikey; + Size dummyhikeysz; + + if (PageAddItem(newpage, PageGetItem(page, diritemid), + ItemIdGetLength(diritemid), prefixoff, + false, false) == InvalidOffsetNumber) + elog(ERROR, "deduplication failed to add prefix directory"); + (void) _bt_prefix_decode_items(page, &ditems, &dummyhikey, + &dummyhikeysz); + } + intervals = (BTDedupInterval *) ptr; for (offnum = minoff; offnum <= maxoff; offnum = OffsetNumberNext(offnum)) { ItemId itemid = PageGetItemId(page, offnum); - IndexTuple itup = (IndexTuple) PageGetItem(page, itemid); + IndexTuple itup = coded ? ditems[offnum - minoff] : + (IndexTuple) PageGetItem(page, itemid); if (offnum == minoff) _bt_dedup_start_pending(state, itup, offnum); @@ -516,12 +627,21 @@ btree_xlog_dedup(XLogReaderState *record) } else { - _bt_dedup_finish_pending(newpage, state); + if (coded) + _bt_dedup_finish_pending_coded(page, newpage, state); + else + _bt_dedup_finish_pending(newpage, state); _bt_dedup_start_pending(state, itup, offnum); } } - _bt_dedup_finish_pending(newpage, state); + if (coded) + { + _bt_dedup_finish_pending_coded(page, newpage, state); + _bt_prefix_recount(newpage); + } + else + _bt_dedup_finish_pending(newpage, state); Assert(state->nintervals == xlrec->nintervals); Assert(memcmp(state->intervals, intervals, state->nintervals * sizeof(BTDedupInterval)) == 0); @@ -620,6 +740,7 @@ btree_xlog_vacuum(XLogReaderState *record) if (xlrec->ndeleted > 0) PageIndexMultiDelete(page, (OffsetNumber *) ptr, xlrec->ndeleted); + _bt_prefix_recount(page); /* * Clear the vacuum cycle ID, and mark the page as not containing any @@ -686,6 +807,7 @@ btree_xlog_delete(XLogReaderState *record) if (xlrec->ndeleted > 0) PageIndexMultiDelete(page, (OffsetNumber *) ptr, xlrec->ndeleted); + _bt_prefix_recount(page); /* * Do *not* clear the vacuum cycle ID, but do mark the page as not diff --git a/src/backend/access/rmgrdesc/nbtdesc.c b/src/backend/access/rmgrdesc/nbtdesc.c index 1d08f9957bdca..cc5edbc1dbc91 100644 --- a/src/backend/access/rmgrdesc/nbtdesc.c +++ b/src/backend/access/rmgrdesc/nbtdesc.c @@ -46,6 +46,11 @@ btree_desc(StringInfo buf, XLogReaderState *record) appendStringInfo(buf, "level: %u, firstrightoff: %d, newitemoff: %d, postingoff: %d", xlrec->level, xlrec->firstrightoff, xlrec->newitemoff, xlrec->postingoff); + if (xlrec->flags != 0) + appendStringInfo(buf, ", prefix:%s%s%s", + (xlrec->flags & XLH_SPLIT_ORIG_CODED) ? " orig" : "", + (xlrec->flags & XLH_SPLIT_LEFT_CODED) ? " left" : "", + (xlrec->flags & XLH_SPLIT_RIGHT_CODED) ? " right" : ""); break; } case XLOG_BTREE_DEDUP: diff --git a/src/include/access/nbtree.h b/src/include/access/nbtree.h index 3097e9bb1af9b..f27dfd4cc47ba 100644 --- a/src/include/access/nbtree.h +++ b/src/include/access/nbtree.h @@ -83,6 +83,8 @@ typedef BTPageOpaqueData *BTPageOpaque; #define BTP_HAS_GARBAGE (1 << 6) /* page has LP_DEAD tuples (deprecated) */ #define BTP_INCOMPLETE_SPLIT (1 << 7) /* right sibling's downlink is missing */ #define BTP_HAS_FULLXID (1 << 8) /* contains BTDeletedPageData */ +#define BTP_PREFIX (1 << 9) /* leaf keys coded against a page prefix + * (see nbtprefix.c) */ /* * The max allowed value of a cycle ID is a bit less than 64K. This is @@ -367,7 +369,55 @@ typedef struct BTVacState #define P_HIKEY ((OffsetNumber) 1) #define P_FIRSTKEY ((OffsetNumber) 2) -#define P_FIRSTDATAKEY(opaque) (P_RIGHTMOST(opaque) ? P_HIKEY : P_FIRSTKEY) + +/* + * Leaf key prefix compression (see nbtprefix.c for the code). + * + * A leaf of an index whose prefix_compression reloption is on may be flagged + * BTP_PREFIX. Its data items are organized in GROUPS of consecutive items; + * each group has an ANCHOR, a copy of the key part of the group's first item, + * and each member is stored "coded": without the leading data-area bytes it + * shares with the anchor. Sharing is by stored bytes, never by the opclass + * notion of equality, so it is sound for any column type (an index-only scan + * gets back exactly the bytes that were stored) and needs no equalimage + * support; it covers whole leading columns and any leading bytes of the + * first column that differs. + * + * Page layout. At BTPageGetPrefixOff(opaque) (right after the high key) is a + * single PREFIX DIRECTORY item that holds every group's anchor; the data items + * follow it, in key order, starting at P_FIRSTDATAKEY. One item before the + * data keeps P_FIRSTDATAKEY a function of the page flag alone, so neither + * BTPageOpaqueData nor the on-disk page header changes, and binary search over + * the data items is unaffected. The directory item is an IndexTupleData header + * (invalid t_tid; t_info = its size) followed by the group count, the cached + * decoded size of the page's data items (see _bt_prefix_split_needed), the + * anchor offsets, and the anchors (BTPrefixDirHdr, BTPrefixAnchorDisk). + * + * Coded member. An IndexTupleData header whose t_tid is the member's own heap + * TID (or posting list metadata), a small code header (group, shared byte + * count, the original's t_info), the original's null bitmap, the residual (the + * original's data-area bytes after the shared ones) and, for a posting list + * tuple, its posting list in the standard layout. Code that reads only heap + * TIDs therefore works on coded items as is. Decoding splices the anchor's + * shared bytes back in front of the residual and reproduces the original tuple + * byte for byte. Coding and decoding use only the page and the tuple, never + * the catalog, so WAL redo repeats them. Pivots (high keys, downlinks) are + * never coded. + */ +#define BTREE_PREFIX_MAXGROUPS 0xFFFE /* group-id ceiling (uint16) */ + +/* + * Most bytes a coded member can take beyond its plain tuple (see the static + * assertion in nbtprefix.c). Insert reserves this on a prefix page so the + * coded PageAddItem cannot fail after the fit check. + */ +#define BTREE_PREFIX_CODE_OVERHEAD MAXALIGN(16) + +#define P_HASPREFIX(opaque) (((opaque)->btpo_flags & BTP_PREFIX) != 0) +#define BTPageGetPrefixOff(opaque) \ + (P_RIGHTMOST(opaque) ? P_HIKEY : P_FIRSTKEY) +#define P_FIRSTDATAKEY(opaque) \ + (BTPageGetPrefixOff(opaque) + (P_HASPREFIX(opaque) ? 1 : 0)) /* * Notes on B-Tree tuple format, and key and non-key attributes: @@ -676,6 +726,34 @@ BTreeTupleGetMaxHeapTID(IndexTuple itup) return &itup->t_tid; } +/* + * Workspace for _bt_getitem. Every read of a leaf data item that could be on + * a BTP_PREFIX page goes through _bt_getitem rather than PageGetItem, so + * decoding has one home. The returned tuple is valid until the workspace is + * reused or the page is unlocked. High keys, pivots, and items a caller + * changes in place are read with PageGetItem. + */ +typedef PGAlignedBlock BTItemBuf; + +extern IndexTuple _bt_prefix_decode(Page page, OffsetNumber offnum, BTItemBuf *buf); +extern IndexTuple _bt_prefix_decode_copy(Page page, OffsetNumber offnum); +extern void _bt_prefix_check(Page page); + +/* + * Return the data item at `offnum' on `page' as a plain IndexTuple, decoded + * into `buf' on a BTP_PREFIX page and the on-page tuple otherwise. Callers + * must not write through the result. + */ +static inline IndexTuple +_bt_getitem(Page page, OffsetNumber offnum, BTItemBuf *buf) +{ + BTPageOpaque opaque = BTPageGetOpaque(page); + + if (unlikely(P_HASPREFIX(opaque)) && offnum > BTPageGetPrefixOff(opaque)) + return _bt_prefix_decode(page, offnum, buf); + return (IndexTuple) PageGetItem(page, PageGetItemId(page, offnum)); +} + /* * Operator strategy numbers for B-tree have been moved to access/stratnum.h, * because many places need to use them in ScanKeyInit() calls. @@ -1075,10 +1153,13 @@ typedef struct BTScanOpaqueData /* * If we are doing an index-only scan, these are the tuple storage * workspaces for the currPos and markPos respectively. Each is of size - * BLCKSZ, so it can hold as much as a full page's worth of tuples. + * BLCKSZ, so it can hold as much as a full page's worth of tuples, or 2 * + * BLCKSZ once bigTuples is set (a prefix-compressed leaf can decode to + * more than one page; see _bt_prefix_split_needed). */ char *currTuples; /* tuple storage for currPos */ char *markTuples; /* tuple storage for markPos */ + bool bigTuples; /* workspaces grown for prefix pages? */ /* * If the marked position is on the same page as current position, we @@ -1122,6 +1203,7 @@ typedef struct BTOptions int fillfactor; /* page fill factor in percent (0..100) */ float8 vacuum_cleanup_index_scale_factor; /* deprecated */ bool deduplicate_items; /* Try to deduplicate items? */ + bool prefix_compression; /* Code leaf keys against a page prefix? */ } BTOptions; #define BTGetFillFactor(relation) \ @@ -1203,6 +1285,8 @@ extern void _bt_dedup_start_pending(BTDedupState state, IndexTuple base, OffsetNumber baseoff); extern bool _bt_dedup_save_htid(BTDedupState state, IndexTuple itup); extern Size _bt_dedup_finish_pending(Page newpage, BTDedupState state); +extern void _bt_dedup_finish_pending_coded(Page page, Page newpage, + BTDedupState state); extern IndexTuple _bt_form_posting(IndexTuple base, const ItemPointerData *htids, int nhtids); extern void _bt_update_posting(BTVacuumPosting vacposting); @@ -1315,6 +1399,48 @@ extern void _bt_check_third_page(Relation rel, Relation heap, bool needheaptidspace, Page page, IndexTuple newtup); extern bool _bt_allequalimage(Relation rel, bool debugmessage); +/* + * prototypes for functions in nbtprefix.c + */ +extern bool _bt_prefix_enabled(Relation index); +extern IndexTuple _bt_prefix_encode_insert(Page page, + OffsetNumber newitemoff, IndexTuple itup); +extern void _bt_prefix_compress_page(Relation index, Page page); + +/* Running estimate of a coded leaf, for filling pages during CREATE INDEX */ +typedef struct BTPrefixPageEst +{ + int ngroups; + IndexTuple grouprep; /* current group's representative */ + IndexTuple prev; /* previous tuple added (NULL at start) */ + Size anchorsz; /* directory anchor blobs so far */ + Size codedsz; /* coded items, plus line pointers */ + Size lastcoded; /* most recent item's share of codedsz */ + Size maxcoded; /* largest coded item, without line pointer */ + Size plainsz; /* plain items, plus line pointers */ + Size maxplain; /* largest plain item, plus line pointer */ +} BTPrefixPageEst; + +extern void _bt_prefix_est_add(BTPrefixPageEst *est, IndexTuple itup); +extern Size _bt_prefix_est_coded(const BTPrefixPageEst *est); +extern bool _bt_prefix_est_representable(const BTPrefixPageEst *est); +extern bool _bt_prefix_worthwhile(Size codedsz, Size plainsz); +extern bool _bt_prefix_form_page(Page newpage, IndexTuple hikey, + IndexTuple *items, int n, bool force); +extern IndexTuple _bt_prefix_recode(Page page, OffsetNumber offnum, + IndexTuple itup); +extern int _bt_prefix_decode_items(Page page, IndexTuple **items_out, + IndexTuple *hikey, Size *hikeysz); +extern Page _bt_prefix_try_plain_page(Relation rel, Page page, Page out); +extern bool _bt_prefix_split_needed(Page page, Size newitemsz); +extern OffsetNumber _bt_prefix_findsplitloc(Relation rel, Page page, + IndexTuple *ditems, + OffsetNumber newitemoff, + Size newitemsz, + bool *newitemonleft); +extern void _bt_prefix_recount(Page page); +extern void _bt_prefix_note_insert(Page page, IndexTuple coded); + /* * prototypes for functions in nbtvalidate.c */ diff --git a/src/include/access/nbtxlog.h b/src/include/access/nbtxlog.h index 3a78ec27fe8ce..8ec9073f7b468 100644 --- a/src/include/access/nbtxlog.h +++ b/src/include/access/nbtxlog.h @@ -156,9 +156,23 @@ typedef struct xl_btree_split OffsetNumber firstrightoff; /* first origpage item on rightpage */ OffsetNumber newitemoff; /* new item's offset */ uint16 postingoff; /* offset inside orig posting tuple */ + uint8 flags; /* XLH_SPLIT_* prefix compression flags */ } xl_btree_split; -#define SizeOfBtreeSplit (offsetof(xl_btree_split, postingoff) + sizeof(uint16)) +#define SizeOfBtreeSplit (offsetof(xl_btree_split, flags) + sizeof(uint8)) + +/* + * xl_btree_split flags for prefix-compressed (BTP_PREFIX) leaves. When the + * original page was coded, firstrightoff and newitemoff are offsets into its + * decoded item sequence, which has no prefix directory, so data items start + * at BTPageGetPrefixOff; redo decodes the original page to rebuild the left + * half. Redo lays out a coded left half with _bt_prefix_form_page from those + * items, exactly as the primary did. A coded right half arrives as its coded + * items, directory included, and only needs the page flag set. + */ +#define XLH_SPLIT_ORIG_CODED 0x01 +#define XLH_SPLIT_LEFT_CODED 0x02 +#define XLH_SPLIT_RIGHT_CODED 0x04 /* * When page is deduplicated, consecutive groups of tuples with equal keys are diff --git a/src/test/recovery/Makefile b/src/test/recovery/Makefile index e90e0b1ad4c61..d766357f8c3fa 100644 --- a/src/test/recovery/Makefile +++ b/src/test/recovery/Makefile @@ -9,7 +9,9 @@ # #------------------------------------------------------------------------- -EXTRA_INSTALL=contrib/pg_prewarm \ +EXTRA_INSTALL=contrib/amcheck \ + contrib/pageinspect \ + contrib/pg_prewarm \ contrib/pg_stat_statements \ contrib/pg_visibility \ contrib/test_decoding \ diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build index cb3df6ed89502..c99040a161f91 100644 --- a/src/test/recovery/meson.build +++ b/src/test/recovery/meson.build @@ -70,6 +70,7 @@ tests += { 't/059_remote_apply_status_interval.pl', 't/060_multixact_crashed_updater.pl', 't/061_recovery_target_prefetch.pl', + 't/062_nbtree_prefix.pl', ], }, } diff --git a/src/test/recovery/t/062_nbtree_prefix.pl b/src/test/recovery/t/062_nbtree_prefix.pl new file mode 100644 index 0000000000000..fce469e3c25ec --- /dev/null +++ b/src/test/recovery/t/062_nbtree_prefix.pl @@ -0,0 +1,438 @@ +# Copyright (c) 2026, PostgreSQL Global Development Group + +# Replay of prefix-compressed btree leaves on a streaming standby. +# +# Redo rebuilds coded leaves from the WAL record, not from a full-page image, +# for inserts, splits, deduplication, posting list splits, VACUUM, simple and +# bottom-up deletion, and page deletion. wal_consistency_checking makes any +# divergence from the primary's page fail replay. +# +# Queries test btpo_flags bits from nbtree.h: BTP_ROOT is 2, BTP_PREFIX is 512. +use strict; +use warnings FATAL => 'all'; +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +my $primary = PostgreSQL::Test::Cluster->new('primary'); +$primary->init(allows_streaming => 1); +$primary->append_conf( + 'postgresql.conf', q{ +wal_consistency_checking = 'btree' +autovacuum = off +}); +$primary->start; + +# wal_consistency_checking logs a full-page image with every btree record, so +# the workload writes far more WAL than max_wal_size; a slot keeps the primary +# from recycling segments the standby has not received yet. +$primary->safe_psql('postgres', + "SELECT pg_create_physical_replication_slot('standby')"); +$primary->backup('backup'); + +my $standby = PostgreSQL::Test::Cluster->new('standby'); +$standby->init_from_backup($primary, 'backup', has_streaming => 1); +$standby->append_conf('postgresql.conf', "primary_slot_name = 'standby'"); +$standby->start; + +$primary->safe_psql( + 'postgres', q{ +CREATE EXTENSION amcheck; +CREATE EXTENSION pageinspect; + +-- Distinct keys sharing a long prefix: coded inserts and splits, including +-- splits of pages whose decoded content exceeds one page. +CREATE TABLE pfx_url (u text COLLATE "C", id int); +CREATE INDEX pfx_url_u ON pfx_url (u) WITH (prefix_compression = on); +INSERT INTO pfx_url + SELECT 'https://example.com/path/to/resource/' || (hashint4(g) & x'7fffffff'::int), g + FROM generate_series(1, 30000) g; + +-- Bulk-built coded leaves, then inserts into them. +CREATE INDEX pfx_url_u_id ON pfx_url (u, id) WITH (prefix_compression = on); +INSERT INTO pfx_url + SELECT 'https://example.com/path/to/resource/' || g, -g + FROM generate_series(1, 10000) g; + +-- Duplicates in random order: deduplication of coded pages, then posting +-- list splits on them. +CREATE TABLE pfx_dup (u text COLLATE "C", n int); +CREATE INDEX pfx_dup_u ON pfx_dup (u) WITH (prefix_compression = on); +INSERT INTO pfx_dup + SELECT 'https://example.com/path/to/resource/' || lpad((g % 300)::text, 8, '0'), g + FROM generate_series(1, 30000) g ORDER BY random(); +INSERT INTO pfx_dup + SELECT 'https://example.com/path/to/resource/' || lpad((g % 300)::text, 8, '0'), g + FROM generate_series(30001, 60000) g ORDER BY random(); + +-- VACUUM of coded pages (posting list updates and deletions), then page +-- deletion of emptied coded leaves. +DELETE FROM pfx_dup WHERE n % 3 = 0; +VACUUM pfx_dup; +DELETE FROM pfx_dup WHERE u < 'https://example.com/path/to/resource/00000150'; +VACUUM pfx_dup; + +-- Non-key updates: bottom-up deletion on coded pages. +CREATE TABLE pfx_upd (id int PRIMARY KEY, u text COLLATE "C", f int); +CREATE INDEX pfx_upd_u ON pfx_upd (u) WITH (prefix_compression = on); +INSERT INTO pfx_upd + SELECT g, 'https://example.com/x/' || lpad((g % 500)::text, 8, '0'), 0 + FROM generate_series(1, 20000) g; +UPDATE pfx_upd SET f = f + 1; +UPDATE pfx_upd SET f = f + 1; + +-- Unique checking with a nullable second key and an INCLUDE column. Equal +-- numeric values with different scales must retain their representations. +CREATE TABLE pfx_unique (u text COLLATE "C", n numeric, payload text, + f int DEFAULT 0); +INSERT INTO pfx_unique (u, n, payload) + SELECT 'https://example.com/unique/' || lpad(g::text, 8, '0'), + CASE WHEN g % 10 = 0 THEN NULL + WHEN g % 2 = 0 THEN 1.0 ELSE 1.00 END, + CASE WHEN g % 7 = 0 THEN NULL ELSE 'payload-' || g END + FROM generate_series(1, 2000) g; +CREATE UNIQUE INDEX pfx_unique_u ON pfx_unique (u, n) INCLUDE (payload) + NULLS NOT DISTINCT WITH (prefix_compression = on); +INSERT INTO pfx_unique (u, n, payload) + SELECT 'https://example.com/unique/' || lpad(g::text, 8, '0'), + CASE WHEN g % 10 = 0 THEN NULL + WHEN g % 2 = 0 THEN 1.0 ELSE 1.00 END, + CASE WHEN g % 7 = 0 THEN NULL ELSE 'payload-' || g END + FROM generate_series(2001, 4000) g; +VACUUM ANALYZE pfx_unique; +}); + +# Check the leaves containing both duplicate probe keys, not unrelated leaves +# that may be plain. Do this before updates can create HOT root redirects. +is( $primary->safe_psql( + 'postgres', q{ +SELECT count(DISTINCT u) = 2 + FROM generate_series(1, + (pg_relation_size('pfx_unique_u') / + current_setting('block_size')::int)::int - 1) b, + LATERAL bt_page_stats('pfx_unique_u', b) s, + LATERAL bt_page_items('pfx_unique_u', b) i, + pfx_unique t + WHERE s.type = 'l' AND (s.btpo_flags & 512) <> 0 + AND i.itemoffset > CASE WHEN s.btpo_next = 0 THEN 1 ELSE 2 END + AND i.htid = t.ctid + AND t.u IN ('https://example.com/unique/00000002', + 'https://example.com/unique/00000010'); +}), + 't', + 'both unique duplicate probes target prefix-compressed leaves'); + +foreach my $duplicate ( + q{('https://example.com/unique/00000002', 1.000, 'duplicate')}, + q{('https://example.com/unique/00000010', NULL, 'duplicate')}) +{ + my ($ret, $stdout, $stderr) = $primary->psql('postgres', + "INSERT INTO pfx_unique (u, n, payload) VALUES $duplicate"); + is($ret, 3, 'compressed unique index rejects duplicate'); + like( + $stderr, + qr/duplicate key value violates unique constraint "pfx_unique_u"/, + 'duplicate rejected by compressed index'); +} + +$primary->safe_psql( + 'postgres', q{ +UPDATE pfx_unique SET f = f + 1; +UPDATE pfx_unique SET f = f + 1; +VACUUM ANALYZE pfx_unique; +}); + +$primary->wait_for_replay_catchup($standby); + +# The standby replayed everything (a consistency failure would have stopped +# it) and is still serving queries. +is($standby->safe_psql('postgres', 'SELECT 1'), '1', 'standby is alive'); + +my $query = q{ +SET enable_seqscan = off; +SET enable_bitmapscan = off; +SELECT count(*), md5(string_agg(u, '|' ORDER BY u)) FROM pfx_url; +SELECT count(*), md5(string_agg(u || n, '|' ORDER BY u, n)) FROM pfx_dup; +SELECT count(*) FROM pfx_upd WHERE u = 'https://example.com/x/00000007'; +}; +is( $standby->safe_psql('postgres', $query), + $primary->safe_psql('postgres', $query), + 'standby index scans match primary'); + +# Compare the decoded keys and INCLUDE values with an independent heap scan, +# including numeric scale (numeric equality alone would not detect its loss). +my $unique_query = q{ +SELECT count(*), md5(string_agg( + u || ':' || coalesce(n::text, '') || ':' || + coalesce(payload, ''), '|' ORDER BY u)) FROM pfx_unique; +}; +my $unique_expected = $primary->safe_psql( + 'postgres', + 'SET enable_indexscan = off; SET enable_indexonlyscan = off; ' + . 'SET enable_bitmapscan = off; SET enable_seqscan = on; ' + . $unique_query); +foreach my $node ($primary, $standby) +{ + my $ios = 'SET enable_seqscan = off; SET enable_bitmapscan = off; ' + . 'SET enable_indexonlyscan = on; '; + like( + $node->safe_psql('postgres', + $ios . 'EXPLAIN (COSTS OFF) ' . $unique_query), + qr/Index Only Scan using pfx_unique_u/, + 'unique index digest uses index-only scan'); + is($node->safe_psql('postgres', $ios . $unique_query), + $unique_expected, 'unique index preserves keys and INCLUDE values'); + is( $node->safe_psql( + 'postgres', $ios . q{ +SELECT n::text, payload FROM pfx_unique + WHERE u = ANY (ARRAY['https://example.com/unique/00000002', + 'https://example.com/unique/00000003', + 'https://example.com/unique/00002002']) + ORDER BY u; +SELECT payload FROM pfx_unique + WHERE u = ANY (ARRAY['https://example.com/unique/00000010', + 'https://example.com/unique/00002010']) + AND n IS NULL ORDER BY u; +}), + "1.0|payload-2\n1.00|payload-3\n1.0|\npayload-10\npayload-2010", + 'array probes and NULL keys on multicolumn unique index'); +} + +foreach my $idx (qw(pfx_url_u pfx_url_u_id pfx_dup_u pfx_upd_u pfx_unique_u)) +{ + is( $standby->safe_psql( + 'postgres', "SELECT bt_index_check('$idx', true)"), + '', + "amcheck on standby: $idx"); +} + +# Guard against a workload that never produced a coded leaf. +ok( $primary->safe_psql( + 'postgres', q{ +SELECT count(*) > 0 + FROM generate_series(1, + (pg_relation_size('pfx_url_u') / + current_setting('block_size')::int)::int - 1) b, + LATERAL bt_page_stats('pfx_url_u', b) s + WHERE s.type = 'l' AND (s.btpo_flags & 512) <> 0; +}) eq 't', + 'index has prefix-compressed leaves'); + +# VACUUM removes the empty root directory on both primary and standby. +SKIP: +{ + skip 'large tuple insertion into empty root requires 32KB pages', 7 + unless $primary->safe_psql('postgres', 'SHOW block_size') == 32768; + + $primary->safe_psql( + 'postgres', q{ +CREATE TABLE pfx_empty (a smallint, b bytea); +ALTER TABLE pfx_empty ALTER COLUMN b SET STORAGE PLAIN; +INSERT INTO pfx_empty + SELECT 1, decode(repeat('ab', 1024), 'hex') FROM generate_series(1, 3); +CREATE INDEX pfx_empty_idx ON pfx_empty (a, b) + WITH (prefix_compression = on, deduplicate_items = off); +CHECKPOINT; +DELETE FROM pfx_empty; +VACUUM pfx_empty; +}); + is( $primary->safe_psql( + 'postgres', q{ +SELECT btpo_flags & 512 = 0 AND btpo_flags & 2 <> 0 + AND live_items = 0 AND dead_items = 0 + FROM bt_page_stats('pfx_empty_idx', 1); +}), + 't', 'vacuum removes the empty root directory before insertion'); + + $primary->safe_psql( + 'postgres', q{ +INSERT INTO pfx_empty VALUES (2, decode(repeat('cd', 8168), 'hex')); +VACUUM pfx_empty; +}); + $primary->wait_for_replay_catchup($standby); + foreach my $node ($primary, $standby) + { + is( $node->safe_psql('postgres', + "SELECT bt_index_check('pfx_empty_idx', true)"), + '', 'empty root insertion passes amcheck'); + my $settings = 'SET enable_seqscan = off; SET enable_bitmapscan = off; '; + my $query = q{ +SELECT a, octet_length(b), b = decode(repeat('cd', 8168), 'hex') + FROM pfx_empty; +}; + like( + $node->safe_psql('postgres', + $settings . 'EXPLAIN (COSTS OFF) ' . $query), + qr/Index Only Scan using pfx_empty_idx/, + 'empty root insertion uses index-only scan'); + is($node->safe_psql('postgres', $settings . $query), + '2|8168|t', 'empty root insertion preserves indexed value'); + } +} + +# Deduplication merges keys that are equal under equalimage even when their +# stored bytes differ. Here the heap compresses equal keys with pglz first +# and lz4 later, and index tuples keep the inline-compressed datums, so +# posting lists built and split on coded leaves mix both representations. +# The index must still return the stored values, on the primary and after +# byte-checked replay on the standby. +SKIP: +{ + skip 'mixed compression methods require lz4', 7 + unless check_pg_config('^#define USE_LZ4 1$'); + + $primary->safe_psql( + 'postgres', q{ +CREATE TABLE pfx_img (id int, k text COLLATE "C") + WITH (autovacuum_enabled = off, fillfactor = 100); +ALTER TABLE pfx_img ALTER COLUMN k SET COMPRESSION pglz; +INSERT INTO pfx_img + SELECT g, 'https://example.com/path/to/resource/' || + lpad((g % 20)::text, 4, '0') || repeat('x', 3000) + FROM generate_series(1, 400) g; +CREATE INDEX pfx_img_k ON pfx_img (k) WITH (prefix_compression = on); +-- Free heap slots inside every posting list's TID range, so that the lz4 +-- reinserts split existing posting lists instead of only appending. +DELETE FROM pfx_img WHERE id BETWEEN 150 AND 250; +VACUUM pfx_img; +ALTER TABLE pfx_img ALTER COLUMN k SET COMPRESSION lz4; +INSERT INTO pfx_img + SELECT g, 'https://example.com/path/to/resource/' || + lpad((g % 20)::text, 4, '0') || repeat('x', 3000) + FROM generate_series(150, 800) g WHERE g NOT BETWEEN 251 AND 400; +VACUUM ANALYZE pfx_img; +}); + is( $primary->safe_psql( + 'postgres', q{ +SELECT count(*) > 0 + FROM (SELECT b, i.itemoffset + FROM generate_series(1, + (pg_relation_size('pfx_img_k') / + current_setting('block_size')::int)::int - 1) b, + LATERAL bt_page_stats('pfx_img_k', b) s, + LATERAL bt_page_items('pfx_img_k', b) i, + LATERAL unnest(i.tids) t(tid) + JOIN pfx_img h ON h.ctid = t.tid + WHERE s.type = 'l' AND (s.btpo_flags & 512) <> 0 + GROUP BY 1, 2 + HAVING count(DISTINCT pg_column_compression(h.k)) = 2) m; +}), + 't', + 'coded posting lists merge pglz and lz4 representations'); + + $primary->wait_for_replay_catchup($standby); + my $query = q{SELECT count(*), md5(string_agg(k, '|' ORDER BY k)) + FROM pfx_img}; + my $expected = $primary->safe_psql('postgres', + 'SET enable_indexscan = off; SET enable_indexonlyscan = off; ' + . 'SET enable_bitmapscan = off; ' . $query); + foreach my $node ($primary, $standby) + { + is( $node->safe_psql('postgres', + "SELECT bt_index_check('pfx_img_k', true)"), + '', 'mixed-representation index passes amcheck'); + my $ios = 'SET enable_seqscan = off; SET enable_bitmapscan = off; '; + like( + $node->safe_psql('postgres', $ios . 'EXPLAIN (COSTS OFF) ' . $query), + qr/Index Only Scan using pfx_img_k/, + 'mixed-representation digest uses index-only scan'); + is($node->safe_psql('postgres', $ios . $query), + $expected, 'mixed-representation index returns the heap values'); + } +} + +# A nondeterministic collation has no equalimage support, so deduplication +# stays off while prefix compression shares the identical bytes of keys that +# compare equal but are stored differently. Each case variant must come back +# unchanged, and uniqueness must still use the collation's equality. +SKIP: +{ + skip 'nondeterministic collations require ICU', 9 + unless check_pg_config('^#define USE_ICU 1$'); + + # ICU collations need a UTF8 database, whatever the cluster's default. + $primary->safe_psql('postgres', + "CREATE DATABASE pfx_icu ENCODING 'UTF8' LOCALE 'C' TEMPLATE template0" + ); + $primary->safe_psql( + 'pfx_icu', q{ +CREATE EXTENSION amcheck; +CREATE EXTENSION pageinspect; +CREATE COLLATION pfx_ci (provider = icu, locale = 'und-u-ks-level2', + deterministic = false); +CREATE TABLE pfx_nd (k text COLLATE pfx_ci) WITH (autovacuum_enabled = off); +INSERT INTO pfx_nd + SELECT v || lpad(g::text, 5, '0') + FROM generate_series(1, 1500) g, + unnest(ARRAY['https://example.com/path/to/resource/', + 'https://EXAMPLE.com/path/to/resource/', + 'HTTPS://EXAMPLE.COM/PATH/TO/RESOURCE/']) v; +CREATE INDEX pfx_nd_k ON pfx_nd (k) WITH (prefix_compression = on); +INSERT INTO pfx_nd + SELECT 'https://Example.Com/Path/To/Resource/' || lpad(g::text, 5, '0') + FROM generate_series(1, 1500) g; +CREATE TABLE pfx_nd_u (k text COLLATE pfx_ci) WITH (autovacuum_enabled = off); +INSERT INTO pfx_nd_u + SELECT 'https://example.com/path/to/resource/' || lpad(g::text, 5, '0') + FROM generate_series(1, 3000) g; +CREATE UNIQUE INDEX pfx_nd_u_k ON pfx_nd_u (k) + WITH (prefix_compression = on); +VACUUM ANALYZE pfx_nd; +VACUUM ANALYZE pfx_nd_u; +}); + is( $primary->safe_psql( + 'pfx_icu', q{ +SELECT NOT m.allequalimage AND + bool_or(s.type = 'l' AND (s.btpo_flags & 512) <> 0) AND + NOT bool_or(i.tids IS NOT NULL) + FROM bt_metap('pfx_nd_k') m, + generate_series(1, + (pg_relation_size('pfx_nd_k') / + current_setting('block_size')::int)::int - 1) b, + LATERAL bt_page_stats('pfx_nd_k', b) s, + LATERAL bt_page_items('pfx_nd_k', b) i + GROUP BY m.allequalimage; +}), + 't', + 'nondeterministic index is coded without posting lists'); + + my ($ret, $stdout, $stderr) = $primary->psql('pfx_icu', + "INSERT INTO pfx_nd_u VALUES ('HTTPS://EXAMPLE.COM/PATH/TO/RESOURCE/01234')"); + is($ret, 3, 'case variant of an existing key is rejected'); + like( + $stderr, + qr/duplicate key value violates unique constraint "pfx_nd_u_k"/, + 'nondeterministic uniqueness is checked on coded leaves'); + + $primary->wait_for_replay_catchup($standby); + my $query = q{SELECT count(*), md5(string_agg(k, '|' ORDER BY k COLLATE "C")) + FROM pfx_nd}; + my $expected = $primary->safe_psql('pfx_icu', + 'SET enable_indexscan = off; SET enable_indexonlyscan = off; ' + . 'SET enable_bitmapscan = off; ' . $query); + my $ios = 'SET enable_seqscan = off; SET enable_bitmapscan = off; '; + foreach my $node ($primary, $standby) + { + is( $node->safe_psql('pfx_icu', + "SELECT bt_index_check('pfx_nd_k', true)"), + '', 'nondeterministic index passes amcheck'); + is($node->safe_psql('pfx_icu', $ios . $query), + $expected, 'nondeterministic index returns every variant unchanged'); + } + like( + $primary->safe_psql('pfx_icu', $ios . 'EXPLAIN (COSTS OFF) ' . $query), + qr/Index Only Scan using pfx_nd_k/, + 'nondeterministic digest uses index-only scan'); + is( $standby->safe_psql( + 'pfx_icu', $ios . q{ +SELECT string_agg(k, ',' ORDER BY k COLLATE "C") FROM pfx_nd + WHERE k = 'https://example.com/path/to/resource/00042'; +}), + 'HTTPS://EXAMPLE.COM/PATH/TO/RESOURCE/00042,' + . 'https://EXAMPLE.com/path/to/resource/00042,' + . 'https://Example.Com/Path/To/Resource/00042,' + . 'https://example.com/path/to/resource/00042', + 'equality probe finds all case variants'); +} + +done_testing(); diff --git a/src/test/regress/expected/btree_index.out b/src/test/regress/expected/btree_index.out index 7c53d598649cb..6e18bf328ff2f 100644 --- a/src/test/regress/expected/btree_index.out +++ b/src/test/regress/expected/btree_index.out @@ -891,3 +891,358 @@ ALTER INDEX btree_part_idx ALTER COLUMN id SET (n_distinct=100); ERROR: ALTER action ALTER COLUMN ... SET cannot be performed on relation "btree_part_idx" DETAIL: This operation is not supported for partitioned indexes. DROP TABLE btree_part; +-- +-- Leaf key prefix compression (prefix_compression reloption). +-- +-- Forced scans of a prefix-compressed index must return what the heap or the +-- inserted literals return, after build, retail inserts and splits, and +-- VACUUM. The keys share a long prefix, sit around 127 bytes (where the +-- varlena header grows from 1 to 4 bytes, so neighbors share only a +-- header-length prefix), exceed a group's anchor, share nothing, or are NULL. +-- The C collation keeps the output platform-independent. +-- +CREATE TABLE btree_prefix (u text COLLATE "C"); +INSERT INTO btree_prefix + SELECT 'https://example.com/path/to/resource/' || lpad((g % 20000)::text, 8, '0') + FROM generate_series(1, 20000) g; +INSERT INTO btree_prefix + SELECT repeat('a', 40) || repeat('b', n) FROM generate_series(85, 90) n; +INSERT INTO btree_prefix VALUES + (repeat('a', 125)), (repeat('a', 126)), (repeat('a', 127)), (repeat('a', 300)), + ('zzz-no-shared-prefix'), (NULL); +CREATE INDEX btree_prefix_on ON btree_prefix (u) WITH (prefix_compression = on); +-- The queries below must read the index, not fall back to the heap. +SET enable_seqscan = off; +SET enable_bitmapscan = off; +EXPLAIN (costs off) + SELECT u FROM btree_prefix WHERE u = 'https://example.com/path/to/resource/00012345'; + QUERY PLAN +--------------------------------------------------------------------------- + Index Only Scan using btree_prefix_on on btree_prefix + Index Cond: (u = 'https://example.com/path/to/resource/00012345'::text) +(2 rows) + +-- The recorded output is the oracle for these scans. +SELECT count(*) FROM btree_prefix + WHERE u = 'https://example.com/path/to/resource/00012345'; + count +------- + 1 +(1 row) + +SELECT count(*) FROM btree_prefix + WHERE u BETWEEN 'https://example.com/path/to/resource/00000100' + AND 'https://example.com/path/to/resource/00000900'; + count +------- + 801 +(1 row) + +SELECT u FROM btree_prefix + WHERE u > 'https://example.com/path/to/resource/00019996' ORDER BY u DESC; + u +----------------------------------------------- + zzz-no-shared-prefix + https://example.com/path/to/resource/00019999 + https://example.com/path/to/resource/00019998 + https://example.com/path/to/resource/00019997 +(4 rows) + +-- Boundary and oversized keys round-trip to their exact stored values. +SELECT u FROM btree_prefix WHERE u LIKE 'aaaa%' ORDER BY u; + u +-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +(10 rows) + +SELECT count(*) FROM btree_prefix WHERE u = repeat('a', 300); + count +------- + 1 +(1 row) + +SELECT count(*) FROM btree_prefix WHERE u IS NULL; + count +------- + 1 +(1 row) + +-- Compare an index-only scan with the inserted literals. The plan shows the +-- keys come from decoded index tuples, not the heap. +EXPLAIN (costs off) + SELECT md5(string_agg(u, '|' ORDER BY u)) FROM btree_prefix WHERE u IS NOT NULL; + QUERY PLAN +------------------------------------------------------------- + Aggregate + -> Index Only Scan using btree_prefix_on on btree_prefix + Index Cond: (u IS NOT NULL) +(3 rows) + +SELECT (SELECT md5(string_agg(u, '|' ORDER BY u)) + FROM btree_prefix WHERE u IS NOT NULL) = + md5(string_agg(x, '|' ORDER BY x)) AS ios_ok + FROM ( + SELECT 'https://example.com/path/to/resource/' || lpad((g % 20000)::text, 8, '0') AS x + FROM generate_series(1, 20000) g + UNION ALL SELECT repeat('a', 40) || repeat('b', n) FROM generate_series(85, 90) n + UNION ALL SELECT v FROM (VALUES (repeat('a',125)),(repeat('a',126)), + (repeat('a',127)),(repeat('a',300)), + ('zzz-no-shared-prefix')) t(v) + ) oracle; + ios_ok +-------- + t +(1 row) + +INSERT INTO btree_prefix + SELECT 'https://example.com/other/' || lpad(g::text, 8, '0') + FROM generate_series(1, 10000) g; +-- Delete only part of the URL range, so the boundary keys survive for later +-- checks. +DELETE FROM btree_prefix + WHERE u >= 'https://example.com/path/to/resource/00000000' + AND u < 'https://example.com/path/to/resource/00005000'; +VACUUM btree_prefix; +INSERT INTO btree_prefix + SELECT 'https://example.com/path/to/resource/' || lpad((g % 5000)::text, 8, '0') + FROM generate_series(1, 5000) g; +-- The index-only digest must equal the digest of a sequential heap scan. +EXPLAIN (costs off) + SELECT md5(string_agg(u, '|' ORDER BY u)) FROM btree_prefix WHERE u IS NOT NULL; + QUERY PLAN +------------------------------------------------------------- + Aggregate + -> Index Only Scan using btree_prefix_on on btree_prefix + Index Cond: (u IS NOT NULL) +(3 rows) + +SELECT md5(string_agg(u, '|' ORDER BY u)) AS ios_digest + FROM btree_prefix WHERE u IS NOT NULL \gset +SET enable_indexscan = off; +SET enable_seqscan = on; +EXPLAIN (costs off) + SELECT md5(string_agg(u, '|' ORDER BY u)) FROM btree_prefix WHERE u IS NOT NULL; + QUERY PLAN +--------------------------------------- + Aggregate + -> Sort + Sort Key: u COLLATE "C" + -> Seq Scan on btree_prefix + Filter: (u IS NOT NULL) +(5 rows) + +SELECT :'ios_digest' = + (SELECT md5(string_agg(u, '|' ORDER BY u)) FROM btree_prefix WHERE u IS NOT NULL) + AS post_churn_ok; + post_churn_ok +--------------- + t +(1 row) + +RESET enable_indexscan; +RESET enable_seqscan; +RESET enable_bitmapscan; +-- The reloption round-trips and can be toggled without a rewrite. +SELECT reloptions FROM pg_class WHERE relname = 'btree_prefix_on'; + reloptions +------------------------- + {prefix_compression=on} +(1 row) + +ALTER INDEX btree_prefix_on SET (prefix_compression = off); +SELECT reloptions FROM pg_class WHERE relname = 'btree_prefix_on'; + reloptions +-------------------------- + {prefix_compression=off} +(1 row) + +-- Reading back with the option off still returns correct rows: existing +-- BTP_PREFIX leaves keep their coded form and decode on the page flag. +SET enable_seqscan = off; +SELECT count(*) FROM btree_prefix WHERE u = repeat('a', 126); + count +------- + 1 +(1 row) + +RESET enable_seqscan; +-- Verify scans of a fixed-width key with prefix compression enabled. +CREATE INDEX btree_prefix_int ON btree_prefix ((length(u))) WITH (prefix_compression = on); +SET enable_seqscan = off; +SET enable_bitmapscan = off; +EXPLAIN (costs off) + SELECT length(u) FROM btree_prefix WHERE length(u) = 300; + QUERY PLAN +--------------------------------------------------- + Index Scan using btree_prefix_int on btree_prefix + Index Cond: (length(u) = 300) +(2 rows) + +SELECT length(u) FROM btree_prefix WHERE length(u) = 300; + length +-------- + 300 +(1 row) + +RESET enable_seqscan; +RESET enable_bitmapscan; +DROP TABLE btree_prefix; +-- +-- Bottom-up index deletion on prefix-compressed pages. +-- +-- Non-key UPDATEs make "logically unchanged" index inserts, so full coded +-- leaves get a bottom-up deletion pass before they split. What the pass can +-- remove depends on timing, so only the index contents are checked. +-- +CREATE TABLE btree_prefix_bu (id int PRIMARY KEY, u text COLLATE "C", filler text); +INSERT INTO btree_prefix_bu + SELECT g, 'https://example.com/path/' || lpad((g % 500)::text, 8, '0'), repeat('x', 40) + FROM generate_series(1, 4000) g; +CREATE INDEX btree_prefix_bu_u ON btree_prefix_bu (u) WITH (prefix_compression = on); +UPDATE btree_prefix_bu SET filler = repeat('y', 40); +UPDATE btree_prefix_bu SET filler = repeat('z', 40); +UPDATE btree_prefix_bu SET filler = repeat('w', 40); +SET enable_seqscan = off; +SET enable_bitmapscan = off; +EXPLAIN (costs off) SELECT u FROM btree_prefix_bu; + QUERY PLAN +------------------------------------------------------------ + Index Only Scan using btree_prefix_bu_u on btree_prefix_bu +(1 row) + +SELECT (SELECT md5(string_agg(u, '|' ORDER BY u)) FROM btree_prefix_bu) = + md5(string_agg(x, '|' ORDER BY x)) AS bottomup_ok + FROM (SELECT 'https://example.com/path/' || lpad((g % 500)::text, 8, '0') AS x + FROM generate_series(1, 4000) g) oracle; + bottomup_ok +------------- + t +(1 row) + +SELECT count(*) FROM btree_prefix_bu + WHERE u = 'https://example.com/path/' || lpad('7', 8, '0'); + count +------- + 8 +(1 row) + +RESET enable_seqscan; +RESET enable_bitmapscan; +DROP TABLE btree_prefix_bu; +-- A final coded leaf must fit all posting tuples, not just the layout with +-- the last posting tuple replaced by a high key. +CREATE TABLE btree_prefix_post (u text COLLATE "C"); +INSERT INTO btree_prefix_post + SELECT repeat('x', 119) FROM generate_series(1, 1356); +CREATE INDEX btree_prefix_post_u ON btree_prefix_post (u) + WITH (prefix_compression = on); +SET enable_seqscan = off; +SET enable_bitmapscan = off; +SELECT count(*) FROM btree_prefix_post WHERE u = repeat('x', 119); + count +------- + 1356 +(1 row) + +RESET enable_seqscan; +RESET enable_bitmapscan; +DROP TABLE btree_prefix_post; +-- +-- Runtime deduplication on prefix-compressed leaves. Retail inserts of +-- duplicates fill coded leaves, which deduplicate and re-code before they +-- split. +-- +CREATE TABLE btree_prefix_dd (u text COLLATE "C"); +CREATE INDEX btree_prefix_dd_u ON btree_prefix_dd (u) WITH (prefix_compression = on); +INSERT INTO btree_prefix_dd + SELECT 'https://example.com/path/to/resource/' || lpad((g % 200)::text, 8, '0') + FROM generate_series(1, 40000) g; +SET enable_seqscan = off; +SET enable_bitmapscan = off; +EXPLAIN (costs off) SELECT u FROM btree_prefix_dd; + QUERY PLAN +------------------------------------------------------------ + Index Only Scan using btree_prefix_dd_u on btree_prefix_dd +(1 row) + +SELECT (SELECT md5(string_agg(u, '|' ORDER BY u)) FROM btree_prefix_dd) = + md5(string_agg(x, '|' ORDER BY x)) AS runtime_dedup_ok + FROM (SELECT 'https://example.com/path/to/resource/' || lpad((g % 200)::text, 8, '0') AS x + FROM generate_series(1, 40000) g) oracle; + runtime_dedup_ok +------------------ + t +(1 row) + +SELECT count(*) FROM btree_prefix_dd + WHERE u = 'https://example.com/path/to/resource/' || lpad('42', 8, '0'); + count +------- + 200 +(1 row) + +RESET enable_seqscan; +RESET enable_bitmapscan; +DROP TABLE btree_prefix_dd; +-- +-- Compression actually happens, both when an index is built and when it grows +-- by insertion: a prefix-compressed index on keys with a long shared prefix +-- is much smaller than a plain one. +-- +CREATE TABLE btree_prefix_sz (u text COLLATE "C"); +INSERT INTO btree_prefix_sz + SELECT 'https://example.com/path/to/resource/' || lpad(g::text, 8, '0') + FROM generate_series(1, 20000) g; +CREATE INDEX btree_prefix_sz_on ON btree_prefix_sz (u) WITH (prefix_compression = on); +CREATE INDEX btree_prefix_sz_off ON btree_prefix_sz (u); +SELECT pg_relation_size('btree_prefix_sz_on') * 3 < + pg_relation_size('btree_prefix_sz_off') * 2 AS build_compresses; + build_compresses +------------------ + t +(1 row) + +TRUNCATE btree_prefix_sz; +INSERT INTO btree_prefix_sz + SELECT 'https://example.com/path/to/resource/' || lpad(((g * 7919) % 20000)::text, 8, '0') + FROM generate_series(1, 20000) g; +SELECT pg_relation_size('btree_prefix_sz_on') * 3 < + pg_relation_size('btree_prefix_sz_off') * 2 AS insert_compresses; + insert_compresses +------------------- + t +(1 row) + +DROP TABLE btree_prefix_sz; +-- +-- Multiple prefix groups per page. When a leaf's first tuple shares only a +-- short prefix (here the leading int column) with a long run of tuples that +-- share much more among themselves, the run must form its own group rather +-- than stay anchored to that first tuple. Without per-page grouping this case +-- does not compress at all. +-- +CREATE TABLE btree_prefix_grp (tenant int4, u text COLLATE "C"); +INSERT INTO btree_prefix_grp VALUES (1001, 'a'); +INSERT INTO btree_prefix_grp + SELECT 1001, 'https://shop.example.com/pay/' || lpad(g::text, 6, '0') + FROM generate_series(1, 150 * current_setting('block_size')::integer / 8192) g; +CREATE INDEX btree_prefix_grp_on ON btree_prefix_grp (tenant, u) + WITH (prefix_compression = on); +CREATE INDEX btree_prefix_grp_off ON btree_prefix_grp (tenant, u); +SELECT pg_relation_size('btree_prefix_grp_on') < + pg_relation_size('btree_prefix_grp_off') AS groups_compress; + groups_compress +----------------- + t +(1 row) + +DROP TABLE btree_prefix_grp; diff --git a/src/test/regress/pg_regress.c b/src/test/regress/pg_regress.c index 809b188bce578..0385b74936897 100644 --- a/src/test/regress/pg_regress.c +++ b/src/test/regress/pg_regress.c @@ -1243,7 +1243,7 @@ spawn_process(const char *cmdline) char *cmdline2; cmdline2 = psprintf("exec %s", cmdline); - execl(shellprog, shellprog, "-c", cmdline2, (char *) NULL); + execlp(shellprog, shellprog, "-c", cmdline2, (char *) NULL); /* Not using the normal bail() here as we want _exit */ bail_noatexit("could not exec \"%s\": %m", shellprog); } diff --git a/src/test/regress/sql/btree_index.sql b/src/test/regress/sql/btree_index.sql index 6990d7818da47..e516b8d6c8457 100644 --- a/src/test/regress/sql/btree_index.sql +++ b/src/test/regress/sql/btree_index.sql @@ -520,3 +520,213 @@ CREATE TABLE btree_part (id int4) PARTITION BY RANGE (id); CREATE INDEX btree_part_idx ON btree_part(id); ALTER INDEX btree_part_idx ALTER COLUMN id SET (n_distinct=100); DROP TABLE btree_part; + +-- +-- Leaf key prefix compression (prefix_compression reloption). +-- +-- Forced scans of a prefix-compressed index must return what the heap or the +-- inserted literals return, after build, retail inserts and splits, and +-- VACUUM. The keys share a long prefix, sit around 127 bytes (where the +-- varlena header grows from 1 to 4 bytes, so neighbors share only a +-- header-length prefix), exceed a group's anchor, share nothing, or are NULL. +-- The C collation keeps the output platform-independent. +-- +CREATE TABLE btree_prefix (u text COLLATE "C"); +INSERT INTO btree_prefix + SELECT 'https://example.com/path/to/resource/' || lpad((g % 20000)::text, 8, '0') + FROM generate_series(1, 20000) g; +INSERT INTO btree_prefix + SELECT repeat('a', 40) || repeat('b', n) FROM generate_series(85, 90) n; +INSERT INTO btree_prefix VALUES + (repeat('a', 125)), (repeat('a', 126)), (repeat('a', 127)), (repeat('a', 300)), + ('zzz-no-shared-prefix'), (NULL); +CREATE INDEX btree_prefix_on ON btree_prefix (u) WITH (prefix_compression = on); + +-- The queries below must read the index, not fall back to the heap. +SET enable_seqscan = off; +SET enable_bitmapscan = off; +EXPLAIN (costs off) + SELECT u FROM btree_prefix WHERE u = 'https://example.com/path/to/resource/00012345'; + +-- The recorded output is the oracle for these scans. +SELECT count(*) FROM btree_prefix + WHERE u = 'https://example.com/path/to/resource/00012345'; +SELECT count(*) FROM btree_prefix + WHERE u BETWEEN 'https://example.com/path/to/resource/00000100' + AND 'https://example.com/path/to/resource/00000900'; +SELECT u FROM btree_prefix + WHERE u > 'https://example.com/path/to/resource/00019996' ORDER BY u DESC; +-- Boundary and oversized keys round-trip to their exact stored values. +SELECT u FROM btree_prefix WHERE u LIKE 'aaaa%' ORDER BY u; +SELECT count(*) FROM btree_prefix WHERE u = repeat('a', 300); +SELECT count(*) FROM btree_prefix WHERE u IS NULL; + +-- Compare an index-only scan with the inserted literals. The plan shows the +-- keys come from decoded index tuples, not the heap. +EXPLAIN (costs off) + SELECT md5(string_agg(u, '|' ORDER BY u)) FROM btree_prefix WHERE u IS NOT NULL; +SELECT (SELECT md5(string_agg(u, '|' ORDER BY u)) + FROM btree_prefix WHERE u IS NOT NULL) = + md5(string_agg(x, '|' ORDER BY x)) AS ios_ok + FROM ( + SELECT 'https://example.com/path/to/resource/' || lpad((g % 20000)::text, 8, '0') AS x + FROM generate_series(1, 20000) g + UNION ALL SELECT repeat('a', 40) || repeat('b', n) FROM generate_series(85, 90) n + UNION ALL SELECT v FROM (VALUES (repeat('a',125)),(repeat('a',126)), + (repeat('a',127)),(repeat('a',300)), + ('zzz-no-shared-prefix')) t(v) + ) oracle; + +INSERT INTO btree_prefix + SELECT 'https://example.com/other/' || lpad(g::text, 8, '0') + FROM generate_series(1, 10000) g; +-- Delete only part of the URL range, so the boundary keys survive for later +-- checks. +DELETE FROM btree_prefix + WHERE u >= 'https://example.com/path/to/resource/00000000' + AND u < 'https://example.com/path/to/resource/00005000'; +VACUUM btree_prefix; +INSERT INTO btree_prefix + SELECT 'https://example.com/path/to/resource/' || lpad((g % 5000)::text, 8, '0') + FROM generate_series(1, 5000) g; +-- The index-only digest must equal the digest of a sequential heap scan. +EXPLAIN (costs off) + SELECT md5(string_agg(u, '|' ORDER BY u)) FROM btree_prefix WHERE u IS NOT NULL; +SELECT md5(string_agg(u, '|' ORDER BY u)) AS ios_digest + FROM btree_prefix WHERE u IS NOT NULL \gset +SET enable_indexscan = off; +SET enable_seqscan = on; +EXPLAIN (costs off) + SELECT md5(string_agg(u, '|' ORDER BY u)) FROM btree_prefix WHERE u IS NOT NULL; +SELECT :'ios_digest' = + (SELECT md5(string_agg(u, '|' ORDER BY u)) FROM btree_prefix WHERE u IS NOT NULL) + AS post_churn_ok; +RESET enable_indexscan; +RESET enable_seqscan; +RESET enable_bitmapscan; + +-- The reloption round-trips and can be toggled without a rewrite. +SELECT reloptions FROM pg_class WHERE relname = 'btree_prefix_on'; +ALTER INDEX btree_prefix_on SET (prefix_compression = off); +SELECT reloptions FROM pg_class WHERE relname = 'btree_prefix_on'; +-- Reading back with the option off still returns correct rows: existing +-- BTP_PREFIX leaves keep their coded form and decode on the page flag. +SET enable_seqscan = off; +SELECT count(*) FROM btree_prefix WHERE u = repeat('a', 126); +RESET enable_seqscan; + +-- Verify scans of a fixed-width key with prefix compression enabled. +CREATE INDEX btree_prefix_int ON btree_prefix ((length(u))) WITH (prefix_compression = on); +SET enable_seqscan = off; +SET enable_bitmapscan = off; +EXPLAIN (costs off) + SELECT length(u) FROM btree_prefix WHERE length(u) = 300; +SELECT length(u) FROM btree_prefix WHERE length(u) = 300; +RESET enable_seqscan; +RESET enable_bitmapscan; +DROP TABLE btree_prefix; + +-- +-- Bottom-up index deletion on prefix-compressed pages. +-- +-- Non-key UPDATEs make "logically unchanged" index inserts, so full coded +-- leaves get a bottom-up deletion pass before they split. What the pass can +-- remove depends on timing, so only the index contents are checked. +-- +CREATE TABLE btree_prefix_bu (id int PRIMARY KEY, u text COLLATE "C", filler text); +INSERT INTO btree_prefix_bu + SELECT g, 'https://example.com/path/' || lpad((g % 500)::text, 8, '0'), repeat('x', 40) + FROM generate_series(1, 4000) g; +CREATE INDEX btree_prefix_bu_u ON btree_prefix_bu (u) WITH (prefix_compression = on); +UPDATE btree_prefix_bu SET filler = repeat('y', 40); +UPDATE btree_prefix_bu SET filler = repeat('z', 40); +UPDATE btree_prefix_bu SET filler = repeat('w', 40); +SET enable_seqscan = off; +SET enable_bitmapscan = off; +EXPLAIN (costs off) SELECT u FROM btree_prefix_bu; +SELECT (SELECT md5(string_agg(u, '|' ORDER BY u)) FROM btree_prefix_bu) = + md5(string_agg(x, '|' ORDER BY x)) AS bottomup_ok + FROM (SELECT 'https://example.com/path/' || lpad((g % 500)::text, 8, '0') AS x + FROM generate_series(1, 4000) g) oracle; +SELECT count(*) FROM btree_prefix_bu + WHERE u = 'https://example.com/path/' || lpad('7', 8, '0'); +RESET enable_seqscan; +RESET enable_bitmapscan; +DROP TABLE btree_prefix_bu; + +-- A final coded leaf must fit all posting tuples, not just the layout with +-- the last posting tuple replaced by a high key. +CREATE TABLE btree_prefix_post (u text COLLATE "C"); +INSERT INTO btree_prefix_post + SELECT repeat('x', 119) FROM generate_series(1, 1356); +CREATE INDEX btree_prefix_post_u ON btree_prefix_post (u) + WITH (prefix_compression = on); +SET enable_seqscan = off; +SET enable_bitmapscan = off; +SELECT count(*) FROM btree_prefix_post WHERE u = repeat('x', 119); +RESET enable_seqscan; +RESET enable_bitmapscan; +DROP TABLE btree_prefix_post; + +-- +-- Runtime deduplication on prefix-compressed leaves. Retail inserts of +-- duplicates fill coded leaves, which deduplicate and re-code before they +-- split. +-- +CREATE TABLE btree_prefix_dd (u text COLLATE "C"); +CREATE INDEX btree_prefix_dd_u ON btree_prefix_dd (u) WITH (prefix_compression = on); +INSERT INTO btree_prefix_dd + SELECT 'https://example.com/path/to/resource/' || lpad((g % 200)::text, 8, '0') + FROM generate_series(1, 40000) g; +SET enable_seqscan = off; +SET enable_bitmapscan = off; +EXPLAIN (costs off) SELECT u FROM btree_prefix_dd; +SELECT (SELECT md5(string_agg(u, '|' ORDER BY u)) FROM btree_prefix_dd) = + md5(string_agg(x, '|' ORDER BY x)) AS runtime_dedup_ok + FROM (SELECT 'https://example.com/path/to/resource/' || lpad((g % 200)::text, 8, '0') AS x + FROM generate_series(1, 40000) g) oracle; +SELECT count(*) FROM btree_prefix_dd + WHERE u = 'https://example.com/path/to/resource/' || lpad('42', 8, '0'); +RESET enable_seqscan; +RESET enable_bitmapscan; +DROP TABLE btree_prefix_dd; + +-- +-- Compression actually happens, both when an index is built and when it grows +-- by insertion: a prefix-compressed index on keys with a long shared prefix +-- is much smaller than a plain one. +-- +CREATE TABLE btree_prefix_sz (u text COLLATE "C"); +INSERT INTO btree_prefix_sz + SELECT 'https://example.com/path/to/resource/' || lpad(g::text, 8, '0') + FROM generate_series(1, 20000) g; +CREATE INDEX btree_prefix_sz_on ON btree_prefix_sz (u) WITH (prefix_compression = on); +CREATE INDEX btree_prefix_sz_off ON btree_prefix_sz (u); +SELECT pg_relation_size('btree_prefix_sz_on') * 3 < + pg_relation_size('btree_prefix_sz_off') * 2 AS build_compresses; +TRUNCATE btree_prefix_sz; +INSERT INTO btree_prefix_sz + SELECT 'https://example.com/path/to/resource/' || lpad(((g * 7919) % 20000)::text, 8, '0') + FROM generate_series(1, 20000) g; +SELECT pg_relation_size('btree_prefix_sz_on') * 3 < + pg_relation_size('btree_prefix_sz_off') * 2 AS insert_compresses; +DROP TABLE btree_prefix_sz; + +-- +-- Multiple prefix groups per page. When a leaf's first tuple shares only a +-- short prefix (here the leading int column) with a long run of tuples that +-- share much more among themselves, the run must form its own group rather +-- than stay anchored to that first tuple. Without per-page grouping this case +-- does not compress at all. +-- +CREATE TABLE btree_prefix_grp (tenant int4, u text COLLATE "C"); +INSERT INTO btree_prefix_grp VALUES (1001, 'a'); +INSERT INTO btree_prefix_grp + SELECT 1001, 'https://shop.example.com/pay/' || lpad(g::text, 6, '0') + FROM generate_series(1, 150 * current_setting('block_size')::integer / 8192) g; +CREATE INDEX btree_prefix_grp_on ON btree_prefix_grp (tenant, u) + WITH (prefix_compression = on); +CREATE INDEX btree_prefix_grp_off ON btree_prefix_grp (tenant, u); +SELECT pg_relation_size('btree_prefix_grp_on') < + pg_relation_size('btree_prefix_grp_off') AS groups_compress; +DROP TABLE btree_prefix_grp; diff --git a/src/tools/pgindent/pgindent b/src/tools/pgindent/pgindent index f75c006bbff43..5e79bea47cf96 100755 --- a/src/tools/pgindent/pgindent +++ b/src/tools/pgindent/pgindent @@ -1,4 +1,4 @@ -#!/usr/bin/perl +#!/usr/bin/env perl # Copyright (c) 2021-2026, PostgreSQL Global Development Group diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index f10eb46926676..1831b3d0d4478 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -215,6 +215,7 @@ BTDeletedPageData BTIndexStat BTInsertState BTInsertStateData +BTItemBuf BTLeader BTMetaPageData BTOneVacInfo @@ -226,6 +227,12 @@ BTPageStat BTPageState BTParallelScanDesc BTPendingFSM +BTPrefixAnchor +BTPrefixAnchorDisk +BTPrefixCode +BTPrefixDir +BTPrefixDirHdr +BTPrefixPageEst BTReadPageState BTScanInsert BTScanInsertData