Skip to content

fix(lock): atomic heartbeat rewrite ends the #904 torn-read flake - #1196

Merged
iamtoruk merged 1 commit into
mainfrom
fix/atomic-heartbeat-rewrite
Aug 30, 2026
Merged

fix(lock): atomic heartbeat rewrite ends the #904 torn-read flake#1196
iamtoruk merged 1 commit into
mainfrom
fix/atomic-heartbeat-rewrite

Conversation

@iamtoruk

Copy link
Copy Markdown
Member

The cache-refresh lock heartbeat rewrote the lock file in place (truncate then write), exposing every concurrent reader to an empty or partial JSON body. observe() papers over the window with stat-bracketed retries, but plain readers race it — that is the Unexpected end of JSON input flake that hit main and two PR runs today (#904 family).

Fix: the heartbeat writes the next body beside the lock and rename()s over it. POSIX rename is atomic and Node maps it to a replacing move on Windows, so a reader sees the old body or the new body, never a torn one. A refused replace (Windows busy handle) skips the tick and cleans its temp file; staleness is nine heartbeats wide, so a skipped tick is absorbed. observe() keeps its tolerance for the exclusive-create window and for older versions that still rewrite in place against the same cache dir.

Evidence:

  • New regression test (400 plain reads against a 1ms heartbeat): fails 5/5 runs on the old code, passes with the fix.
  • Serial lock suite (npm run test:locks): 10/10 consecutive green runs (36 tests each).
  • Full suite: 3,895 passed, 0 failed. tsc and npm run build clean.

Remaining #904 family member (the takeover-window completed-by-other misclassification in the process test) is a different race and stays tracked there.

…ncating in place

The heartbeat rewrote session-refresh.lock with a plain writeFile,
which truncates before it writes, so any reader could observe an empty
or partial body for the width of the write. observe() tolerated that
window with retries, but every plain reader (the lock tests included)
raced it, which is the JSON parse flake behind #904.

The rewrite now lands next to the lock and renames over it, so a
reader sees the previous body or the next one, never a torn one. A
refused replace on Windows skips the tick, which staleness absorbs at
nine heartbeats per staleMs. observe() keeps its tolerance because
older codeburn versions sharing the cache dir still rewrite in place.

The new regression test hammers plain reads against a 1ms heartbeat:
it failed 5 of 5 runs against the old rewrite and passes 10 of 10
serial lock-suite runs with this change.
@iamtoruk
iamtoruk merged commit 6a3fa2d into main Aug 30, 2026
16 checks passed
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