Repository navigation
Conversation
Two changes to HASH's lock scope, not its page layout:
1. take the hash metapage lock only when the per-handle cached bucket
mapping may be stale (format-compatible), so the common lookup or
insert never locks the metapage;
2. make a bucket split non-fencing with per-bucket split state (opt-in,
new format version).
The motivation is read from the source. Every hash cursor operation
takes a metapage READ lock, which degree-3 transactions keep until they
end. A split upgrades the cursor's metapage lock to WRITE and holds it
through __ham_split_page and, under a transaction, until commit. The
"after releasing metapage" comment in __ham_expand_table refers to
metalock, the master database's metapage for subdatabase allocation, not
the hash metapage; the RFC says so and cites the call chain.
The INDEX table now has four cells on every row. Rows 0012-0016 had
three; their Type is filled from the RFCs (0013 is a plan). RFC 0004
gains a Related line pointing at 0017. rfc/0017/README.md is the
evidence plan.
Write the change-1 design before coding, per the checkpoint protocol: the cache-and-validate scheme, the metapage-LSN staleness stamp (no region or on-disk format change), and a hazard-by-hazard safety argument (lock order, aborted splits, the 7 reader sites, contraction, subdatabases, CDB/non-logging). Primary target is the metapage LSN as the staleness check, which beats RFC option (a) because it needs no __env_struct_sig change. Fallback to (a) only with numbers if the LSN proves unsafe.
…change 1) Keyed HASH lookups and inserts no longer hold a lock-manager lock on the hash metapage for the whole operation (and, under a transaction at degree 3, to transaction end). They map the key through a per-cursor copy of the metapage mapping fields (max_bucket, high_mask, low_mask, spares[]), lock the bucket, then validate the mapping by comparing the real metapage LSN -- read with an unlocked __memp_fget -- against the LSN captured when the copy was taken. A logged split advances the metapage LSN, so a mismatch means the mapping moved under us; the cursor then refreshes the copy and re-maps. No on-disk, log, or region format change (__env_struct_sig unchanged). Scope and safety: - Gated on hcp->cache_ok && STD_LOCKING(dbc) && DBC_LOGGING(dbc). DBC_LOGGING, not LOGGING_ON(env), because a non-logging cursor (DB_TXN_NOT_DURABLE, recovery) takes the LSN_NOT_LOGGED split branch and would not advance the stamp. - cache_ok is set only for keyed point access (DB_SET/SET_RANGE/ GET_BOTH[_RANGE] in __hamc_get; DB_KEYFIRST/KEYLAST/NODUPDATA/ NOOVERWRITE/OVERWRITE_DUP in __hamc_put). Cursor scans keep master's locked metapath so a concurrent committed split cannot make a scan return a relocated record twice. - The copy is filled under a transient metapage READ lock released immediately (__LPUT, not __TLPUT). The READ fill conflicts with a splitter's uncommitted metapage WRITE lock, so a fill can only observe a fully committed or fully aborted mapping -- the torn (old LSN, post-split fields) pair that would defeat the LSN check is unreachable. - Validation reads the metapage with __memp_fget only (no lock-manager lock), so no reader ever holds a bucket lock while waiting on a metapage lock-manager lock; the deadlock order is preserved. - __ham_dirty_meta promotes the cache view to the real write-locked metapage before any metapage write (split/contract/nelem++), and __ham_return_meta promotes even for read-only requests so __db_new / __db_free never shadow the shared free list / last_pgno through the per-cursor snapshot. The full design and hazard-by-hazard argument are in rfc/0017/DESIGN-CHANGE1.md. Generated src/dbinc_auto/hash_ext.h and int_def.in via dist/s_include.
Add src/dbinc/db_quickselect.h, a header-only generic quickselect that
places a requested set of order statistics in place (Hoare partition,
median-of-three, insertion-sort base case) and leaves base[ks[i]]
holding the same element a full qsort would -- so the percentile
reporters that qsort-then-index can swap to selection with identical
output.
Convert the k-th/top-k sites the state file identified:
- src/log/log_handoff_trace.c hoff_pct (p50/p90/p99/p999/max; the mean
is summed separately since it is order-independent);
- test/bench/commit_bench.c phase() and the main latency block;
- test/bench/fsync_probe.c (min/p50/p90/p99/max, both sync modes).
The engine's other qsort calls need full order (idspace gap scan, sync
page order, archive names, txn_stat, join cursor sort, mvcc freelist,
heap/db verify, lock list, rep lsn list, partition keys) and are left
alone; none is a take-the-k-th pattern.
Equivalence proof: test/c/quickselect_equiv.c compares db_quickselect to
qsort at every reported position across random, sorted, reverse-sorted,
all-equal and duplicate-heavy inputs; run_quickselect_equiv.sh runs it
(db tier) and its QS_SABOTAGE arm disables selection and REQUIRES a
failure, proving the check has teeth.
Add the RFC 0017 concurrency benchmark test/bench/hash_conc_bench.c (T
threads, hash + btree control, insert/lookup x txn/notxn, throughput +
p50/p99/p999 + max stall + deadlock/wait counters) and three test/db
correctness runners sharing test/db/hash_conc.c:
- run_hash_conc: concurrent insert/lookup across forced splits, T
threads x P processes, verifying every committed key present once,
no aborted key visible, and DB->verify; a HASH_CONC_SABOTAGE arm
rebuilds hash.c with -DRFC17_SABOTAGE_NO_VALIDATE and requires FAIL;
- run_hash_abort_split: abort a split-forcing txn with concurrent
readers (hazard H2);
- run_hash_notdurable: DB_TXN_NOT_DURABLE fallback (lead review #1).
MANIFEST entries and executable bits added.
Contributor
Coccinelle convention checksNo new violations. ✅ Resolved since baseline (3) -- update dist/cocci/baseline.txt to lock these in. |
Contributor
ABI diff vs
|
…adlock) A blocking __memp_fget of the metapage in __ham_meta_validate deadlocked under 2+ processes each with 2+ threads inserting across forced splits. The validate holds a bucket lock and waits on the metapage buffer latch (MUTEX_READLOCK of bhp->mtx_buf); a concurrent splitter holds that latch (the metapage is dirtied) and then waits for a bucket WRITE lock-manager lock. That bucket-held, wait-on-latch edge closes a cycle the lock-manager deadlock detector cannot see, because a buffer latch is not a lock object -- so the YOUNGEST detector never fires and the processes hang. This is hazard H7 from the design note, which had wrongly assumed the splitter never holds the metapage latch across a bucket-lock wait; the gdb traces show it does. Fix: read the metapage with DB_MPOOL_TRY and, on DB_LOCK_NOTGRANTED, declare the cache stale. The caller then releases the bucket lock and retries, and the refill's metapage READ lock-manager wait against the splitter's WRITE is a real lock-manager edge the detector resolves. A split in progress is also exactly when the mapping may be changing, so declaring it stale is semantically correct too. Verified on EC2 Debian: the 2x2 process/thread hang is gone; run_hash_conc (13715 committed keys, 0 missing, 0 aborted visible, db_verify OK), run_hash_abort_split and run_hash_notdurable all PASS under --enable-diagnostic; and the HASH_CONC_SABOTAGE arm (validation disabled) loses 8566 committed keys and fails db_verify with "item hashes incorrectly", proving the validation carries the load.
The abort mode reads nkeys from argv[5]; the runner passed only 5 args so argc<6 tripped the usage check. Pass an unused nthread placeholder.
…ted plainly
EC2 c6id.8xlarge, Debian 12, XFS on local NVMe instance store (/nvme,
findmnt shows xfs). A/B base=origin/master vs branch, ABAB alternation,
hash_conc_bench; headline insert cells at 9 reps/6s (CV<=6%), full
matrix at 5 reps. Harness test/bench/ab_hash_conc.sh + ab_summary.py;
raw data rfc0017-ab-raw.tsv and rfc0017-ab-insert-tight.tsv; tables
rfc0017-ab-results.md and rfc/0017/README.md.
Result: change 1 does NOT deliver a throughput gain on the insert-heavy,
split-inducing workload. It is a 5-20% throughput REGRESSION at high
concurrency (0.80x at t=32, both txn and notxn), measured confidently.
What it trades for that:
- deadlocks drop ~4 orders of magnitude (~1-2 vs ~22,000-29,000 per
run): master's higher op count is largely deadlock-retry churn under
DB_LOCK_YOUNGEST;
- p99 tail latency roughly halves (960 vs 1770 us at t=16).
Hash point-lookup (the RFC's stated target) is neutral-to-slightly
positive and never regresses. B-tree control and single-threaded hash
are unchanged within noise. Region signature identical (0x841f4ea8).
Recommendation recorded in rfc/0017/README.md: change 1 as implemented
is not worth shipping for throughput alone; the real win needs change 2
(non-fencing split), which removes the whole-table WRITE fence at its
source. The change-1 prototype's findings that constrain change 2 are
added to the RFC.
The header is shared with standalone bench programs (test/bench/fsync_probe.c) that do not include db_int.h, so it needs <stddef.h> for size_t on its own; in an engine TU db_int.h is included first and the include is harmless. Same exception shape as mutex_int.h and win_db.h already have.
…ive) The first A/B scored every attempt as throughput, including transactions aborted by DB_LOCK_DEADLOCK. Base deadlocks under split-heavy inserts and the branch does not, so base was inflated. hash_conc_bench now counts only committed ops, reports aborts separately, and records latency for committed ops only. ab_insert_goodput.sh re-runs the insert cells. Corrected result on c6id.8xlarge, Debian, XFS on the local NVMe (hash cells 9 reps, CV <= 6.5%; the btree control has 2-3 reps because the AWS account expired mid-run): hash insert t<=8: within noise hash insert t=16/32: branch 0.84-0.91x goodput, p99 1.7-2.3x worse btree insert: 0.97-1.02x, unchanged Change 1 alone is a measured negative for split-heavy inserts. The earlier "p99 2x better" claim is withdrawn. The first table is kept, labelled superseded.
The first A/B counted deadlock-aborted attempts as throughput. With goodput counted, the branch is 0.84-0.91x at 16-32 threads, and its p99 is worse, not better. Withdraw the "tail latency halves" claim; change 1 alone is a plain negative; prioritise change 2.
…BER) The trailing __memp_fput overwrote ret unconditionally. Use the house idiom: take t_ret only when ret is 0.
Profiling the first version on m5d.8xlarge (perf, DWARF stacks) showed
it did not remove the cost it was meant to remove. Its per-cursor cache
was refilled under a metapage READ lock on every operation, so
__db_lget/__lock_put on the metapage stayed at about 77% of lookup time
at 32 threads, the same as master. Inserts were worse: the stamp was
the metapage LSN, which moves on every split anywhere, so nearly every
insert retried and refilled.
v2:
- the mapping fields are a hint kept across operations; reading the
hint takes no lock;
- __ham_get_meta_fast maps the key from the hint and locks that
bucket as a probe, then pins the metapage with DB_MPOOL_TRY and
maps again from the live fields. The same page means proceed. A
different page means __LPUT the probe (nothing was read under it),
refresh the hint and retry. A latched metapage (a split is
updating it) falls back to the locked path, so no bucket lock ever
waits on the metapage latch;
- validation recomputes the mapping instead of comparing LSNs, so a
split of another bucket no longer forces a retry;
- __ham_split_page now write-locks the new bucket page as well as
the old one. The metapage WRITE lock used to be the only fence on
the new bucket;
- not used under MVCC, dirty reads or recovery. Scans and
positional ops keep the locked metapage.
The benchmark default cache was 512 MB, smaller than its own ~1 GB
ffactor-4 database, so every earlier run measured buffer eviction in
__memp_alloc (93% of the time), not hash locking. The default is now
4 GB (HC_CACHE_MB overrides it). Earlier results are invalid and will
be replaced.
Not yet built or measured: the spot host was reclaimed as the build
started.
Measured v2 on c6id.8xlarge, Debian 12, XFS on the local NVMe, A/B against origin/master 411e58f. Arms alternate with rotation, 5 reps (9 for transactional lookups), committed ops only, 4 GB cache. hash insert, txn and non-txn: 1.14-1.46x at 4-32 threads hash lookup, non-txn: 1.12-1.68x at 1-4, 3.7-11.6x at 8-32 hash lookup, txn: 1.10-1.24x at 1-4; 0.93-1.10x at 8-32, inside the 8% master-vs-master noise floor; both arms are bound there by the txn region mutex in __txn_begin/__txn_end btree control: 0.99-1.04x in every cell Hash insert p99 rises at 16-32 threads while goodput rises 32-46%; master's lower p99 there comes with 1000-2450 deadlock aborts/s. Correctness on the same commit: - test/db tier 43/43 on --enable-diagnostic (lock-order checker on); - TCL test001-test060 under -hash 60/60; - the sabotage arm loses 13697/13715 committed keys; - the region signature is 0x841f4ea8 on both arms. run_hash_conc.sh's sabotage arm now rebuilds hash_meta.c, where the validation lives. DESIGN-CHANGE1.md is rewritten for v2, with its correctness argument C1-C7. v1 stays as a negative result. The v1 benchmark tables stay in rfc0017-ab-results.md, marked invalid (512 MB cache for a ~1 GB database).
gburd
marked this pull request as ready for review
October 24, 2026 03:42
…currency # Conflicts: # test/MANIFEST
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
RFC 0017 change 1, plus a quickselect helper for percentile reporting.
Depends on #226. Without it the macOS
defaultjobs hang: the newmulti-process hash test hits a macOS pshared-condvar PANIC that already exists
on master. Run 40055366615 (this branch with #226 merged in, a throwaway probe
branch) passes 50/50, including all four macOS default jobs.
What changes
Keyed hash gets and puts no longer take the hash metapage lock.
Before, every keyed operation acquired a metapage READ lock through the lock
manager, and a transaction held it until commit. At 32 threads, that acquire
and its release at commit were about 84% of lookup time (perf, DWARF stacks).
A split upgraded the lock to WRITE, so inserts that met a split deadlocked:
master aborts 200–2450 transactions per second in the insert benchmark.
Now (
__ham_get_meta_fastinsrc/hash/hash_meta.c):operations.
DB_MPOOL_TRY(a latch, not a lock) and map thekey again.
lock (nothing was read under it), refresh the hint and retry. Metapage
latched by a split: fall back to the old locked path for that call.
__ham_split_pagenow also write-locks the new bucket page. The metapageWRITE lock used to be its only fence.
The correctness argument, C1–C7, is in
rfc/0017/DESIGN-CHANGE1.md. In short:manager's reference count;
the locked path.
No on-disk, log or region change. The region signature is
0x841f4ea8on botharms.
Results
c6id.8xlarge, Debian 12, XFS on the local NVMe instance store, A/B against
origin/master411e58f13.The 0.93 for transactional lookups at t=8 is inside it. There, both arms
spend about 60% in
__txn_begin/__txn_endon the transaction regionmutex, not in hash.
while committed throughput rises 32–46%. Master's lower p99 comes with
1000–2450 deadlock aborts per second; this branch has 30–100.
test/bench/rfc0017-ab-results.md.Tests
test/dbrunners:run_hash_conc: 2 processes × 4 threads, forced splits; every committedkey found once, no aborted key visible,
db_verifyOK;run_hash_abort_split;run_hash_notdurable.HASH_CONC_SABOTAGE=1trusts a stale hint and loses13697/13715 committed keys.
test/dbtier on--enable-diagnostic(lock-order checker on): 43/43.test001–test060under-hash: 60/60.Quickselect
There is no binary heap outside the HEAP access method, so nothing could
switch from a heap. The candidates were places that sort a whole array only to
read percentiles:
src/log/log_handoff_trace.c;test/bench/commit_bench.c;test/bench/fsync_probe.c.They now use
src/dbinc/db_quickselect.h.run_quickselect_equivchecks theresult equals qsort at every percentile, on random, sorted, reverse, all-equal
and duplicate-heavy input, and has its own sabotage arm.
The other engine
qsortcalls need the full order: the idspace gap scan, thesync page order, archive names and the txn stat array.
History
The first implementation (v1) cached the mapping but refilled it under the
metapage lock on every operation, and validated by metapage LSN, which changes
on every split. It was slower. Its benchmark was also invalid: a 512 MB cache
for a ~1 GB database, so it measured buffer eviction. Both are recorded in the
design note and the results file as negative results.
Not done