Skip to content

fix(hits): allow retry after failed ledger writes - #256

Merged
abogartz merged 2 commits into
abogartz:mainfrom
WhollyMindless:fix/210-ledger-retry
Nov 2, 2026
Merged

abogartz merged 2 commits into
abogartz:mainfrom
WhollyMindless:fix/210-ledger-retry

Conversation

@WhollyMindless

@WhollyMindless WhollyMindless commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #210.

A failed use-ledger write previously armed the one-hour success throttle, suppressing later retries even after the store recovered. The writer now tracks the next eligible attempt explicitly: successful writes wait one hour; failed attempts wait 60 seconds. Both windows are measured from the call's observation time. A separate in-flight reservation prevents overlapping identical calls from duplicating records; it is released in finally. Both successful and failed keys share the existing bounded-map eviction policy.

The short failure cooldown prevents repeated pull/recall calls for the same key from each paying the full lock timeout under sustained contention. The first eligible attempt can still wait for the existing lock budget; this is not a global latency limit across distinct keys. No automatic retries are scheduled.

resetHitThrottle now explicitly requires quiescence and throws if writes are pending. Clearing a reservation would neither cancel its I/O nor prevent its completion from modifying reset state. Tests must await their writes before resetting or changing stores.

Regression coverage includes in-process lock refusal, filesystem-lock refusal (pre-created lock file), append failure, cooldown boundaries and re-arming after another failure, concurrent duplicate suppression, normal success-throttle expiry, and reset during an active write. The filesystem-lock test counts actual timeout events rather than asserting machine-dependent elapsed times.

Validation (Bun 1.4.4)

  • Windows full bun run gate: typecheck and lint pass (498 advisory warnings); 853 unit tests pass / 26 skip / 0 fail; 30 E2E pass / 0 fail.
  • Focused Windows ledger suite: 18 pass / 0 fail.
  • Focused WSL Linux ledger suite: 17 pass / 1 skip / 0 fail (existing Windows-only rotation test skipped).
  • Backoff/reset regression checks against the previous implementation, with only the new exported constant available: 14 pass / 4 fail; fixed: 18 pass / 0 fail.
  • Initial PR validation also proved the two original retry tests fail on base bf7f6d2, and removing the in-flight guard produces 12 successful concurrent appends instead of 1.

Existing limitation: injection adopts its epoch even if telemetry fails and normally skips another ledger attempt until an epoch rebuild reaches noteHits; this change does not add injection retry scheduling. Pull and recall can make later attempts. Deduplication remains in-process, not cross-process exactly-once delivery.

Offered for your consideration under the claim on #210. Please feel free to defer or reject this PR if you prefer a different approach or priority.

@WhollyMindless

Copy link
Copy Markdown
Contributor Author

Verification report — reviewed by Qwen3.8-Flash-Next

Independent check of this PR's validation claims and diff, run on a scratch worktree of the PR head (fa0952a) on Windows, Bun 1.4.4. Posted on behalf of the review session; the reviewer cannot apply labels or reviews from a non-maintainer account, so this is a comment.

Validation claims — all reproduce

Claim on the PR body Independent result
Focused ledger tests green with the fix 16 pass / 0 fail ✓
New tests fail on base bf7f6d2 14 pass / 2 fail — exactly the two retry tests (a refused lock…, an append failure…), and only those ✓
Removing the in-flight guard breaks the concurrency test Confirmed by mutating src/hits/ledger.ts (guard's two lines removed): overlapping identical calls… fails; green again on restore ✓
Full unit suite 851 pass / 26 skip / 0 fail ✓
typecheck / lint pass / 498 warnings, 0 errors ✓

So all three new tests are load-bearing in the sense #68 asks for: two die without the fix, the third dies without the guard rather than merely without the lock. E2E was not re-run here (packed-artifact install; the diff touches nothing on that surface) — accepted on the body's report.

Code review

Correct. The check→reserve sequence (inFlight.has … inFlight.add) has no await between the two, so under single-threaded JS the reservation is atomic — moving lastWrite.set after the write opens no duplicate-eligibility window. finally guarantees the reservation cannot leak. The eviction relocation is safe because lastWrite now only grows on the success path.

Requested change (one line): resetHitThrottle() (src/hits/ledger.ts:67) clears lastWrite but not inFlight. Today every caller awaits, so nothing leaks — but a single un-awaited recordHits straddling a test boundary would suppress an identical call in the next test, which is the cross-test scope-leak class this repo already tracks (#146, #149). Since beforeEach treats resetHitThrottle() as full isolation, adding inFlight.clear() keeps the seam honest.

Question for the maintainer (design trade-off, not a defect): under sustained lock contention, every later call now retries with the full 5s DEFAULT_TIMEOUT_MS budget — noteHits is awaited on the inject/recall paths (src/index.ts:409), so a stuck lock turns each read into a 5s telemetry stall where the old code paid it at most once per hour per key. #210 asked for retry-always, so shipping as-is is defensible; an optional lastFailure backoff (~30–60s) would preserve retry-ability without a stall-per-call. Leaving that call to be made explicitly rather than silently.

Nit: the comment at src/hits/ledger.ts:130 ("…without evicting reservations for pending I/O") describes a hazard that doesn't exist — reservations live in inFlight, never in lastWrite. "Only successful writes insert; same cap as before" says the true thing.

Test notes

  • The LOCK_WRITE.timeoutMs/onEvent mutation follows the established house pattern (lock-write-timeout.test.ts et al.), restored in finally.
  • The entered/released handshake avoids fixed sleeps, which addresses this repo's documented flake history.
  • The directory-as-ledger-file trick for post-lock I/O failure is platform-agnostic: any throw lands in the fail-soft path.

Net: mergeable as-is. The one-line resetHitThrottle() addition is the only thing I'd ask for before merge; the backoff question and the comment nit can follow up or be waved.

Reviewed by Qwen3.8-Flash-Next (verification run: Windows, Bun 1.4.4, PR head fa0952a, base bf7f6d2).

@WhollyMindless

Copy link
Copy Markdown
Contributor Author

Review of head fa0952a

The fix is correct and does what #210 asks, but I'd add a short failure backoff before merge. After the lock is released, the retry now succeeds, where on base it stayed blocked. The catch is that repeated failures now cost much more. That case is narrow, and the fix is about three lines.

I ran a throwaway timing probe on base bf7f6d2 and on this head (Windows, Bun 1.4.4). I did not re-run the test suite.

1. Medium: each failed write now stalls the read that triggered it

recordHits is awaited on every grep, glob and read that pulls memories (src/index.ts:471), and on memory_recall (src/tools/recall.ts:68). The old throttle, by accident, limited the failure cost to once per key per hour. Now every call pays it.

Four identical calls while the lock was held:

Scenario Base This head
Live holder: total time 5.2 s (5 s, then 0, 0, 0) 20.3 s (5 s each)
Live holder: store_lock evidence lines 1 4
Retry once the holder is gone (#210) false true
Dead holder: total time 5.0 s, nothing written 10.0 s, write succeeds on call 2
  • How narrow it is: the probe's live holder kept refreshing the lock file's timestamp, which real holders don't do. A dead lock is stolen after 10 s, so that case costs about two stalled calls. It only keeps going with a continuous chain of live holders or a lock file that can't be removed.

  • Same cause, from reading the code (not run): on Windows, a rotation blocked by a reader handle re-reads the 2 MB file and retries the rename for 2 s while holding the lock, now on each call.

  • Suggested fix: in the catch, reuse the existing map so the throttle expires soon:

    lastWrite.set(key, now - THROTTLE_MS + RETRY_BACKOFF_MS); // e.g. 60s

    The size cap then has to run on this path too, and the two retry tests need to advance time past the backoff. Use ledger: allow retry after a failed write without an hour-long throttle #210 asks to "keep retry available", which a backoff still satisfies.

2. Low: the inject source doesn't get the retry

src/inject/epochs.ts:223 ignores whether the write succeeded and adopts the epoch anyway. Later turns then exit early at line 183, so nothing retries until the store changes. Base has the same limit, so this isn't a regression, but only pull and recall really retry. One sentence in the PR body would cover it. Confirmed by reading the code, not by running it.

3. Low: resetHitThrottle doesn't fully reset

In the probe, a call made while an identical write was pending was refused. When that write finished, it re-armed the throttle after the reset. The inFlight.clear() suggested in the earlier comment fixes the refusal only: the pending write still re-arms the throttle, and its finally could remove a newer reservation. This only matters for test isolation, so the one-liner is fine.

4. Low: the refused-lock test never reaches the lock file

The holder is in the same process, so the timeout comes from the in-process queue (src/store/lock.ts:247). This is a coverage gap, not a bug: the probe did go through the file path on this head, and it behaved correctly. A pre-created .lock file would cover it.

Nit: the comment "without evicting reservations for pending I/O" describes a hazard that doesn't exist, as the earlier comment also says.

Reviewed by Claude (timing probe: Windows, Bun 1.4.4, PR head fa0952a, base bf7f6d2).

@WhollyMindless

Copy link
Copy Markdown
Contributor Author

Addressed in 59e6744:

  • Added a 60-second per-key failure cooldown (from the attempt's observation time), retaining the one-hour success throttle. Explicit next-attempt deadlines avoid storing fictitious successful-write timestamps. Both outcomes use the same bounded-map eviction path.
  • Added the real filesystem-lock refusal test. Repeated calls inside the cooldown emit no additional timeout event; expiry admits another attempt, another failure re-arms the cooldown, and a released lock can be retried at the next expiry. Existing append-failure and in-process-lock tests now pin the short backoff boundary.
  • Did not add inFlight.clear(): reset now refuses pending writers with an actionable error. A test verifies the live reservation stays protective and reset works after completion. This makes the fixture-lifetime requirement explicit rather than pretending to cancel asynchronous I/O.
  • Updated the eviction wording and documented the existing injection/epoch limitation in the PR body. No injection retry machinery added.

Validation: Windows full gate green (853 pass / 26 skip unit tests; 30/30 E2E; typecheck/lint pass), focused Windows 18/18 and WSL Linux 17 pass / 1 platform skip. The revised tests fail four assertions on the prior implementation with the new constant available, and pass with the fix.

The first eligible attempt still has the existing lock wait; cooldown protection is per key and bounded by map eviction. This addresses repeated same-key stalls without claiming all telemetry latency is removed. Please feel free to reject or adjust the 60-second policy if you prefer another trade-off.

@WhollyMindless

Copy link
Copy Markdown
Contributor Author

Re-verification of head 59e6744 — reviewed by Qwen3.8-Flash-Next

Follow-up to my earlier report on fa0952a. The head moved after that review; I re-ran the checks on the new head in the same scratch worktree (Windows, Bun 1.4.4). Non-maintainer, so this stays a comment.

Validation claims in the 59e6744 reply — all reproduce

Claim Independent result
Focused ledger tests 18/18 on Windows 18 pass / 0 fail ✓
Full unit suite 853 pass / 26 skip 853 pass / 26 skip / 0 fail ✓
(CI: lint / test / test-windows / smoke) all green on this head ✓

E2E was not re-run here; accepted from CI and the body's 30/30.

The delta (fa0952a → 59e6744), read as a review

The lastWrite map becoming a nextAttempt deadline map is the right shape — it closes the stall the timing probe measured (4 failed calls ≈ 20s → now one wait plus 60s cooldown per key) without storing fictitious success timestamps, and it preserves the old success semantics exactly: the boundary at now == eligibleAt admits the attempt, same as now - prev == THROTTLE_MS did. Eviction in the finally covers both outcomes with the same 2000-cap. nextAttempt.set and inFlight.delete are adjacent synchronous statements, so no eligibility window opens during release. Cooldown measured from the attempt's observation time is documented, deterministic for tests, and honestly annotated.

resetHitThrottle() throwing on pending writers: confirmed test-seam-only — git grep finds no production call site in src/. And a correction to my earlier report: the 59e6744 reply is right that the inFlight.clear() I requested was a half-fix. Clearing cannot cancel the pending write, which would then re-arm nextAttempt after the reset — Refusing loudly makes the fixture-lifetime requirement real where clear() would have papered over it. Withdrawn in favor of what shipped.

State of my original three findings: the stall question is resolved by the shipped cooldown; the reset-isolation request is resolved better than proposed; the comment nit is fixed. No open asks from me. The 60-second constant is sensibly left to the maintainer to adjust — its only contract, per the tests, is "short compared to the hour, long compared to a lock budget," which 60s satisfies.

Net: LGTM at 59e6744 from my side — mergeable as far as verification goes, pending whatever the maintainer wants from the review queue.

Reviewed by Qwen3.8-Flash-Next (re-verification run: Windows, Bun 1.4.4, PR head 59e6744, base bf7f6d2).

@WhollyMindless

Copy link
Copy Markdown
Contributor Author

Re-review of head 59e6744

I'd merge this. All four findings from my earlier review are dealt with, the stall is gone, and the new tests fail when the code is broken. I have no blocking requests, only two optional small items below.

Earlier findings

Finding Status How
1. Each failed write stalls the read Fixed A 60-second cooldown per key, confirmed by re-running the probe
2. Inject doesn't get the retry Disclosed The PR body now states the limit; inject still doesn't retry, which is reasonable
3. resetHitThrottle doesn't fully reset Fixed, better than my suggestion Reset now throws if a write is pending, which avoids the problems inFlight.clear() had
4. Refused-lock test skips the lock file Fixed New test uses a pre-created lock file

Moving to nextAttempt is also cleaner than the now - THROTTLE_MS + RETRY_BACKOFF_MS trick I suggested, since it doesn't store a fake timestamp.

What I ran

Four identical calls while the lock was held (the live holder is simulated the same way as in the earlier probe):

Scenario Base fa0952a 59e6744
Live holder: total time 5.2 s 20.3 s 5.2 s
Live holder: store_lock lines 1 4 1
Dead holder: total time 5.0 s 10.0 s 5.0 s
  • Retry after the holder is gone: refused at 59.999 s and succeeds at 60 s, as designed. On base the same retry stays blocked for an hour.
  • Different keys still stall: three different keys cost about 5 s each. The first attempt for each key has always paid that, and the PR body says so.
  • Full unit suite (Windows): 853 pass, 26 skip, 0 fail, matching the PR's numbers. Typecheck printed no errors.
  • Flake check: the three test files that call reset ran 20 times each, 680 pass and 0 fail. That matters because reset can now throw.
  • Not run: E2E and Linux locally. For those I'm relying on CI, which is green on this head, and the PR's reported numbers.

Mutations against test/hits.test.ts: 7 of 9 were caught.

  • Caught: a zero failure cooldown, a one-hour failure cooldown (the original bug), a 60-second success cooldown, no in-flight guard, a reservation that's never released, reset not throwing, and reset not clearing.
  • Survived: removing the eviction cap, and evicting only one key at a time. The cap's logic is unchanged and only moved, so this looks like an old gap, though I didn't test base. I also ran these two only against test/hits.test.ts, not the whole suite.

Optional small items

  1. A useful comment was dropped. The old comment explained why the throttle exists: the epoch block rides every request, so one offer would otherwise be counted dozens of times. The new one covers only the timing. One restored sentence would keep that reason.
  2. One test title is now slightly off. "a refused lock does not throttle the retry after the holder releases" now does wait 60 seconds, as the test itself asserts. Something like "…only for the short cooldown" would be accurate.

One side effect to be aware of: if a test ever abandons a pending write, for example by timing out, later resets will throw and one failure could spread to other tests. The PR says this is deliberate, I think it's the right trade, and nothing triggered it in these runs.

Reviewed by Claude (Opus 5.5; timing probe, full unit suite and mutation checks: Windows, Bun 1.4.4, PR head 59e6744, base bf7f6d2).

@abogartz abogartz added the review:requested Human-admitted for autonomous review by ocsi-reviewer label Nov 2, 2026

@ocsi-reviewer ocsi-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

APPROVE — head 59e67445412fb88e5870c6dcf17bab2491c2d460, merge-base bf7f6d2.

Contract (#210, authored by WhollyMindless — trusted human): "Keep retry available after a refused ledger write while preserving deduplication for simultaneous calls. Test failure followed by successful retry and concurrent identical calls. Retrieval must remain available even when telemetry fails."

Per-criterion evidence

  1. Retry available after refused write — differential at merge-base with the issue's exact repro (lock held, LOCK_WRITE.timeoutMs=30, recordHits('recall','sid-1',[row]), release, retry at observation+61s): head → {"first":false,"second":true} exit 0; base → {"first":false,"second":false} exit 1, failing for the stated reason (1h throttle armed before the write). Fixed path: nextAttempt set only in finally, failure cooldown RETRY_BACKOFF_MS (src/hits/ledger.ts:61,133,141).
  2. Deduplication for simultaneous calls — inFlight guard checked and added synchronously before any await (src/hits/ledger.ts:111,122), released in finally (:146). Test "overlapping identical calls persist one use" (test/hits.test.ts:205): 12 concurrent recordHits → exactly 1 true, ledger count 1. Green.
  3. Failure-then-success tested — three tests: filesystem-lock refusal backs off then permits another attempt (test/hits.test.ts:105), in-process lock refusal then retry at RETRY_BACKOFF_MS boundary (:150), append failure fail-soft then retry once writable (:185). Boundary asserted exactly: t0+RETRY_BACKOFF_MS-1 false, t0+RETRY_BACKOFF_MS true.
  4. Retrieval available when telemetry fails — catch returns false, never throws (src/hits/ledger.ts:135-140); append-failure test asserts false with no throw and one line after recovery.

Commands run (macOS, Bun 1.4.4)

  • bun run typecheck — 0 errors
  • bun run lint — 498 warnings = baseline
  • bun run test — 865 pass / 14 skip / 0 fail
  • bun run test:e2e — 30 pass / 0 fail
  • CI gh pr checks — lint / test / test-windows / smoke all pass

Test-integrity check — no assertion deleted, no .skip, no tolerance widened: the diff to test/hits.test.ts is purely additive (5 new tests) plus imports; the pre-existing throttle tests remain.

Findings — no P0/P1. Nit: resetHitThrottle now throws on pending writes (src/hits/ledger.ts:70); safe today (test-only callers, full suite green) and the docstring states the contract — future tests must await their writes.

Author's issue-thread claim "the new tests fail when the code is broken" is corroborated by the merge-base differential above. Human merges.

@abogartz
abogartz merged commit c67d237 into abogartz:main Nov 2, 2026
4 checks passed
@abogartz-opencode-self-improvement

Copy link
Copy Markdown

🎉 This PR is included in version 0.15.8 🎉

The release is available on:

Your semantic-release bot 📦🚀

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

Labels

released review:requested Human-admitted for autonomous review by ocsi-reviewer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Use ledger: allow retry after a failed write without an hour-long throttle

2 participants