Repository navigation
fix(hits): allow retry after failed ledger writes - #256
Conversation
Verification report — reviewed by Qwen3.8-Flash-NextIndependent check of this PR's validation claims and diff, run on a scratch worktree of the PR head ( Validation claims — all reproduce
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 reviewCorrect. The check→reserve sequence ( Requested change (one line): Question for the maintainer (design trade-off, not a defect): under sustained lock contention, every later call now retries with the full 5s 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 Test notes
Net: mergeable as-is. The one-line Reviewed by Qwen3.8-Flash-Next (verification run: Windows, Bun 1.4.4, PR head |
Review of head
|
| 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).
|
Addressed in 59e6744:
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. |
Re-verification of head
|
| 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).
Re-review of head
|
| 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
- 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.
- 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).
There was a problem hiding this comment.
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
- 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:nextAttemptset only infinally, failure cooldownRETRY_BACKOFF_MS(src/hits/ledger.ts:61,133,141). - Deduplication for simultaneous calls —
inFlightguard checked and added synchronously before any await (src/hits/ledger.ts:111,122), released infinally(:146). Test "overlapping identical calls persist one use" (test/hits.test.ts:205): 12 concurrentrecordHits→ exactly 1true, ledger count 1. Green. - 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_MSboundary (:150), append failure fail-soft then retry once writable (:185). Boundary asserted exactly:t0+RETRY_BACKOFF_MS-1false,t0+RETRY_BACKOFF_MStrue. - Retrieval available when telemetry fails —
catchreturnsfalse, never throws (src/hits/ledger.ts:135-140); append-failure test assertsfalsewith no throw and one line after recovery.
Commands run (macOS, Bun 1.4.4)
bun run typecheck— 0 errorsbun run lint— 498 warnings = baselinebun run test— 865 pass / 14 skip / 0 failbun 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.
|
🎉 This PR is included in version 0.15.8 🎉 The release is available on: Your semantic-release bot 📦🚀 |
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.
resetHitThrottlenow 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)
bun run gate: typecheck and lint pass (498 advisory warnings); 853 unit tests pass / 26 skip / 0 fail; 30 E2E pass / 0 fail.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.