Repository navigation
Isolate concurrent store probes - #9
Conversation
|
OpenRouter review posted ( |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
OpenRouter pull-request review
Verdict: issues
Scope: full-pr (full-pr)
Mode: initial
Commit: a1d992dc05652830387de8339d266b1b782c7444
Judge: openai/gpt-5.6-luna (repaired(canonical+1): source coverage preserved before publication cap)
Cost: $0.1514 (lanes $0.1447 + judge $0.0067)
Lanes
meta/muse-spark-1.2: ok (9 finding(s), 49.2s, 90065+7749 tokens (36405 cached), 5 tool round(s), via Meta, $0.11)z-ai/glm-5.3-flash: ok (6 finding(s), 276.3s, 261415+46665 tokens (193920 cached), 7 tool round(s), via Crusoe, $0.0393)
Warning
meta/muse-spark-1.2: coverage claims 6 finding(s) in 'packages/health/src/index.ts' but 7 were reported
Findings
🔴 Issue 1 — Construction crashes if globalThis.crypto is unavailable
packages/health/src/index.ts:152 · bug · identified by meta/muse-spark-1.2
Concrete failure: createStorePingCheck throws synchronously when globalThis.crypto.randomUUID is missing (Node <19, edge runtimes without Web Crypto, or Vitest/jsdom without polyfill) — the host's composition root fails to start and the health endpoint is never mounted.
Evidence: packages/health/src/index.ts:152 does globalThis.crypto.randomUUID() unconditionally with no existence check or node:crypto fallback. Previous code had a static string "ping" and never touched crypto.
Mechanism: accessed at construction time, so every createStorePingCheck({store,collection}) without explicit id evaluates the expression immediately; there is no try/catch to produce a degradable id.
Checked: grep randomUUID finds only this site; package.json engines >=22 guarantee Node has globalThis.crypto on native, but hosts can still run in non-Node or test environments and the package has no runtime guard. No fallback was found.
🔴 Issue 2 — Stuck previous write starves all future probes
packages/health/src/index.ts:164 · bug · identified by meta/muse-spark-1.2
Concrete failure: if a put never settles and its caller's withTimeout fires, previousWriteSettled remains the never-settling promise. Every subsequent run() first does await withTimeout(previousWriteSettled, timeoutMs) (index.ts:164) and therefore times out with store_ping_timeout without ever issuing a new put. Even after the backend recovers, health stays fail until the original stuck promise finally settles (which may be never).
Evidence: previousWriteSettled = write.then(()=>undefined,()=>undefined) at index.ts:168-171 is only replaced when a new write is started; but a new write is only started after await withTimeout(previousWriteSettled,…) succeeds. The catch block at index.ts:181-196 returns store_ping_timeout but never resets previousWriteSettled.
Checked: test waits for a timed-out write before starting the next probe (index.test.ts:224) only covers the case where the old write eventually resolves; no test covers never-settling previous write starvation.
🟠 Issue 3 — Per-instance random probe id causes unbounded row growth
packages/health/src/index.ts:152 · risk · identified by meta/muse-spark-1.2
Concrete failure: every createStorePingCheck() without explicit id now creates a fresh row ping-<uuid> and never deletes it. A host that accidentally constructs the check per request, or a fleet of short-lived workers that restart frequently, accumulates one record per construction forever in health_probes / __health__ with no TTL or GC — metered storage fills and list/scan costs grow linearly.
Evidence: DEFAULT_PROBE_ID_PREFIX="ping-" + randomUUID() at packages/health/src/index.ts:60,152. Docs acknowledge the leak (docs/MONITORING.md:60-62 and packages/health/README.md:45-47) but give no retention or cleanup guidance; the old default was a single stable ping row that was overwritten.
Checked: store mock in tests shows list("__health__") growing; no TTL field on HealthProbeRecord and no cleanup code exists.
🟠 Issue 4 — A write that never settles wedges every later probe on the check instance
packages/health/src/index.ts:164 · risk · identified by z-ai/glm-5.3-flash
Concrete failure: probe A's probes.put(record) hangs indefinitely (the exact failure mode withTimeout exists for). A returns store_ping_timeout after 5s, but previousWriteSettled now points at that still-pending write promise. The store then recovers. Probe B waits up to timeoutMs for A's zombie write, times out at line 164, and jumps to catch — it never issues its own write, so previousWriteSettled is never re-pointed. Every subsequent probe repeats the same 5s wait-and-fail loop, so the health endpoint returns 503 (and burns timeoutMs per scrape, long enough that monitors may record HTTP timeouts instead of 503s) until the zombie promise happens to settle or the process restarts. Under the pre-PR code, the next probe simply started a fresh write and recovered as soon as the store did; one hung request now degrades into a permanent false failure with no un-wedge path other than the zombie's own settlement.
Mechanism: previousWriteSettled is only reassigned at lines 167–171, which are reachable only after the await withTimeout(previousWriteSettled, timeoutMs) at line 164 succeeds; there is no reset, and the check passes no abort signal to the store, so nothing else ends a never-settling write. Also note that when the wait times out the probe reports store_ping_timeout although it never touched the store in that attempt, which muddies the enumerated-reason contract for log monitors.
Checked: full runProbe body (only reassignment site is inside the try after the wait), all tests in packages/health/src/index.test.ts (no test drives the wait-timeout path — see the missing-test finding), and withTimeout (it only races, never cancels the underlying promise). Counterpoint I could not rule out: adapters whose SDK promise always eventually settles bound the outage to that settlement time, but the package's own timeout exists precisely because promises may never settle.
🟠 Issue 5 — Effective probe deadline can reach ~3× timeoutMs
packages/health/src/index.ts:164 · risk · identified by meta/muse-spark-1.2
Concrete failure: a caller configuring timeoutMs: 5000 expects failure within ~5s, but runProbe sequentially awaits previousWriteSettled (timeoutMs) + put (timeoutMs) + get (timeoutMs) (index.ts:164,172,173). If a previous write is slow-but-settling, total wall time can be ~15s before latencyMs is returned, violating host SLOs and monitor timeouts.
Evidence: each phase uses independent withTimeout(..., timeoutMs) rather than a shared deadline from started. Date.now() at index.ts:160 measures total elapsed, not remaining budget.
Checked: no shared deadline or AbortSignal was introduced; docs state createStorePingCheck bounds its own I/O the way hosts should, implying a single timeout budget.
🟠 Issue 6 — Breaking change: default probe row id changed from stable "ping"
packages/health/src/index.ts:60 · risk · identified by meta/muse-spark-1.2
Concrete failure: existing dashboards, Synthetic checks, or janitor jobs that query health_probes with {partition:"__health__", id:"ping"} stop finding rows after upgrade; a host reading the probe row to prove liveness gets null / round_trip_mismatch until it updates queries, and old ping rows become orphaned.
Evidence: DEFAULT_PROBE_ID → DEFAULT_PROBE_ID_PREFIX change at index.ts:60; old value was exactly "ping", new is ping-<uuid v4> per instance. Tests updated index.test.ts:81-90 to assert regex instead of exact equality. No migration note or changelog entry exists at this commit; version in packages/health/package.json bumped to 0.2.0 but docs do not call out the incompatibility.
Checked: grep for healthProbe usage finds no code-map, but docs/MONITORING.md adds new isolation prose without a "breaking change" callout.
🟠 Issue 7 — Default per-instance probe id turns the health collection into unbounded growth with no cleanup
packages/health/src/index.ts:152 · risk · identified by z-ai/glm-5.3-flash
Concrete failure: the default id changed from the stable "ping" (one row per partition, overwritten forever) to ping-<uuid> generated once per check construction. Any deployment that constructs the check at module scope and restarts or recycles processes now orphans one row per process lifetime, forever: a long-lived host redeployed daily leaves a permanently stale row per deploy, and the documented primary consumer (the pegma.dev Worker, named in docs/PROJECT_PLAN.md) constructs per isolate, and Worker isolates churn constantly — so health_probes accumulates rows without bound on the metered backend that docs/securityscan.md SEC-004 already flags for cost amplification. Stale rows also poison any future "probedAt is fresh" assertion made against the collection. The package owns no deletion/TTL path (index.ts never deletes), and the new docs do not close the gap: docs/MONITORING.md covers per-request construction and "short-lived runtimes", but not the restart/redeploy/isolate-recycle case, and packages/health/README.md frames the stable id as optional ("when a deployment needs to reuse the same row").
Secondary consequence of the same change: hosts upgrading from the published 0.1.x line keep a ping row that is never written or deleted again; any external tooling reading that row sees a frozen timestamp and can false-alarm. Nothing in-repo reads the old id (grepped for "ping"/ping- repo-wide), so this is limited to out-of-repo consumers, but it deserves a migration note.
Checked: packages/health/src/index.ts (no cleanup code), both doc files' new paragraphs as quoted above, repo-wide grep for the old id, and docs/PROJECT_PLAN.md for the named consumers. Proof gap: I cannot see the hosts' own repos to confirm they do not already pass an id, so the exposure is the default path only.
🔵 Issue 8 — Coalesced concurrent callers share stale latencyMs
packages/health/src/index.ts:206 · nit · identified by meta/muse-spark-1.2
Concrete failure: concurrent check.run() calls return the same Promise<CheckResult> (index.ts:206-214). The second caller that arrived after started=Date.now() gets the first caller's latencyMs, which undercounts its own queuing time (or overcounts if it would have been faster). Monitors aggregating latencyMs get misleading p50/p95 values.
Evidence: inFlight stores and reuses attempt without per-caller timing. Test coalesces concurrent calls on one check instance (index.test.ts:113) asserts expect(second).toBe(first) intentionally, so shared latency is by design but undocumented.
Checked: no separate started per caller; documented as "share the same in-flight round trip" but latency semantics are not clarified.
🔵 Issue 9 — Silent swallow of previous write rejection hides root cause
packages/health/src/index.ts:168 · nit · identified by meta/muse-spark-1.2
Concrete failure: previousWriteSettled = write.then(()=>undefined,()=>undefined) (index.ts:168-171) discards the rejection reason. If a write rejects with a transient credential/permission error, the error is never logged (only the eventual store_ping_failed of the probe that observed it), making incident triage harder.
Evidence: catch at index.ts:181-196 logs nothing for createStorePingCheck failures; only runHealthChecks' health.check_threw logs arbitrary checks. Previous write failures are observable only as store_ping_timeout on the next probe that waited for the swallowed promise.
Checked: grep for logger in index.ts shows logging only in runHealthChecks/runCheck, not in createStorePingCheck.
🔵 Issue 10 — Flaky 5 ms timeout in tests and racy isolation test
packages/health/src/index.test.ts:240 · nit · identified by meta/muse-spark-1.2
Concrete failure: tests use timeoutMs: 5 with setTimeout-based withTimeout (index.test.ts:240,313). On overloaded CI, 5 ms can fire before the artificially deferred put is registered, or the isolation test (index.test.ts:149) depends on putCalls ===1 awaiting firstWrite while second write races — flakes as Promise microtask ordering varies.
Evidence: waits for a timed-out write... asserts expect(putCalls).toBe(1) after a single await Promise.resolve(), assuming the second probe has not yet reached its put. The isolation test resolves ordering via firstWrite deferred that is only resolved by the second put, which deadlocks if second put never starts due to previous starvation logic.
Checked: vitest default timeout not increased; no vi.useFakeTimers used to make timing deterministic.
🔵 Issue 11 — Docs advise replica-specific id without collision guidance or cleanup
docs/MONITORING.md:57 · nit · identified by meta/muse-spark-1.2
Concrete failure: docs/MONITORING.md:57-62 tells short-lived runtimes to "pass a stable, replica-specific id and keep that id distinct from other live replicas" but gives no mechanism to ensure uniqueness across restarts or guidance on expiring dead replica rows, so two concurrent Cloudflare Workers or Azure instances that accidentally share id:"replica-1" will again overwrite each other's probedAt and cause flapping round_trip_mismatch failures.
Evidence: same wording duplicated in packages/health/README.md:43-47. HealthProbeRecord has no lease/expiry field, so dead rows accumulate indefinitely as noted above.
Checked: no example showing how to derive id (hostname, pod name, etc.) and no warning about reuse across concurrent live replicas.
🔵 Issue 12 — README and MONITORING still claim the check "writes and reads on every call", now false under coalescing
packages/health/README.md:43 · nit · identified by z-ai/glm-5.3-flash
Concrete failure: a reader reconciling the security guidance with the new behavior gets contradictory statements in the same documents. packages/health/README.md line 43 says "createStorePingCheck writes and reads on every call" and docs/MONITORING.md line 50 says it "performs a real write plus a read on every call — that is the point, a connectivity ping would lie" — yet this PR adds coalescing (and says so in the very next paragraph it edits in both files): concurrent calls share one round trip and issue no write of their own. The rate-limiting advice still holds, but the stated invariant is now inaccurate for exactly the concurrency case this PR introduces, and the PR edited the adjacent paragraphs without reconciling the older claim.
Checked: full text of both files at the head commit; the coalescing implementation in run()/runProbe().
🔵 Issue 13 — docs/securityscan.md line anchors for createStorePingCheck no longer point at the referenced code
docs/securityscan.md:16 · nit · identified by z-ai/glm-5.3-flash
Concrete failure: an auditor verifying SEC-001's remediation opens packages/health/src/index.ts at the cited "lines 172–181 (createStorePingCheck → catch block)" and lands on the new record/previousWriteSettled assignment block instead of the catch block (now around lines 185–199); SEC-004's "lines 154–171" anchor (line 114 of the doc) now points at construction options and the wait rather than the put/get round trip, because this PR inserts ~30 lines above and inside the function. The file is dated, but it is the repo's standing security record, and its evidence anchors are now silently wrong.
Checked: line positions of createStorePingCheck, its catch block, and the put/get body in the head version of packages/health/src/index.ts against both citations in docs/securityscan.md.
🔵 Issue 14 — No test covers the new wait-timeout branch that fails a probe without touching the store
packages/health/src/index.test.ts · nit · identified by z-ai/glm-5.3-flash
Concrete failure: the new first statement of runProbe (await withTimeout(previousWriteSettled, timeoutMs)) introduces a failure mode where a probe returns fail/store_ping_timeout having issued no write at all, and where previousWriteSettled is consequently never advanced (the wedge path in the risk finding above). No test pins this: the "waits for a timed-out write before starting the next probe" test resolves the stale write in time, and "reports a timeout as its own enumerated reason" exercises the write's own timeout, not the wait's. A regression that reorders the wait, drops the sequencing, or fails the probe during the wait would only be caught by accident.
Checked: all createStorePingCheck tests in the file; none leaves previousWriteSettled pending long enough to hit the wait's timeout, and none asserts putCalls stays at 0 for a failed wait.
🔵 Issue 15 — expect(records).toHaveLength(2) assumes vitest toHaveLength supports Map.size
packages/health/src/index.test.ts:194 · nit · identified by z-ai/glm-5.3-flash
Concrete failure: the new "isolates separate check instances sharing one store" test asserts expect(records).toHaveLength(2) on a Map, whose length is exposed via size, not length. If vitest 4.1.10's toHaveLength (as opposed to Jest's, which requires a numeric length) does not consult .size, the matcher throws a TypeError and this test fails CI on Node 22/24.
Checked: package.json and pnpm-lock.yaml pin vitest/@vitest/expect at 4.1.10; no other test in the repo uses toHaveLength on a non-array. Proof gap: node_modules is absent from the review checkout, so I could not read @vitest/expect's matcher source to confirm .size support; my recollection is that vitest does support Map/Set via size, so this may be a false alarm — the gate run will settle it either way, and expect(records.size).toBe(2) is the unambiguous form.
There was a problem hiding this comment.
OpenRouter pull-request review
Verdict: issues
Scope: latest-commit (commit-range)
Mode: verify
Commit: a5f9b51069adab2106ccb9b62306ac844b1ad439
Judge: openai/gpt-5.6-luna
Cost: $0.1177 (lanes $0.1167 + judge $0.0010)
Lanes
meta/muse-spark-1.2: ok (0 finding(s), 32.1s, 65734+4788 tokens (9442 cached), 3 tool round(s), via Meta, $0.0921)z-ai/glm-5.3-flash: ok (1 finding(s), 353.9s, 370887+25744 tokens (247040 cached), 12 tool round(s), via StreamLake, $0.0245)
Round 2 resolution
- ✅
r1-1fixed correctly — Construction crashes if globalThis.crypto is unavailable: Construction no longer crashes:packages/health/src/index.ts:143-150addscreateDefaultProbeId()that checksglobalThis.crypto?.randomUUIDwithtypeof === 'function'and falls back toDate.now+Math.random+incrementingfallbackProbeId. Testindex.test.ts:69-78stubscryptotoundefinedand verifiescheck.run()still succeeds. - ✅
r1-2fixed correctly — Stuck previous write starves all future probes: Starvation removed:previousWriteSettledandawait withTimeout(previousWriteSettled)deleted fromindex.ts:164,168. NewrunProbegoes straight towriteProbeand testindex.test.ts:236-329verifies recovery while an earlier timed-outinsertIfAbsentis still pending – secondrun()issues its own write (writeCalls==2) instead of waiting on the zombie. - ✅
r1-3fixed correctly — Per-instance random probe id causes unbounded row growth: Unbounded growth mitigated: successful probe now doesdeleteIfUnchangedbest-effort after verifiedgetVersioned(index.ts:214-222), andindex.test.ts:92-96assertslist('__health__')is empty after a default-id probe. DocsMONITORING.md:61/README.md:46-48now state row is conditionally removed and advise explicit replica id, so per-construction leak per success is eliminated (orphan … - ✅
r1-4fixed correctly — A write that never settles wedges every later probe on the check instance: Same wedge as r1-2 – removed thepreviousWriteSettledgate that made every laterrun()waittimeoutMsand never re-point. New shared-deadline + CAS loop (writeProbe+withinDeadline) lets next probe start immediately; verified by "recovers while an earlier timed-out write is still pending" test. - ✅
r1-5fixed correctly — Effective probe deadline can reach ~3× timeoutMs: Deadline now shared:runProbesetsdeadline = started + timeoutMs(index.ts:181-182) and all storage ops go throughwithinDeadlinewhich usesremainingMs = deadline - Date.now()(index.ts:266-274). Testindex.test.ts:405-453proves sequential 3ms+3ms ops with 5ms budget fails withstore_ping_timeoutat ~5ms and does not reach 15ms. - ✅
r1-6fixed correctly — Breaking change: default probe row id changed from stable "ping": Breaking-change documented:docs/MONITORING.md:63-64andpackages/health/README.md:50-51now state "Earlier releases usedpingas the default; passid: \"ping\"to retain that key intentionally", giving explicit migration path for dashboards/janitors queryingid:"ping". - ✅
r1-7fixed correctly — Default per-instance probe id turns the health collection into unbounded growth with no cleanup: Duplicate of r1-3 growth concern – same conditionaldeleteIfUnchangedcleanup and per-incident orphan bound applies. Default id stays unique for replica isolation but no longer leaves one row per successful construction. - 8 nit finding(s) from earlier rounds retired (severity floor for follow-up rounds is
risk). - Open findings after this round: 1 (0 bug-severity).
Findings
🟠 Issue 1 — CAS retry loop in writeProbe has no attempt cap or backoff, so sustained contention hammers the store until the deadline
packages/health/src/index.ts:173 · risk · identified by z-ai/glm-5.3-flash
Concrete failure: two replicas misconfigured with the same explicit id (a misuse the new migration note makes easier, since it invites hosts to pass id: "ping" for backward compatibility), or a store adapter whose putIfUnchanged always returns false / whose insertIfAbsent always reports inserted: false, make the for (;;) loop in writeProbe issue a getVersioned + conditional-write pair at full speed on every iteration. With the default timeoutMs: 5000 and a ~10ms store round trip, that is on the order of a thousand storage operations per probe run — versus exactly two (put + get) in the previous implementation — repeated by every scrape of a public, unauthenticated endpoint against the metered backend that docs/MONITORING.md and SEC-004 exist to protect. Each run ends in store_ping_timeout rather than any contention-specific reason, so a host cannot distinguish "storage is down" from "two replicas are fighting over one row".
Evidence: packages/health/src/index.ts:173 loops until a CAS write succeeds with no iteration cap and no delay between attempts; the only exit conditions are success and withinDeadline throwing ProbeTimeoutError when deadline - Date.now() <= 0. A secondary aggravation: if the adapter's CAS methods resolve synchronously (no real I/O pending), each iteration is pure microtask work, so the loop spins in microtasks for the entire timeout window and can starve other I/O on the isolate for up to timeoutMs per probe.
What I checked to falsify it: the shared deadline does bound the loop (it cannot hang forever — the "recovers while an earlier timed-out write is still pending" and "uses one timeout budget" tests confirm the deadline machinery works), zombie-write contention from a single instance converges in at most a couple of retries, and docs/MONITORING.md:61-64 does warn hosts to keep ids distinct among simultaneously running replicas. Those warnings are advisory only — nothing enforces them, the wall-clock bound still permits unbounded operation counts per run, and no reason code or backoff distinguishes persistent CAS contention, so I am reporting it as a risk rather than a bug. Proof gap: I could not execute the suite or inspect @pegma/storage-core@0.4.0's real putIfUnchanged semantics in this inert checkout; the severity of the adapter-triggered variant depends on whether any real adapter can report persistent CAS failure while reads stay healthy.
There was a problem hiding this comment.
OpenRouter pull-request review
Verdict: clean
Scope: latest-commit (commit-range)
Mode: verify
Commit: ec60b3775d1d7fe36b527319fe45e332534da5d6
Judge: openai/gpt-5.6-luna
Cost: $0.0546 (lanes $0.0545 + judge $0.0001)
Lanes
meta/muse-spark-1.2: ok (0 finding(s), 14.1s, 30241+1854 tokens (5203 cached), 2 tool round(s), via Meta, $0.0400)z-ai/glm-5.3-flash: ok (0 finding(s), 52.3s, 125473+8398 tokens (69120 cached), 8 tool round(s), via PrimeIntellect, $0.0146)
Round 3 resolution
- ✅
r2-1fixed correctly — CAS retry loop in writeProbe has no attempt cap or backoff, so sustained contention hammers the store until the deadline: writeProbe now capped at MAX_PROBE_WRITE_ATTEMPTS=3 (packages/health/src/index.ts:62,174). Loopfor (let attempt=0; attempt<3; ...)does getVersioned + conditional write per attempt and throws "health probe write attempts exhausted" afterward, which runProbe maps to store_ping_failed. New test bounds repeated conditional write conflicts verifies exactly 3 reads and 3 writes before fail. Checked … - Open findings after this round: 0 (0 bug-severity).
No structured findings from the successful lane(s).
Summary
Validation
CI=1 pnpm run format:checkCI=1 pnpm run checkCI=1 pnpm test