Repository navigation
fix(semantic-cache): serialise index bucket writers under a cache-level lock - #41824
mikebridge wants to merge 6 commits into
Conversation
…el lock Addresses @rusackas's twice-flagged review finding on apache#40221: store_result performed a non-atomic read-modify-write on the index bucket, so two concurrent writers for one view could clobber each other's entries; the eviction prune in try_serve_from_cache had the same shape and could actively drop an entry added between its read and write. A Redis WATCH/Lua transaction can't be used here: the index value is a pickled Python list managed through the Flask-Caching abstraction, and the data cache is not guaranteed to be Redis-backed. Instead, a short-lived lock key acquired via cache.add (SET NX on Redis, add on memcached) serialises index writers per bucket, with a hard invariant: when the backend supports add(), the index is only written while holding the lock — on acquisition timeout the update is skipped (losing at most one write's future cache benefit) rather than performed unlocked, which could clobber a concurrent writer. Backends without add() degrade to the previous unlocked behavior. The new test choreographs the exact historical interleaving with events (no timing dependence): thread A parked inside its index read while thread B stores for the same view, then A resumes. Validated bidirectionally — without the fix it fails every run with B's entry clobbered by A's stale write; with the fix both entries survive (B blocks on the lock, releases A, then appends). Full semantic_layers suite: 374 passing.
|
Bito Automatic Review Skipped - Branch Excluded |
✅ Deploy Preview for superset-docs-preview ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## sl-cache #41824 +/- ##
============================================
- Coverage 63.43% 63.41% -0.03%
============================================
Files 2592 2591 -1
Lines 138780 138715 -65
Branches 32235 32229 -6
============================================
- Hits 88038 87968 -70
- Misses 49212 49226 +14
+ Partials 1530 1521 -9
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Multi-lens self-review (posting for transparency before anyone spends review time)We ran this PR through a six-lens parallel review panel (Python, committer, CD, clean-code, tidy-first, Amin-style scans) and verified every load-bearing claim against the pinned cachelib 0.13.0 source. Verdicts: 0 blockers, unanimous approve-with-changes — the invariant, skip-not-clobber choice, and deterministic test were endorsed by all six, but the panel found real hardening gaps. Findings below; a follow-up commit addressing them is queued. HIGH (all independently found by multiple lenses)
MEDIUM
LOW (condensed)Orphaned value blob when a store's index write is skipped (worth a comment; deleting is unsafe) · What the panel endorsed (unchanged in the follow-up): skip-on-timeout as "the correct half of the invariant" (writing unlocked on timeout would reintroduce the clobber exactly under contention); the harness releasing the parked thread from inside a failed 🤖 Generated with Claude Code |
Addresses every finding from the multi-lens review posted on the PR: 1. Read path stays lock-free on clean hits (6/6 lenses): the prune is gated on having actually observed an evicted value in the candidate loop, uses a single non-blocking lock attempt (it is opportunistic — a missed prune retries on the next read that observes the eviction), checks existence via cache.has() (Redis EXISTS; falls back to get() where has() is unavailable or unimplemented) instead of fetching full pickled payloads, and is isolated in its own try/except so housekeeping can never turn a computed cache hit into a miss. 2. Fenced release (6/6): the lock value is now an owner token; release deletes only on token match, so a holder that outlives the TTL cannot free a successor's lock. With has() collapsing the critical section, TTL expiry itself becomes implausible. 3. Abandoned-lock breaking (verified against cachelib 0.13.0): RedisCache.add is SETNX then a separate EXPIRE, so a holder killed between the two leaves a TTL-less lock that would freeze the bucket's index updates until changed_on rotates the key. The token embeds its acquisition timestamp; waiters break locks older than _INDEX_LOCK_STALE_FACTOR x TTL (with a warning). 4. Observability: a skipped store registration logs at warning with the index key (and a comment documents the orphaned-value-until-TTL trade-off); the docstring now scopes the invariant honestly to backends with atomic add and names the best-effort degradation on SimpleCache/NullCache. Tests — all mutation-validated (each fails under the exact mutation it guards): timeout-skip invariant (lock permanently busy with a fresh foreign token -> index never written unlocked); abandoned TTL-less lock is broken; prune-vs-store race (reader parked in its unlocked index read while a writer stores -> the locked re-read keeps the new entry while dropping the dead one). Harness hardened per review: module-level imports, typed events, harness_errors surfaced instead of being swallowed by production defensive excepts, and the retry budget patched up in-test for slow-CI headroom. Full semantic_layers suite: 377.
|
Follow-up pushed in
Full |
Round-2 review (six-lens panel, run via Claude)Re-ran the same six-lens review panel over the cumulative diff after the hardening commit, with an adversarial brief: verify the round-1 fixes hold and hunt for defects the new code introduced. Full disclosure: this is an AI-generated review (Claude), with every load-bearing claim verified against source or by execution. Round-1 findings: all resolved, 6/6 lenses — two verified empirically. One lens re-ran the suite in an isolated worktree (73/73, ruff clean); another ran the four concurrency tests 30/30 consecutive passes (0.42–0.80 s, no sleeps in the pass path) and confirmed all four fail fast against the base branch (0.73 s, no hangs) — genuinely pinning, CI-safe. New findings — all in the round-2 hardening code itself (each degrades to the pre-fix benign lost-entry, never wrong data; fixes queued as round 3):
CI note: the red pre-commit at HEAD is an infra flake (the "Enable brew and helm-docs" setup step died with "Broken pipe" before any hook ran) — will re-trigger. Verdicts: SHIP ×1, approve ×2, approve-with-nits ×2, polish-first ×1 · 0 blockers. |
Closes every finding from the round-2 six-lens review (posted on the PR):
1. Lock tokens are minted per acquisition attempt, so the embedded
timestamp reflects acquisition time — a token minted once before a
slow retry loop could be stale at birth, making the just-acquired
lock immediately breakable.
2. The stale-lock break is best-effort fenced (re-read and compare
before delete) and retries the add immediately within the same
iteration — so a single-attempt caller that breaks an orphan gets
its own acquisition instead of donating the break. Break logging
demoted to info (a waiter herd breaking one lock is not a fault).
The residual multi-breaker window is documented alongside the
release fence's, and the _update_index invariant docstring now
names both best-effort windows explicitly.
3. The prune performs ZERO backend calls inside the lock: the dead
value keys are exactly those the candidate loop already observed
missing, so the critical section is a constant get + membership
filter + set regardless of bucket size. _value_exists is removed
outright (nothing needs per-entry existence checks anymore).
Entries that never match a query linger until TTL/trim — an
accepted, documented trade for lock-free clean hits.
4. Staleness threshold raised (factor 2 -> 15, i.e. 30s): the
timestamp is compared across workers' wall clocks, and 4s was a
thin NTP tolerance for a correctness threshold — a waiter running
ahead would break every live lock it saw. The frozen-bucket event
this delays is the rarer one. math.isfinite guard added:
float("nan") parses and compares False against any threshold,
making a ":nan" lock value fresh forever — an unbreakable wedge.
5. Mutation-testing gaps closed with five new kill-tests, each
validated to fail under the exact mutation it guards: blind-delete
release (fence), breaker firing on a fresh foreign lock, lock add
without TTL, prune on clean hits (zero lock ops pinned), and the
nan/inf/boundary staleness edges.
6. Hygiene: superset-internal test imports hoisted to module top
(making the round-2 resolution claim accurate), skip-warning
wording corrected ("may be unreachable" — an earlier entry can
reference the same canonical value key).
Full semantic_layers suite: 388 passing.
|
Round 3 pushed in
Suite: 388 passing. CI is running fresh on this head (the previous red was an infra flake in the brew setup step, pre-hooks). |
Round 4, from an independent second-model review plus live-Redis validation of the whole protocol: 1. The prune now drops the EXACT entries observed dead (frozen-dataclass identity, timestamp included) instead of every entry sharing the value key. A concurrent store_result re-executing the same query re-registers the SAME canonical value key with a fresh entry and a live value; the key-based prune introduced in round 3 would have dropped that fresh registration. Zero-backend-calls-under-lock is preserved. Pinned by a deterministic choreography test (reader parked at the moment it observes the missing value; writer re-stores the same query; the fresh registration must survive) — fails under the key-based mutation. 2. The single-attempt stale-break retry is pinned: a one-attempt caller (the prune path) that breaks a TTL-less orphan must complete its own update in the same attempt, not donate the break — removing the in-iteration retry now fails a test. 3. The staleness boundary is pinned with frozen time (exactly-at- threshold is NOT stale; the > -> >= mutation now fails). 4. The _update_index docstring names the third best-effort window (plain TTL expiry if the locked get+set itself stalls past the TTL), alongside the fence and clock-skew windows. Live-Redis validation (real cachelib RedisCache, dev-stack Redis): 8 threads x 40 contended updates on one bucket -> 320/320 entries, zero losses, zero skips; a genuine TTL-less SETNX orphan broken and recovered; the release fence declining a foreign token; a fresh foreign lock skipped in <1 ms without being broken; the acquired lock carrying a real 2 s Redis TTL. Full semantic_layers suite: 390 passing.
|
Final validation round pushed in Independent second-model review (OpenAI Codex, adversarial) found one real race the panels missed — introduced by round 3's own optimization: the key-based prune could drop a freshly re-registered same-key entry (a concurrent Live-Redis validation (real
Suite: 390 passing — twelve dedicated lock-protocol/concurrency tests, every one validated to fail under the exact mutation or pre-fix code it guards. |
rusackas
left a comment
There was a problem hiding this comment.
Thanks @mikebridge, LGTM. Pulled the branch and ran it locally... 86/86 green, and the event-choreographed concurrency tests are deterministic rather than sleep-and-hope, which I appreciate.
For anyone puzzled by the failing CI: it's the 100% coverage gate on superset/semantic_layers/, which sl-cache already fails at the same 87 before this PR... cache.py actually goes up here (74% → 77%), so it's inherited, not introduced. Worth settling before the feature branch heads to master though. CC @betodealmeida
Review-panel finding on the sibling force-store PR (apache#41826): candidates were ranked by reuse mode only, and Python's stable sort preserves insertion order within a rank — so an OLDER stale broader entry that also satisfies the query (EXACT-with-leftovers) was served ahead of a just-forced fresh entry for the identical query. The forced refresh never stuck for readers. Tie-break by entry timestamp, freshest first. Pinned by a test with a deterministically older same-rank broader entry — fails under the rank-only sort.
…nches Three edges for the 100% coverage gate (the rest of the gap is closed by the sibling coverage PR into sl-cache): a lock that vanishes between the failed add and the staleness read (plain retry, not a stale-break); the fenced break declining when the lock changed hands between the staleness read and the re-read; and the degraded no-add path skipping the write when mutate returns None.
rusackas
left a comment
There was a problem hiding this comment.
Still LGTM. The freshest-first tie-break on same-rank candidates (from the #41826 review) is a real fix, and the choreographed test pins it well. The last few tests just fill in partial coverage branches, no new production code there.
|
Supersession note to prevent accidental merge: #42760 is the consolidated replacement under review and explicitly carries forward the still-valid work and attribution from this PR stack. This does not mean #42760 has been accepted for adoption yet; that decision remains pending. Please do not merge this stacked PR while the consolidation decision is open; a maintainer or PR owner can close it and reopen later if the direction changes. |
|
Closing: this was a contribution into #40221's Closed by Claude (AI) on behalf of @mikebridge. |
SUMMARY
Contribution into #40221's branch (
sl-cache), addressing @rusackas's twice-flagged review finding:store_resultperforms a non-atomic read-modify-write on the index bucket, so two concurrent writers for one view can clobber each other's entries. The eviction prune intry_serve_from_cachehas the same shape and can actively drop an entry added between its read and write.Why not WATCH/MULTI or Lua (the original suggestion): the index value is a pickled Python list managed through the Flask-Caching abstraction, and
data_cacheis not guaranteed to be Redis-backed. Lua can't merge pickled payloads, andWATCHrequires reaching into Redis-only client internals.The fix: a short-lived lock key acquired via
cache.add— the portable set-if-absent primitive (SETNXon Redis,addon memcached) — serialises index writers per bucket. The invariant, honestly scoped: on backends whereaddis atomic, the index is only written while holding the lock, with two narrow best-effort windows (the non-atomic get-compare-delete in the release/break fences, and cross-worker clock skew beyond the 30 s stale threshold), both bounded to the pre-fix benign lost-entry — never wrong data. On acquisition timeout (~500 ms of sleeps plus backend round-trips) the update is skipped — losing at most that write's future cache benefit — rather than performed unlocked, which could clobber a concurrent writer. Backends withoutadd()degrade to the previous behavior. Bothstore_resultand the prune path go through the same helper (_update_index), and the prune re-reads under the lock instead of writing back a stale list.Hardening from two review rounds (both panels' findings and resolutions are in the PR comments): the lock value is an owner token minted per acquisition attempt (release and stale-break are both fenced by compare-before-delete); locks orphaned without a TTL (cachelib
RedisCache.addis SETNX-then-EXPIRE, so a holder killed between the two leaves one) are broken after 15×TTL, withmath.isfiniteguarding against never-stale:nanvalues and the threshold sized for cross-worker clock skew; the eviction prune performs zero backend calls inside the lock (it prunes exactly the value keys the candidate loop observed missing) and clean cache hits take no lock at all; skipped registrations log at warning.TESTING INSTRUCTIONS
Nine dedicated tests, every one validated to fail under the exact mutation or pre-fix code it guards:
addcarries the TTL; clean cache hits perform zero lock operations; and the staleness parser's nan/inf/boundary edges.pytest tests/unit_tests/semantic_layers/ -q # 388 passedADDITIONAL INFORMATION
🤖 Generated with Claude Code