Skip to content

rfc0017: HASH keyed ops without the metapage lock (change 1) + quickselect - #225

Open
gburd wants to merge 15 commits into
masterfrom
feat/rfc17-hash-concurrency
Open

gburd wants to merge 15 commits into
masterfrom
feat/rfc17-hash-concurrency

Conversation

@gburd

@gburd gburd commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator

RFC 0017 change 1, plus a quickselect helper for percentile reporting.

Depends on #226. Without it the macOS default jobs hang: the new
multi-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_fast in src/hash/hash_meta.c):

  1. Map the key with a per-cursor hint of the mapping fields, kept across
    operations.
  2. Lock that bucket.
  3. Pin the live metapage with DB_MPOOL_TRY (a latch, not a lock) and map the
    key again.
  4. Same page: proceed with no metapage lock. Different page: release the probe
    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_page now also write-locks the new bucket page. The metapage
WRITE lock used to be its only fence.

The correctness argument, C1–C7, is in rfc/0017/DESIGN-CHANGE1.md. In short:

  • every operation that moves a key's page write-locks that bucket;
  • no thread waits on a latch while holding a bucket lock;
  • dropping the probe inside a transaction is safe because of the lock
    manager's reference count;
  • scans, positional ops, bulk get, MVCC, dirty reads, CDB and recovery keep
    the locked path.

No on-disk, log or region change. The region signature is 0x841f4ea8 on both
arms.

Results

c6id.8xlarge, Debian 12, XFS on the local NVMe instance store, A/B against
origin/master 411e58f13.

  • Arms alternate, with rotation.
  • 5 reps per cell (9 for transactional lookups), 5 s each.
  • Committed ops only, 4 GB cache.
workload t=1 t=4 t=8 t=16 t=32
hash insert, txn 1.00 1.14 1.24 1.32 1.46
hash insert, non-txn 1.00 1.14 1.22 1.32 1.46
hash lookup, non-txn 1.12 1.68 3.70 7.27 11.6
hash lookup, txn (9 reps) 1.10 1.19 0.93 1.04 1.10
btree insert, txn 1.00 1.00 1.00 1.01 1.02
btree lookup, txn 1.01 1.03 1.01 1.02 1.02
  • Noise floor (master against master, 9 reps): up to 8% at 8–32 threads.
    The 0.93 for transactional lookups at t=8 is inside it. There, both arms
    spend about 60% in __txn_begin/__txn_end on the transaction region
    mutex, not in hash.
  • Hash insert p99 rises at 16–32 threads (1.4 ms against 0.8 ms at t=16)
    while committed throughput rises 32–46%. Master's lower p99 comes with
    1000–2450 deadlock aborts per second; this branch has 30–100.
  • Full tables and raw TSVs: test/bench/rfc0017-ab-results.md.

Tests

  • New test/db runners:
    • run_hash_conc: 2 processes × 4 threads, forced splits; every committed
      key found once, no aborted key visible, db_verify OK;
    • run_hash_abort_split;
    • run_hash_notdurable.
  • Sabotage arm: HASH_CONC_SABOTAGE=1 trusts a stale hint and loses
    13697/13715 committed keys.
  • test/db tier on --enable-diagnostic (lock-order checker on): 43/43.
  • TCL test001–test060 under -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_equiv checks the
result equals qsort at every percentile, on random, sorted, reverse, all-equal
and duplicate-heavy input, and has its own sabotage arm.

The other engine qsort calls need the full order: the idspace gap scan, the
sync 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

  • No aarch64 or FreeBSD measurement.
  • Change 2 (non-fencing split, new on-disk format) is design only.

gburd added 4 commits October 23, 2026 09:15
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.
@github-actions

github-actions Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Coccinelle convention checks

No new violations. ✅

Resolved since baseline (3) -- update dist/cocci/baseline.txt to lock these in.
rule_mutex_unbalanced|MUTEX_UNBALANCED|src/btree/bt_curadj.c|return (ret);
rule_mutex_unbalanced|MUTEX_UNBALANCED|src/crypto/mersenne/mt19937db.c|return (ret);
rule_mutex_unbalanced|MUTEX_UNBALANCED|src/mp/mp_register.c|return (ret);

@github-actions

github-actions Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

ABI diff vs v2026.10.8 (libabigail — authoritative)

Functions changes summary: 0 Removed, 0 Changed, 2 Added functions
Variables changes summary: 0 Removed, 0 Changed, 0 Added variable

2 Added functions:

  [A] 'function int __ham_fast_lock(DBC*, const DBT*, db_lockmode_t)'    {__ham_fast_lock}
  [A] 'function int __ham_get_meta_fast(DBC*, const DBT*, db_lockmode_t)'    {__ham_get_meta_fast}

---
_Advisory: libabigail/nm is the authoritative binary-ABI check; Coccinelle is complementary source-level early warning. See dist/cocci/README.md._

gburd added 10 commits October 23, 2026 12:41
…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 gburd changed the title rfc0017: HASH metapage lock scope (change 1) + quickselect rfc0017: HASH keyed ops without the metapage lock (change 1) + quickselect Oct 24, 2026
@gburd
gburd marked this pull request as ready for review October 24, 2026 03:42
@gburd gburd mentioned this pull request Oct 30, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant