From a1d992dc05652830387de8339d266b1b782c7444 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 6 Nov 2026 16:10:45 -0500 Subject: [PATCH 1/3] Isolate concurrent store probes --- docs/MONITORING.md | 9 ++ packages/health/README.md | 4 + packages/health/src/index.test.ts | 173 +++++++++++++++++++++++++++++- packages/health/src/index.ts | 92 ++++++++++------ 4 files changed, 241 insertions(+), 37 deletions(-) diff --git a/docs/MONITORING.md b/docs/MONITORING.md index e79294a..d25e897 100644 --- a/docs/MONITORING.md +++ b/docs/MONITORING.md @@ -54,6 +54,15 @@ rate limiting (or a short response cache, a few seconds) in front of the route, or expose the store ping only on a route scraped by trusted monitors. This package deliberately owns no rate limiter. +Construct `createStorePingCheck` once at the composition root and reuse that +check for every request. Concurrent calls to one check share the same in-flight +round trip. By default, each constructed check receives its own probe record id, +so replicas using the same health collection do not overwrite one another. A +host that constructs checks per request would leave one record per request; +long-lived hosts should use one check per replica, while short-lived runtimes +should pass a stable, replica-specific `id` and keep that id distinct from other +live replicas. + `degraded` still returns HTTP 200 with `ok: true`. If you want to page on degraded storage/logging, add a JSON assertion on `$.status` or a log monitor instead of relying on status codes alone. diff --git a/packages/health/README.md b/packages/health/README.md index 52e22a1..8a5de31 100644 --- a/packages/health/README.md +++ b/packages/health/README.md @@ -43,3 +43,7 @@ bound your own I/O the way `createStorePingCheck` bounds its `timeoutMs`. `createStorePingCheck` writes and reads on every call, so a host serving it on a public route SHOULD rate limit or briefly cache that route — see [`docs/MONITORING.md`](https://github.com/pegma-dev/health/blob/main/docs/MONITORING.md). +Construct the check once at the composition root and reuse it for every health +request. Its default record id is unique to that check instance, which keeps +replicas from sharing a probe row; pass a stable, replica-specific `id` when a +deployment needs to reuse the same row across process restarts. diff --git a/packages/health/src/index.test.ts b/packages/health/src/index.test.ts index 62effed..9787516 100644 --- a/packages/health/src/index.test.ts +++ b/packages/health/src/index.test.ts @@ -1,4 +1,4 @@ -import { fixedClock, type Logger } from "@pegma/spine"; +import { fixedClock, type Clock, type Logger } from "@pegma/spine"; import { createMemoryStore } from "@pegma/storage-core"; import { describe, expect, it } from "vitest"; @@ -11,6 +11,7 @@ import { toHealthResponse, type CheckResult, type HealthCheck, + type HealthProbeRecord, } from "./index.js"; import type { Store } from "@pegma/storage-core"; @@ -24,6 +25,14 @@ const NOW = "2026-07-27T21:00:00.000Z"; const SECRET_SHAPED_MESSAGE = "AccountName=example;AccountKey=PLACEHOLDER_NOT_A_REAL_KEY"; +function deferred() { + let resolve!: (value: T | PromiseLike) => void; + const promise = new Promise((settle) => { + resolve = settle; + }); + return { promise, resolve }; +} + function failingCheck( name: string, status: CheckResult["status"], @@ -70,14 +79,170 @@ describe("createStorePingCheck", () => { const stored = await store .collection(healthProbeCollection) - .get({ partition: "__health__", id: "ping" }); - expect(stored).toEqual({ - id: "ping", + .list("__health__"); + expect(stored).toHaveLength(1); + expect(stored[0]).toEqual({ + id: expect.stringMatching( + /^ping-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/, + ), partition: "__health__", probedAt: NOW, }); }); + it("honors an explicit probe id", async () => { + const store = createMemoryStore(); + const check = createStorePingCheck({ + store, + collection: healthProbeCollection, + clock: fixedClock(NOW), + id: "replica-a", + }); + + await expect(check.run()).resolves.toMatchObject({ status: "ok" }); + await expect( + store + .collection(healthProbeCollection) + .get({ partition: "__health__", id: "replica-a" }), + ).resolves.toEqual({ + id: "replica-a", + partition: "__health__", + probedAt: NOW, + }); + }); + + it("coalesces concurrent calls on one check instance", async () => { + const writeStarted = deferred(); + let stored: HealthProbeRecord | null = null; + let putCalls = 0; + let nowCalls = 0; + const clock: Clock = { + now() { + nowCalls += 1; + return nowCalls === 1 ? NOW : "2026-07-27T21:00:01.000Z"; + }, + }; + const store = { + collection() { + return { + async put(value: HealthProbeRecord) { + putCalls += 1; + await writeStarted.promise; + stored = value; + }, + async get() { + return stored; + }, + }; + }, + } as unknown as Store; + const check = createStorePingCheck({ + store, + collection: healthProbeCollection, + clock, + }); + + const first = check.run(); + const second = check.run(); + expect(second).toBe(first); + writeStarted.resolve(); + + await expect(Promise.all([first, second])).resolves.toMatchObject([ + { status: "ok" }, + { status: "ok" }, + ]); + expect(putCalls).toBe(1); + expect(nowCalls).toBe(1); + }); + + it("isolates separate check instances sharing one store", async () => { + const firstWrite = deferred(); + const records = new Map(); + let putCalls = 0; + const store = { + collection() { + return { + async put(value: HealthProbeRecord) { + putCalls += 1; + records.set(value.id, value); + if (putCalls === 1) { + await firstWrite.promise; + } else { + firstWrite.resolve(); + } + }, + async get(key: { readonly id: string }) { + return records.get(key.id) ?? null; + }, + }; + }, + } as unknown as Store; + const first = createStorePingCheck({ + store, + collection: healthProbeCollection, + clock: fixedClock(NOW), + }); + const second = createStorePingCheck({ + store, + collection: healthProbeCollection, + clock: fixedClock("2026-07-27T21:00:01.000Z"), + }); + + const results = await Promise.all([first.run(), second.run()]); + + expect(results).toMatchObject([{ status: "ok" }, { status: "ok" }]); + expect(records).toHaveLength(2); + }); + + it("waits for a timed-out write before starting the next probe", async () => { + const slowWrite = deferred(); + let stored: HealthProbeRecord | null = null; + let putCalls = 0; + let nowCalls = 0; + const clock: Clock = { + now() { + nowCalls += 1; + return nowCalls === 1 ? NOW : "2026-07-27T21:00:01.000Z"; + }, + }; + const store = { + collection() { + return { + async put(value: HealthProbeRecord) { + putCalls += 1; + if (putCalls === 1) { + await slowWrite.promise; + } + stored = value; + }, + async get() { + return stored; + }, + }; + }, + } as unknown as Store; + const check = createStorePingCheck({ + store, + collection: healthProbeCollection, + clock, + timeoutMs: 5, + }); + + await expect(check.run()).resolves.toMatchObject({ + status: "fail", + detail: { reason: "store_ping_timeout" }, + }); + const next = check.run(); + await Promise.resolve(); + expect(putCalls).toBe(1); + + slowWrite.resolve(); + + await expect(next).resolves.toMatchObject({ status: "ok" }); + expect(putCalls).toBe(2); + expect(nowCalls).toBe(2); + }); + it("fails when the store rejects writes", async () => { const brokenStore = { collection() { diff --git a/packages/health/src/index.ts b/packages/health/src/index.ts index d7cd110..424b30e 100644 --- a/packages/health/src/index.ts +++ b/packages/health/src/index.ts @@ -57,7 +57,7 @@ export interface HealthProbeRecord { } const DEFAULT_PARTITION = "__health__"; -const DEFAULT_PROBE_ID = "ping"; +const DEFAULT_PROBE_ID_PREFIX = "ping-"; const DEFAULT_TIMEOUT_MS = 5_000; const MAX_LOGGED_ERROR_CHARS = 300; @@ -130,7 +130,7 @@ export interface StorePingCheckOptions { readonly collection: CollectionDefinition; /** Defaults to `__health__`. */ readonly partitionKey?: string; - /** Defaults to `ping`. */ + /** Defaults to a unique id for this check instance. */ readonly id?: string; /** Defaults to `storage`. */ readonly name?: string; @@ -148,46 +148,72 @@ export function createStorePingCheck( ): HealthCheck { const name = options.name ?? "storage"; const partition = options.partitionKey ?? DEFAULT_PARTITION; - const id = options.id ?? DEFAULT_PROBE_ID; + const id = + options.id ?? `${DEFAULT_PROBE_ID_PREFIX}${globalThis.crypto.randomUUID()}`; const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS; const clock = options.clock ?? systemClock; const probes = options.store.collection(options.collection); + let inFlight: Promise | undefined; + let previousWriteSettled: Promise = Promise.resolve(); - return { - name, - async run() { - const started = Date.now(); - try { - const probedAt = clock.now(); - const record: HealthProbeRecord = { id, partition, probedAt }; - await withTimeout(probes.put(record), timeoutMs); - const got = await withTimeout(probes.get({ partition, id }), timeoutMs); - if (got === null || got.probedAt !== probedAt) { - return { - status: "fail", - latencyMs: Date.now() - started, - detail: { reason: "round_trip_mismatch" }, - }; - } - return { - status: "ok", - latencyMs: Date.now() - started, - }; - } catch (error) { - // Never surface the underlying error text: store adapter messages - // routinely embed account names, URLs, and request ids, and this detail - // is served on a public endpoint. Report an enumerated reason instead. + async function runProbe(): Promise { + const started = Date.now(); + try { + // A write may outlive its caller's timeout. Let it settle before another + // attempt uses the same row, while still bounding how long this call waits. + await withTimeout(previousWriteSettled, timeoutMs); + const probedAt = clock.now(); + const record: HealthProbeRecord = { id, partition, probedAt }; + const write = probes.put(record); + previousWriteSettled = write.then( + () => undefined, + () => undefined, + ); + await withTimeout(write, timeoutMs); + const got = await withTimeout(probes.get({ partition, id }), timeoutMs); + if (got === null || got.probedAt !== probedAt) { return { status: "fail", latencyMs: Date.now() - started, - detail: { - reason: - error instanceof ProbeTimeoutError - ? "store_ping_timeout" - : "store_ping_failed", - }, + detail: { reason: "round_trip_mismatch" }, }; } + return { + status: "ok", + latencyMs: Date.now() - started, + }; + } catch (error) { + // Never surface the underlying error text: store adapter messages + // routinely embed account names, URLs, and request ids, and this detail + // is served on a public endpoint. Report an enumerated reason instead. + return { + status: "fail", + latencyMs: Date.now() - started, + detail: { + reason: + error instanceof ProbeTimeoutError + ? "store_ping_timeout" + : "store_ping_failed", + }, + }; + } + } + + return { + name, + run() { + if (inFlight !== undefined) { + return inFlight; + } + + const attempt = runProbe(); + inFlight = attempt; + void attempt.finally(() => { + if (inFlight === attempt) { + inFlight = undefined; + } + }); + return attempt; }, }; } From a5f9b51069adab2106ccb9b62306ac844b1ad439 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 6 Nov 2026 16:22:23 -0500 Subject: [PATCH 2/3] Refine store probe coordination --- docs/MONITORING.md | 24 +-- packages/health/README.md | 14 +- packages/health/src/index.test.ts | 257 +++++++++++++++++++++++------- packages/health/src/index.ts | 82 ++++++++-- 4 files changed, 286 insertions(+), 91 deletions(-) diff --git a/docs/MONITORING.md b/docs/MONITORING.md index d25e897..b7f663f 100644 --- a/docs/MONITORING.md +++ b/docs/MONITORING.md @@ -47,21 +47,21 @@ Suggested schedule: every 1–5 minutes. Alert on consecutive failures (e.g. 2). ## Protect the route from amplification -`createStorePingCheck` performs a real write plus a read on every call — that is -the point, a connectivity ping would lie. It also means each request to the -public route costs one storage write against a metered backend. Hosts SHOULD put -rate limiting (or a short response cache, a few seconds) in front of the route, -or expose the store ping only on a route scraped by trusted monitors. This -package deliberately owns no rate limiter. +`createStorePingCheck` performs a real write plus a read for each probe +execution — that is the point, a connectivity ping would lie. It also means +requests to the public route can cost storage writes against a metered backend. +Hosts SHOULD put rate limiting (or a short response cache, a few seconds) in +front of the route, or expose the store ping only on a route scraped by trusted +monitors. This package deliberately owns no rate limiter. Construct `createStorePingCheck` once at the composition root and reuse that check for every request. Concurrent calls to one check share the same in-flight -round trip. By default, each constructed check receives its own probe record id, -so replicas using the same health collection do not overwrite one another. A -host that constructs checks per request would leave one record per request; -long-lived hosts should use one check per replica, while short-lived runtimes -should pass a stable, replica-specific `id` and keep that id distinct from other -live replicas. +round trip and its reported latency. By default, each constructed check receives +its own probe record id, so replicas using the same health collection do not +overwrite one another. A verified row is conditionally removed after the round +trip. Pass an explicit `id` when a host needs a stable key, and keep that id +distinct among simultaneously running replicas. Earlier releases used `ping` as +the default; pass `id: "ping"` to retain that key intentionally. `degraded` still returns HTTP 200 with `ok: true`. If you want to page on degraded storage/logging, add a JSON assertion on `$.status` or a log monitor diff --git a/packages/health/README.md b/packages/health/README.md index 8a5de31..26125fe 100644 --- a/packages/health/README.md +++ b/packages/health/README.md @@ -40,10 +40,14 @@ logged through the injected `Logger` only, never placed in the public body. A check must settle, though: `runHealthChecks` imposes no deadline of its own, so bound your own I/O the way `createStorePingCheck` bounds its `timeoutMs`. -`createStorePingCheck` writes and reads on every call, so a host serving it on a -public route SHOULD rate limit or briefly cache that route — see +`createStorePingCheck` performs a write-and-read round trip for each probe +execution, so a host serving it on a public route SHOULD rate limit or briefly +cache that route — see [`docs/MONITORING.md`](https://github.com/pegma-dev/health/blob/main/docs/MONITORING.md). Construct the check once at the composition root and reuse it for every health -request. Its default record id is unique to that check instance, which keeps -replicas from sharing a probe row; pass a stable, replica-specific `id` when a -deployment needs to reuse the same row across process restarts. +request. Concurrent callers share one execution and its `latencyMs`. The default +record id is unique to that check instance, which keeps replicas from sharing a +probe row, and a verified row is conditionally removed after the round trip. +Pass an explicit `id` when the host needs a stable key; keep that id distinct +among simultaneously running replicas. Earlier releases used `ping` as the +default, so pass `id: "ping"` to retain that key intentionally. diff --git a/packages/health/src/index.test.ts b/packages/health/src/index.test.ts index 9787516..9c7c3c8 100644 --- a/packages/health/src/index.test.ts +++ b/packages/health/src/index.test.ts @@ -1,6 +1,6 @@ import { fixedClock, type Clock, type Logger } from "@pegma/spine"; import { createMemoryStore } from "@pegma/storage-core"; -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { createDetailCheck, @@ -66,6 +66,20 @@ describe("createDetailCheck", () => { }); describe("createStorePingCheck", () => { + it("constructs when Web Crypto is unavailable", async () => { + vi.stubGlobal("crypto", undefined); + try { + const check = createStorePingCheck({ + store: createMemoryStore(), + collection: healthProbeCollection, + clock: fixedClock(NOW), + }); + await expect(check.run()).resolves.toMatchObject({ status: "ok" }); + } finally { + vi.unstubAllGlobals(); + } + }); + it("round-trips a probe write through an injected store", async () => { const store = createMemoryStore(); const check = createStorePingCheck({ @@ -80,18 +94,33 @@ describe("createStorePingCheck", () => { const stored = await store .collection(healthProbeCollection) .list("__health__"); - expect(stored).toHaveLength(1); - expect(stored[0]).toEqual({ - id: expect.stringMatching( - /^ping-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/, - ), - partition: "__health__", - probedAt: NOW, - }); + expect(stored).toEqual([]); }); it("honors an explicit probe id", async () => { - const store = createMemoryStore(); + let stored: HealthProbeRecord | null = null; + let observed: HealthProbeRecord | null = null; + const store = { + collection() { + return { + async getVersioned() { + return stored === null ? null : { value: stored, version: "1" }; + }, + async insertIfAbsent(value: HealthProbeRecord) { + stored = value; + observed = value; + return { inserted: true, value }; + }, + async putIfUnchanged() { + return false; + }, + async deleteIfUnchanged() { + stored = null; + return true; + }, + }; + }, + } as unknown as Store; const check = createStorePingCheck({ store, collection: healthProbeCollection, @@ -100,11 +129,7 @@ describe("createStorePingCheck", () => { }); await expect(check.run()).resolves.toMatchObject({ status: "ok" }); - await expect( - store - .collection(healthProbeCollection) - .get({ partition: "__health__", id: "replica-a" }), - ).resolves.toEqual({ + expect(observed).toEqual({ id: "replica-a", partition: "__health__", probedAt: NOW, @@ -114,7 +139,7 @@ describe("createStorePingCheck", () => { it("coalesces concurrent calls on one check instance", async () => { const writeStarted = deferred(); let stored: HealthProbeRecord | null = null; - let putCalls = 0; + let writeCalls = 0; let nowCalls = 0; const clock: Clock = { now() { @@ -125,13 +150,21 @@ describe("createStorePingCheck", () => { const store = { collection() { return { - async put(value: HealthProbeRecord) { - putCalls += 1; + async getVersioned() { + return stored === null ? null : { value: stored, version: "1" }; + }, + async insertIfAbsent(value: HealthProbeRecord) { + writeCalls += 1; await writeStarted.promise; stored = value; + return { inserted: true, value }; }, - async get() { - return stored; + async putIfUnchanged() { + return false; + }, + async deleteIfUnchanged() { + stored = null; + return true; }, }; }, @@ -151,28 +184,40 @@ describe("createStorePingCheck", () => { { status: "ok" }, { status: "ok" }, ]); - expect(putCalls).toBe(1); + expect(writeCalls).toBe(1); expect(nowCalls).toBe(1); }); it("isolates separate check instances sharing one store", async () => { const firstWrite = deferred(); - const records = new Map(); - let putCalls = 0; + const records = new Map< + string, + { value: HealthProbeRecord; version: string } + >(); + const observedIds = new Set(); + let writeCalls = 0; const store = { collection() { return { - async put(value: HealthProbeRecord) { - putCalls += 1; - records.set(value.id, value); - if (putCalls === 1) { + async getVersioned(key: { readonly id: string }) { + return records.get(key.id) ?? null; + }, + async insertIfAbsent(value: HealthProbeRecord) { + writeCalls += 1; + observedIds.add(value.id); + records.set(value.id, { value, version: String(writeCalls) }); + if (writeCalls === 1) { await firstWrite.promise; } else { firstWrite.resolve(); } + return { inserted: true, value }; }, - async get(key: { readonly id: string }) { - return records.get(key.id) ?? null; + async putIfUnchanged() { + return false; + }, + async deleteIfUnchanged(key: { readonly id: string }) { + return records.delete(key.id); }, }; }, @@ -191,32 +236,64 @@ describe("createStorePingCheck", () => { const results = await Promise.all([first.run(), second.run()]); expect(results).toMatchObject([{ status: "ok" }, { status: "ok" }]); - expect(records).toHaveLength(2); + expect(observedIds.size).toBe(2); + for (const id of observedIds) { + expect(id).toMatch(/^ping-/); + } }); - it("waits for a timed-out write before starting the next probe", async () => { + it("recovers while an earlier timed-out write is still pending", async () => { + vi.useFakeTimers(); const slowWrite = deferred(); - let stored: HealthProbeRecord | null = null; - let putCalls = 0; + let stored: { value: HealthProbeRecord; version: string } | null = null; + let writeCalls = 0; + let version = 0; let nowCalls = 0; const clock: Clock = { now() { nowCalls += 1; - return nowCalls === 1 ? NOW : "2026-07-27T21:00:01.000Z"; + return nowCalls === 1 + ? NOW + : nowCalls === 2 + ? "2026-07-27T21:00:01.000Z" + : "2026-07-27T21:00:02.000Z"; }, }; const store = { collection() { return { - async put(value: HealthProbeRecord) { - putCalls += 1; - if (putCalls === 1) { + async getVersioned() { + return stored; + }, + async insertIfAbsent(value: HealthProbeRecord) { + writeCalls += 1; + if (writeCalls === 1) { await slowWrite.promise; } - stored = value; + if (stored !== null) { + return { inserted: false, value: stored.value }; + } + version += 1; + stored = { value, version: String(version) }; + return { inserted: true, value }; }, - async get() { - return stored; + async putIfUnchanged(value: HealthProbeRecord, expected: string) { + if (stored?.version !== expected) { + return false; + } + version += 1; + stored = { value, version: String(version) }; + return true; + }, + async deleteIfUnchanged( + _key: { readonly id: string }, + expected: string, + ) { + if (stored?.version !== expected) { + return false; + } + stored = null; + return true; }, }; }, @@ -225,32 +302,38 @@ describe("createStorePingCheck", () => { store, collection: healthProbeCollection, clock, + id: "replica-a", timeoutMs: 5, }); - await expect(check.run()).resolves.toMatchObject({ - status: "fail", - detail: { reason: "store_ping_timeout" }, - }); - const next = check.run(); - await Promise.resolve(); - expect(putCalls).toBe(1); + try { + const timedOut = check.run(); + await vi.advanceTimersByTimeAsync(5); + await expect(timedOut).resolves.toMatchObject({ + status: "fail", + detail: { reason: "store_ping_timeout" }, + }); - slowWrite.resolve(); + await expect(check.run()).resolves.toMatchObject({ status: "ok" }); + expect(writeCalls).toBe(2); - await expect(next).resolves.toMatchObject({ status: "ok" }); - expect(putCalls).toBe(2); - expect(nowCalls).toBe(2); + slowWrite.resolve(); + await Promise.resolve(); + await expect(check.run()).resolves.toMatchObject({ status: "ok" }); + expect(nowCalls).toBe(3); + } finally { + vi.useRealTimers(); + } }); it("fails when the store rejects writes", async () => { const brokenStore = { collection() { return { - async get() { + async getVersioned() { return null; }, - async put() { + async insertIfAbsent() { throw new Error("tables unavailable"); }, }; @@ -270,10 +353,10 @@ describe("createStorePingCheck", () => { const brokenStore = { collection() { return { - async get() { + async getVersioned() { return null; }, - async put() { + async insertIfAbsent() { throw new Error(SECRET_SHAPED_MESSAGE); }, }; @@ -290,14 +373,15 @@ describe("createStorePingCheck", () => { }); it("reports a timeout as its own enumerated reason", async () => { + vi.useFakeTimers(); const hangingStore = { collection() { return { - async get() { + async getVersioned() { return null; }, - put() { - return new Promise(() => { + insertIfAbsent() { + return new Promise(() => { // never settles }); }, @@ -310,9 +394,60 @@ describe("createStorePingCheck", () => { clock: fixedClock(NOW), timeoutMs: 5, }); - const result = await check.run(); - expect(result.status).toBe("fail"); - expect(result.detail).toEqual({ reason: "store_ping_timeout" }); + try { + const pending = check.run(); + await vi.advanceTimersByTimeAsync(5); + const result = await pending; + expect(result.status).toBe("fail"); + expect(result.detail).toEqual({ reason: "store_ping_timeout" }); + } finally { + vi.useRealTimers(); + } + }); + + it("uses one timeout budget across storage operations", async () => { + vi.useFakeTimers(); + let stored: HealthProbeRecord | null = null; + const store = { + collection() { + return { + getVersioned() { + return new Promise((resolve) => { + setTimeout(() => resolve(null), 3); + }); + }, + insertIfAbsent(value: HealthProbeRecord) { + return new Promise<{ inserted: true; value: HealthProbeRecord }>( + (resolve) => { + setTimeout(() => { + stored = value; + resolve({ inserted: true, value }); + }, 3); + }, + ); + }, + }; + }, + } as unknown as Store; + const check = createStorePingCheck({ + store, + collection: healthProbeCollection, + clock: fixedClock(NOW), + timeoutMs: 5, + }); + + try { + const pending = check.run(); + await vi.advanceTimersByTimeAsync(5); + await expect(pending).resolves.toMatchObject({ + status: "fail", + latencyMs: 5, + detail: { reason: "store_ping_timeout" }, + }); + expect(stored).toBeNull(); + } finally { + vi.useRealTimers(); + } }); }); diff --git a/packages/health/src/index.ts b/packages/health/src/index.ts index 424b30e..932c28e 100644 --- a/packages/health/src/index.ts +++ b/packages/health/src/index.ts @@ -60,6 +60,7 @@ const DEFAULT_PARTITION = "__health__"; const DEFAULT_PROBE_ID_PREFIX = "ping-"; const DEFAULT_TIMEOUT_MS = 5_000; const MAX_LOGGED_ERROR_CHARS = 300; +let fallbackProbeId = 0; /** Marks a probe that exceeded its own timeout rather than rejecting. */ class ProbeTimeoutError extends Error {} @@ -139,6 +140,16 @@ export interface StorePingCheckOptions { readonly clock?: Clock; } +function createDefaultProbeId(): string { + const randomUUID = globalThis.crypto?.randomUUID; + if (typeof randomUUID === "function") { + return `${DEFAULT_PROBE_ID_PREFIX}${randomUUID.call(globalThis.crypto)}`; + } + + fallbackProbeId += 1; + return `${DEFAULT_PROBE_ID_PREFIX}${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${fallbackProbeId.toString(36)}`; +} + /** * Put-then-get round-trip against an injected Store. Proves the storage layer * accepts writes and returns them — not merely that a TCP port is open. @@ -148,36 +159,70 @@ export function createStorePingCheck( ): HealthCheck { const name = options.name ?? "storage"; const partition = options.partitionKey ?? DEFAULT_PARTITION; - const id = - options.id ?? `${DEFAULT_PROBE_ID_PREFIX}${globalThis.crypto.randomUUID()}`; + const id = options.id ?? createDefaultProbeId(); const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS; const clock = options.clock ?? systemClock; const probes = options.store.collection(options.collection); let inFlight: Promise | undefined; - let previousWriteSettled: Promise = Promise.resolve(); + + async function writeProbe( + record: HealthProbeRecord, + deadline: number, + ): Promise { + const key = { partition, id }; + for (;;) { + const current = await withinDeadline( + () => probes.getVersioned(key), + deadline, + ); + if (current === null) { + const result = await withinDeadline( + () => probes.insertIfAbsent(record), + deadline, + ); + if (result.inserted) { + return; + } + } else { + const written = await withinDeadline( + () => probes.putIfUnchanged(record, current.version), + deadline, + ); + if (written) { + return; + } + } + } + } async function runProbe(): Promise { const started = Date.now(); + const deadline = started + timeoutMs; try { - // A write may outlive its caller's timeout. Let it settle before another - // attempt uses the same row, while still bounding how long this call waits. - await withTimeout(previousWriteSettled, timeoutMs); const probedAt = clock.now(); const record: HealthProbeRecord = { id, partition, probedAt }; - const write = probes.put(record); - previousWriteSettled = write.then( - () => undefined, - () => undefined, + await writeProbe(record, deadline); + const got = await withinDeadline( + () => probes.getVersioned({ partition, id }), + deadline, ); - await withTimeout(write, timeoutMs); - const got = await withTimeout(probes.get({ partition, id }), timeoutMs); - if (got === null || got.probedAt !== probedAt) { + if (got === null || got.value.probedAt !== probedAt) { return { status: "fail", latencyMs: Date.now() - started, detail: { reason: "round_trip_mismatch" }, }; } + + try { + await withinDeadline( + () => probes.deleteIfUnchanged({ partition, id }, got.version), + deadline, + ); + } catch { + // Cleanup is best effort. The verified round trip remains valid, and a + // later conditional write can safely reuse this check instance's row. + } return { status: "ok", latencyMs: Date.now() - started, @@ -218,6 +263,17 @@ export function createStorePingCheck( }; } +function withinDeadline( + operation: () => Promise, + deadline: number, +): Promise { + const remainingMs = deadline - Date.now(); + if (remainingMs <= 0) { + return Promise.reject(new ProbeTimeoutError("probe deadline elapsed")); + } + return withTimeout(operation(), remainingMs); +} + function withTimeout(promise: Promise, timeoutMs: number): Promise { return new Promise((resolve, reject) => { const timer = setTimeout(() => { From ec60b3775d1d7fe36b527319fe45e332534da5d6 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 6 Nov 2026 16:31:20 -0500 Subject: [PATCH 3/3] Bound store probe write retries --- packages/health/src/index.test.ts | 39 +++++++++++++++++++++++++++++++ packages/health/src/index.ts | 4 +++- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/packages/health/src/index.test.ts b/packages/health/src/index.test.ts index 9c7c3c8..bce8f5c 100644 --- a/packages/health/src/index.test.ts +++ b/packages/health/src/index.test.ts @@ -349,6 +349,45 @@ describe("createStorePingCheck", () => { expect(result.detail).toEqual({ reason: "store_ping_failed" }); }); + it("bounds repeated conditional write conflicts", async () => { + const existing: HealthProbeRecord = { + id: "replica-a", + partition: "__health__", + probedAt: NOW, + }; + let reads = 0; + let writes = 0; + const store = { + collection() { + return { + async getVersioned() { + reads += 1; + return { value: existing, version: "unchanged" }; + }, + async putIfUnchanged() { + writes += 1; + return false; + }, + }; + }, + } as unknown as Store; + const check = createStorePingCheck({ + store, + collection: healthProbeCollection, + clock: fixedClock(NOW), + id: "replica-a", + }); + + const result = await check.run(); + + expect(result).toMatchObject({ + status: "fail", + detail: { reason: "store_ping_failed" }, + }); + expect(reads).toBe(3); + expect(writes).toBe(3); + }); + it("never leaks the store error message into public detail", async () => { const brokenStore = { collection() { diff --git a/packages/health/src/index.ts b/packages/health/src/index.ts index 932c28e..b4edb63 100644 --- a/packages/health/src/index.ts +++ b/packages/health/src/index.ts @@ -59,6 +59,7 @@ export interface HealthProbeRecord { const DEFAULT_PARTITION = "__health__"; const DEFAULT_PROBE_ID_PREFIX = "ping-"; const DEFAULT_TIMEOUT_MS = 5_000; +const MAX_PROBE_WRITE_ATTEMPTS = 3; const MAX_LOGGED_ERROR_CHARS = 300; let fallbackProbeId = 0; @@ -170,7 +171,7 @@ export function createStorePingCheck( deadline: number, ): Promise { const key = { partition, id }; - for (;;) { + for (let attempt = 0; attempt < MAX_PROBE_WRITE_ATTEMPTS; attempt += 1) { const current = await withinDeadline( () => probes.getVersioned(key), deadline, @@ -193,6 +194,7 @@ export function createStorePingCheck( } } } + throw new Error("health probe write attempts exhausted"); } async function runProbe(): Promise {