From 26a907e745ca2a5326a7b337b9102a7dbf2d3c89 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 13 Nov 2026 20:07:01 -0500 Subject: [PATCH 1/3] Report bounded release reconciliation failure details --- ...release-reconciliation-diagnostics.test.ts | 218 ++++++++++++++++++ worker/src/release-reconciliation.ts | 55 ++++- 2 files changed, 271 insertions(+), 2 deletions(-) create mode 100644 worker/src/release-reconciliation-diagnostics.test.ts diff --git a/worker/src/release-reconciliation-diagnostics.test.ts b/worker/src/release-reconciliation-diagnostics.test.ts new file mode 100644 index 0000000..e2dfc28 --- /dev/null +++ b/worker/src/release-reconciliation-diagnostics.test.ts @@ -0,0 +1,218 @@ +import { + createMemoryStore, + type CollectionDefinition, + type CollectionStore, + type Store, +} from '@pegma/storage-core'; +import type { Logger } from '@pegma/spine'; +import { describe, expect, it, vi } from 'vitest'; +import { componentReleaseCollection, componentReleaseKey } from './component-release'; +import { RELEASE_CATALOG } from './release-catalog'; +import { readReleaseOpsState } from './release-ops-state'; +import { runReleaseReconciliation } from './release-reconciliation'; + +const ID = '1312512520'; +const START = Date.parse('2026-11-14T00:00:00Z'); +const AT = '2026-11-14T00:00:01.000Z'; +const LIMIT = 256 * 1024; +const CANARY = 'FICTIONAL_DIAGNOSTIC_DO_NOT_LOG'; +const latest = { id: 123, tag_name: 'v1.0.0', published_at: '2026-11-01T00:00:00Z', draft: false, prerelease: false }; +const validBody = JSON.stringify(latest); +type Fault = 'ops_read' | 'ops_merge' | 'epoch_read' | 'projection_read' | 'transaction'; + +function fixture(fault?: Fault) { + const base = createMemoryStore(); + const log = vi.fn(); + const activity = { reads: 0, versionedReads: 0, transactions: 0, updates: 0 }; + const store: Store = { + collection(definition: CollectionDefinition): CollectionStore { + const records = base.collection(definition); + return { + ...records, + async get(key) { + activity.reads++; + if (fault === 'ops_read' && definition.name === 'releaseOps') throw new Error(CANARY); + return records.get(key); + }, + async getVersioned(key) { + activity.versionedReads++; + if (definition.name === 'componentReleases' && + ((fault === 'epoch_read' && key.id.startsWith('followup-epoch:')) || + (fault === 'projection_read' && key.id === ID))) throw new Error(CANARY); + return records.getVersioned(key); + }, + async transact(partition, actions) { + activity.transactions++; + if (fault === 'transaction' && definition.name === 'componentReleases') throw new Error(CANARY); + return records.transact(partition, actions); + }, + async update(key, decide, options) { + activity.updates++; + if (fault === 'ops_merge' && definition.name === 'releaseOps') throw new Error(CANARY); + return records.update(key, decide, options); + }, + }; + }, + }; + const run = (fetchImpl: typeof fetch, now = AT) => runReleaseReconciliation({ + store, logger: { log }, config: { allowedRepositoryIds: new Set([ID]) }, + scheduledTime: START, now, fetchImpl, + }); + return { base, store, log, activity, run }; +} + +function bodyMustNotBeRead(status: 304 | 404) { + const response = new Response(null, { status }); + const read = vi.fn(() => { throw new Error(CANARY); }); + Object.defineProperty(response, 'body', { get: read }); + return { response, read }; +} + +async function seed(f: ReturnType) { + await f.base.collection(componentReleaseCollection()).update(componentReleaseKey(ID), () => ({ + action: 'write', value: { repositoryId: ID, repositoryName: 'spine', releaseId: '123', tagName: 'v1.0.0', + publishedAt: latest.published_at, releaseUrl: 'https://github.com/pegma-dev/spine/releases/tag/v1.0.0', observedAt: '2026-11-13T18:00:00Z' }, + })); +} + +describe('bounded release reconciliation diagnostics', () => { + it('keeps 200/304/404 summaries, projection changes and one log/fetch per invocation', async () => { + const f = fixture(); + const fetchImpl = vi.fn(async () => new Response(validBody, { headers: { ETag: 'fixture-etag' } })); + expect(await f.run(fetchImpl)).toEqual({ examined: 1, upserted: 1, cleared: 0, notModified: 0, failed: 0 }); + expect(f.activity).toEqual({ reads: 1, versionedReads: 2, transactions: 1, updates: 1 }); + expect((await readReleaseOpsState(f.base)).lastSuccessfulReconciliationAt).toBe(new Date(START).toISOString()); + + const notModified = bodyMustNotBeRead(304); + fetchImpl.mockResolvedValueOnce(notModified.response); + expect(await f.run(fetchImpl, '2026-11-14T00:00:02.000Z')).toEqual({ examined: 1, upserted: 0, cleared: 0, notModified: 1, failed: 0 }); + expect(notModified.read).not.toHaveBeenCalled(); + expect((await f.base.collection(componentReleaseCollection()).get(componentReleaseKey(ID)))?.observedAt).toBe('2026-11-14T00:00:02.000Z'); + expect(f.activity).toEqual({ reads: 2, versionedReads: 4, transactions: 2, updates: 2 }); + + const absent = bodyMustNotBeRead(404); + fetchImpl.mockResolvedValueOnce(absent.response); + expect(await f.run(fetchImpl)).toEqual({ examined: 1, upserted: 0, cleared: 1, notModified: 0, failed: 0 }); + expect(absent.read).not.toHaveBeenCalled(); + expect(await f.base.collection(componentReleaseCollection()).get(componentReleaseKey(ID))).toBeNull(); + expect(f.activity).toEqual({ reads: 3, versionedReads: 6, transactions: 3, updates: 3 }); + expect(fetchImpl).toHaveBeenCalledTimes(3); + expect(f.log).toHaveBeenCalledTimes(3); + for (const [level, event, fields] of f.log.mock.calls) { + expect(level).toBe('info'); expect(event).toBe('release_reconciliation.completed'); + expect(Object.keys(fields ?? {}).sort()).toEqual(['cleared', 'examined', 'notModified', 'upserted']); + } + }); + + it('treats empty 404 as a successful observation without a projection transaction', async () => { + const f = fixture(); const body = bodyMustNotBeRead(404); + const fetchImpl = vi.fn(async () => body.response); + expect(await f.run(fetchImpl)).toEqual({ examined: 1, upserted: 0, cleared: 0, notModified: 0, failed: 0 }); + expect(f.activity).toEqual({ reads: 1, versionedReads: 2, transactions: 0, updates: 1 }); + expect(body.read).not.toHaveBeenCalled(); + expect((await readReleaseOpsState(f.base)).lastSuccessfulReconciliationAt).toBe(new Date(START).toISOString()); + expect(f.log).toHaveBeenCalledTimes(1); + }); + + it.each([ + ['fetch rejection', () => Promise.reject(new Error(CANARY)), { phase: 'fetch', failureClass: 'fetch_rejected' }], + ['HTTP refusal', async () => new Response(CANARY, { status: 403, headers: { 'X-Fixture': CANARY } }), { phase: 'status', failureClass: 'http_status', httpStatus: 403 }], + ['bad JSON', async () => new Response(CANARY), { phase: 'body', failureClass: 'invalid_json', httpStatus: 200, bodyBytes: CANARY.length, bodyBytesSource: 'streamed' }], + ['invalid facts', async () => Response.json({ id: CANARY }), { phase: 'facts', failureClass: 'invalid_release', httpStatus: 200 }], + ['unsafe tag', async () => Response.json({ ...latest, tag_name: CANARY + ' forbidden' }), { phase: 'url', failureClass: 'unsafe_release_url', httpStatus: 200 }], + ] as const)('reports only finite details for %s and preserves the old projection', async (_name, response, detail) => { + const f = fixture(); await seed(f); + const before = await f.base.collection(componentReleaseCollection()).get(componentReleaseKey(ID)); + const fetchImpl = vi.fn(response); + expect(await f.run(fetchImpl)).toEqual({ examined: 1, upserted: 0, cleared: 0, notModified: 0, failed: 1 }); + expect(await f.base.collection(componentReleaseCollection()).get(componentReleaseKey(ID))).toEqual(before); + expect((await readReleaseOpsState(f.base)).lastSuccessfulReconciliationAt).toBeNull(); + expect(fetchImpl).toHaveBeenCalledTimes(1); + expect(f.log).toHaveBeenCalledTimes(1); + expect(f.log).toHaveBeenCalledWith('error', 'release_reconciliation.partial_failure', expect.objectContaining({ + examined: 1, failed: 1, failureDetails: [expect.objectContaining({ repositoryId: ID, ...detail })], failureDetailsOmitted: 0, + })); + expect(JSON.stringify(f.log.mock.calls)).not.toContain(CANARY); + }); + + it.each(['epoch_read', 'projection_read', 'transaction'] as const)('labels %s rejection as projection phase without recording the error', async (fault) => { + const f = fixture(fault); await seed(f); + const fetchImpl = vi.fn(async () => new Response(validBody)); + expect((await f.run(fetchImpl)).failed).toBe(1); + expect(f.log).toHaveBeenCalledWith('error', 'release_reconciliation.partial_failure', expect.objectContaining({ + failureDetails: [expect.objectContaining({ repositoryId: ID, phase: 'projection', failureClass: 'operation_rejected', httpStatus: 200, bodyBytes: validBody.length })], + })); + expect(f.log).toHaveBeenCalledTimes(1); + expect(JSON.stringify(f.log.mock.calls)).not.toContain(CANARY); + expect((await readReleaseOpsState(f.base)).lastSuccessfulReconciliationAt).toBeNull(); + }); + + it.each([304, 404] as const)('preserves projection-read failure on HTTP %i without reading its body', async (status) => { + const f = fixture('projection_read'); const body = bodyMustNotBeRead(status); + expect((await f.run(async () => body.response)).failed).toBe(1); + expect(body.read).not.toHaveBeenCalled(); + expect(f.log).toHaveBeenCalledWith('error', 'release_reconciliation.partial_failure', expect.objectContaining({ + failureDetails: [{ repositoryId: ID, phase: 'projection', failureClass: 'operation_rejected', httpStatus: status }], + })); + expect((await readReleaseOpsState(f.base)).lastSuccessfulReconciliationAt).toBeNull(); + }); + + it.each(['ops_read', 'ops_merge'] as const)('still propagates %s failure before a misleading summary can be logged', async (fault) => { + const f = fixture(fault); + const fetchImpl = vi.fn(async () => new Response(CANARY, { status: 503 })); + await expect(f.run(fetchImpl)).rejects.toThrow(CANARY); + expect(f.log).not.toHaveBeenCalled(); + expect(fetchImpl).toHaveBeenCalledTimes(fault === 'ops_read' ? 0 : 1); + expect((await readReleaseOpsState(f.base)).lastSuccessfulReconciliationAt).toBeNull(); + }); + + it('retains bounded consumed-byte metadata for a failed body reader without error text', async () => { + const f = fixture(); let pulls = 0; + const response = new Response(new ReadableStream({ pull(controller) { + if (pulls++ === 0) controller.enqueue(new TextEncoder().encode('123')); + else controller.error(new Error(CANARY)); + } })); + expect((await f.run(async () => response)).failed).toBe(1); + expect(f.log).toHaveBeenCalledWith('error', 'release_reconciliation.partial_failure', expect.objectContaining({ + failureDetails: [{ repositoryId: ID, phase: 'body', failureClass: 'operation_rejected', httpStatus: 200, bodyBytes: 3, bodyBytesSource: 'streamed' }], + })); + expect(JSON.stringify(f.log.mock.calls)).not.toContain(CANARY); + }); + + it('accepts exactly the existing body cap and rejects one byte over with saturated diagnostics', async () => { + const f = fixture(); const body = validBody + ' '.repeat(LIMIT - validBody.length); + expect((await f.run(async () => new Response(body))).failed).toBe(0); + f.log.mockClear(); + const next = await f.run(async () => new Response(body + ' '.repeat(999))); + expect(next.failed).toBe(1); + expect(f.log).toHaveBeenCalledWith('error', 'release_reconciliation.partial_failure', expect.objectContaining({ + failureDetails: [{ repositoryId: ID, phase: 'body', failureClass: 'too_large', httpStatus: 200, bodyBytes: LIMIT + 1, bodyBytesSource: 'streamed' }], + })); + }); + + it('does not consume a declared oversized body and does not log the header', async () => { + const f = fixture(); const response = new Response(CANARY, { headers: { 'Content-Length': '9'.repeat(50) } }); + const read = vi.fn(() => { throw new Error(CANARY); }); + Object.defineProperty(response, 'body', { get: read }); + expect((await f.run(async () => response)).failed).toBe(1); + expect(read).not.toHaveBeenCalled(); + expect(f.log).toHaveBeenCalledWith('error', 'release_reconciliation.partial_failure', expect.objectContaining({ + failureDetails: [{ repositoryId: ID, phase: 'body', failureClass: 'too_large', httpStatus: 200, bodyBytes: LIMIT + 1, bodyBytesSource: 'declared' }], + })); + expect(JSON.stringify(f.log.mock.calls)).not.toContain(CANARY); + expect(JSON.stringify(f.log.mock.calls)).not.toContain('9'.repeat(50)); + }); + + it('bounds full-backfill details while keeping its counters and one summary log', async () => { + const f = fixture(); const fetchImpl = vi.fn(async () => new Response(null, { status: 503 })); + const summary = await runReleaseReconciliation({ store: f.store, logger: { log: f.log }, + config: { allowedRepositoryIds: new Set(RELEASE_CATALOG.map(entry => entry.repositoryId)) }, fetchImpl, now: AT }); + expect(summary).toEqual({ examined: 13, upserted: 0, cleared: 0, notModified: 0, failed: 13 }); + expect(fetchImpl).toHaveBeenCalledTimes(13); + expect(f.log).toHaveBeenCalledTimes(1); + expect(f.log).toHaveBeenCalledWith('error', 'release_reconciliation.partial_failure', expect.objectContaining({ + failureDetails: RELEASE_CATALOG.slice(0, 4).map(entry => ({ repositoryId: entry.repositoryId, phase: 'status', failureClass: 'http_status', httpStatus: 503 })), failureDetailsOmitted: 9, + })); + expect((await readReleaseOpsState(f.base)).lastSuccessfulReconciliationAt).toBeNull(); + }); +}); diff --git a/worker/src/release-reconciliation.ts b/worker/src/release-reconciliation.ts index bca4c29..c1bd3bc 100644 --- a/worker/src/release-reconciliation.ts +++ b/worker/src/release-reconciliation.ts @@ -26,6 +26,26 @@ const GITHUB_API = 'https://api.github.com'; const REQUEST_TIMEOUT_MS = 10_000; const MAX_RESPONSE_BYTES = 256 * 1024; const USER_AGENT = 'pegma-dev-release-reconciliation'; +const MAX_FAILURE_DETAILS = 4; + +/** Existing summary only: finite public metadata, never error/body/header text. + * bodyBytes saturates at MAX_RESPONSE_BYTES + 1; source distinguishes a + * declared oversized length from actual bytes consumed from the stream. */ +interface ReleaseFailureDetail { + readonly repositoryId: string; + phase: 'fetch' | 'status' | 'body' | 'facts' | 'url' | 'projection'; + failureClass: + | 'operation_rejected' + | 'fetch_rejected' + | 'http_status' + | 'too_large' + | 'invalid_json' + | 'invalid_release' + | 'unsafe_release_url'; + httpStatus?: number; + bodyBytes?: number; + bodyBytesSource?: 'declared' | 'streamed'; +} export interface ReleaseReconciliationConfig { readonly allowedRepositoryIds: ReadonlySet; @@ -113,6 +133,7 @@ export function githubLatestToFacts( async function readBoundedJson( response: Response, + failure: ReleaseFailureDetail, ): Promise< | { readonly ok: true; readonly value: unknown } | { readonly ok: false; readonly reason: 'too_large' | 'invalid_json' } @@ -120,9 +141,13 @@ async function readBoundedJson( const declared = response.headers.get('content-length'); if (declared !== null && /^\d+$/.test(declared)) { if (Number(declared) > MAX_RESPONSE_BYTES) { + failure.bodyBytes = MAX_RESPONSE_BYTES + 1; + failure.bodyBytesSource = 'declared'; return { ok: false, reason: 'too_large' }; } } + failure.bodyBytes = 0; + failure.bodyBytesSource = 'streamed'; const reader = response.body?.getReader(); if (reader === undefined) { return { ok: true, value: null }; @@ -138,6 +163,7 @@ async function readBoundedJson( continue; } total += value.byteLength; + failure.bodyBytes = Math.min(total, MAX_RESPONSE_BYTES + 1); if (total > MAX_RESPONSE_BYTES) { try { await reader.cancel(); @@ -167,12 +193,13 @@ async function reconcileOneRepository(options: { readonly etag: string | undefined; readonly observedAt: string; readonly fetchImpl: typeof fetch; + readonly failure: ReleaseFailureDetail; }): Promise<{ readonly outcome: 'upserted' | 'cleared' | 'not_modified' | 'unchanged' | 'failed'; readonly etag: string | undefined; }> { - const { store, entry, observedAt, fetchImpl } = options; + const { store, entry, observedAt, fetchImpl, failure } = options; // Fetch by stable numeric repository ID so a rename/recreate cannot attach // another repo's release under this catalog slot. const url = `${GITHUB_API}/repositories/${entry.repositoryId}/releases/latest`; @@ -193,10 +220,14 @@ async function reconcileOneRepository(options: { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), }); } catch { + failure.failureClass = 'fetch_rejected'; return { outcome: 'failed', etag: options.etag }; } + failure.phase = 'status'; + failure.httpStatus = response.status; if (response.status === 304) { + failure.phase = 'projection'; await touchCurrentReleaseObservedAt(store, entry.repositoryId, observedAt); return { outcome: 'not_modified', etag: options.etag }; } @@ -204,6 +235,7 @@ async function reconcileOneRepository(options: { const nextEtag = response.headers.get('etag') ?? undefined; if (response.status === 404) { + failure.phase = 'projection'; const cleared = await clearCurrentRelease(store, entry.repositoryId); return { outcome: cleared ? 'cleared' : 'unchanged', @@ -212,27 +244,35 @@ async function reconcileOneRepository(options: { } if (response.status < 200 || response.status >= 300) { + failure.failureClass = 'http_status'; return { outcome: 'failed', etag: options.etag }; } - const parsed = await readBoundedJson(response); + failure.phase = 'body'; + const parsed = await readBoundedJson(response, failure); if (!parsed.ok) { + failure.failureClass = parsed.reason; return { outcome: 'failed', etag: options.etag }; } + failure.phase = 'facts'; const facts = githubLatestToFacts(entry, parsed.value); if (facts === null) { // 2xx with an unusable body is not proof that no stable release exists // (unlike 404). Fail closed so we do not clear good local state. + failure.failureClass = 'invalid_release'; return { outcome: 'failed', etag: options.etag }; } // Catalog repositoryId is the authority; name is display-only. if (facts.repositoryId !== entry.repositoryId) { + failure.failureClass = 'invalid_release'; return { outcome: 'failed', etag: options.etag }; } + failure.phase = 'url'; const releaseUrl = buildPegmaReleaseUrl(facts.repositoryName, facts.tagName); if (releaseUrl === null) { + failure.failureClass = 'unsafe_release_url'; return { outcome: 'failed', etag: options.etag }; } @@ -247,6 +287,7 @@ async function reconcileOneRepository(options: { }; // Authoritative path: GitHub's current stable wins even when older than a // local row left behind by a missed delete/unpublish webhook. + failure.phase = 'projection'; const wrote = await applyAuthoritativeCurrentRelease(store, release); return { outcome: wrote === 'written' ? 'upserted' : 'unchanged', @@ -285,6 +326,7 @@ export async function runReleaseReconciliation( // Epoch-conditioned ETag updates so a concurrent webhook invalidation wins. const etagUpdates: ConditionalEtagUpdate[] = []; const succeeded: string[] = []; + const failureDetails: ReleaseFailureDetail[] = []; let examined = 0; let upserted = 0; @@ -297,6 +339,11 @@ export async function runReleaseReconciliation( // Re-read live ETags/epochs each repo so mid-run invalidations apply. const live = await readReleaseOpsState(store); const expectedEpoch = live.repositoryEtagEpochs[entry.repositoryId] ?? 0; + const failure: ReleaseFailureDetail = { + repositoryId: entry.repositoryId, + phase: 'fetch', + failureClass: 'operation_rejected', + }; let result: { readonly outcome: 'upserted' | 'cleared' | 'not_modified' | 'unchanged' | 'failed'; @@ -309,6 +356,7 @@ export async function runReleaseReconciliation( etag: live.repositoryEtags[entry.repositoryId], observedAt, fetchImpl, + failure, }); } catch { // Version conflicts and unexpected store errors stay per-repository so @@ -318,6 +366,7 @@ export async function runReleaseReconciliation( if (result.outcome === 'failed') { failed += 1; + if (failureDetails.length < MAX_FAILURE_DETAILS) failureDetails.push(failure); } else { succeeded.push(entry.repositoryId); } @@ -386,6 +435,8 @@ export async function runReleaseReconciliation( cleared: summary.cleared, notModified: summary.notModified, failed: summary.failed, + failureDetails, + failureDetailsOmitted: summary.failed - failureDetails.length, }); } From fa6ec24d7e02ec9c49f644773034728dd128dcb4 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 13 Nov 2026 20:09:50 -0500 Subject: [PATCH 2/3] Exercise exact catalog response byte boundary --- worker/src/release-reconciliation-diagnostics.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/worker/src/release-reconciliation-diagnostics.test.ts b/worker/src/release-reconciliation-diagnostics.test.ts index e2dfc28..438a9e7 100644 --- a/worker/src/release-reconciliation-diagnostics.test.ts +++ b/worker/src/release-reconciliation-diagnostics.test.ts @@ -179,11 +179,11 @@ describe('bounded release reconciliation diagnostics', () => { expect(JSON.stringify(f.log.mock.calls)).not.toContain(CANARY); }); - it('accepts exactly the existing body cap and rejects one byte over with saturated diagnostics', async () => { + it.each([1, 999])('accepts the existing body cap and rejects %i bytes over with saturated diagnostics', async (extraBytes) => { const f = fixture(); const body = validBody + ' '.repeat(LIMIT - validBody.length); expect((await f.run(async () => new Response(body))).failed).toBe(0); f.log.mockClear(); - const next = await f.run(async () => new Response(body + ' '.repeat(999))); + const next = await f.run(async () => new Response(body + ' '.repeat(extraBytes))); expect(next.failed).toBe(1); expect(f.log).toHaveBeenCalledWith('error', 'release_reconciliation.partial_failure', expect.objectContaining({ failureDetails: [{ repositoryId: ID, phase: 'body', failureClass: 'too_large', httpStatus: 200, bodyBytes: LIMIT + 1, bodyBytesSource: 'streamed' }], From 1754344685074b2a821d12cbfd486e8cde91aad6 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 13 Nov 2026 20:50:26 -0500 Subject: [PATCH 3/3] Verify logger transport and refine empty-body diagnostics --- ...release-reconciliation-diagnostics.test.ts | 54 +++++++++++++++++++ worker/src/release-reconciliation.ts | 6 ++- 2 files changed, 58 insertions(+), 2 deletions(-) diff --git a/worker/src/release-reconciliation-diagnostics.test.ts b/worker/src/release-reconciliation-diagnostics.test.ts index 438a9e7..b0eeb90 100644 --- a/worker/src/release-reconciliation-diagnostics.test.ts +++ b/worker/src/release-reconciliation-diagnostics.test.ts @@ -10,6 +10,7 @@ import { componentReleaseCollection, componentReleaseKey } from './component-rel import { RELEASE_CATALOG } from './release-catalog'; import { readReleaseOpsState } from './release-ops-state'; import { runReleaseReconciliation } from './release-reconciliation'; +import { createAppLogger } from './logger'; const ID = '1312512520'; const START = Date.parse('2026-11-14T00:00:00Z'); @@ -114,6 +115,41 @@ describe('bounded release reconciliation diagnostics', () => { expect(f.log).toHaveBeenCalledTimes(1); }); + it('preserves nested failure details through the production tee and Cloudflare logger adapters', async () => { + const sink = vi.spyOn(console, 'error').mockImplementation(() => {}); + const waitUntil = vi.fn<(promise: Promise) => void>(); + try { + await runReleaseReconciliation({ + store: createMemoryStore(), logger: createAppLogger({}, waitUntil), + config: { allowedRepositoryIds: new Set([ID]) }, scheduledTime: START, now: AT, + fetchImpl: async () => new Response(CANARY, { status: 403 }), + }); + expect(sink).toHaveBeenCalledTimes(1); + const expected = { + level: 'error', message: 'release_reconciliation.partial_failure', fields: { + examined: 1, upserted: 0, cleared: 0, notModified: 0, failed: 1, + failureDetails: [{ repositoryId: ID, phase: 'status', failureClass: 'http_status', httpStatus: 403 }], + failureDetailsOmitted: 0, + }, + }; + expect(sink).toHaveBeenCalledWith(expected); + expect(JSON.parse(JSON.stringify(sink.mock.calls[0]![0]))).toEqual(expected); + expect(JSON.stringify(sink.mock.calls)).not.toContain(CANARY); + expect(waitUntil).not.toHaveBeenCalled(); + } finally { + sink.mockRestore(); + } + }); + + it('does not claim that a null 2xx body was streamed', async () => { + const f = fixture(); + expect((await f.run(async () => new Response(null))).failed).toBe(1); + expect(f.log).toHaveBeenCalledWith('error', 'release_reconciliation.partial_failure', expect.objectContaining({ + failureDetails: [{ repositoryId: ID, phase: 'facts', failureClass: 'invalid_release', httpStatus: 200 }], + })); + expect((await readReleaseOpsState(f.base)).lastSuccessfulReconciliationAt).toBeNull(); + }); + it.each([ ['fetch rejection', () => Promise.reject(new Error(CANARY)), { phase: 'fetch', failureClass: 'fetch_rejected' }], ['HTTP refusal', async () => new Response(CANARY, { status: 403, headers: { 'X-Fixture': CANARY } }), { phase: 'status', failureClass: 'http_status', httpStatus: 403 }], @@ -215,4 +251,22 @@ describe('bounded release reconciliation diagnostics', () => { })); expect((await readReleaseOpsState(f.base)).lastSuccessfulReconciliationAt).toBeNull(); }); + + it('includes the final catalog repository when its normal scheduled slot fails', async () => { + const f = fixture(); const tail = RELEASE_CATALOG.at(-1)!; + const fetchImpl = vi.fn(async () => new Response(null, { status: 503 })); + const summary = await runReleaseReconciliation({ + store: f.store, logger: { log: f.log }, + config: { allowedRepositoryIds: new Set(RELEASE_CATALOG.map(entry => entry.repositoryId)) }, + scheduledTime: START + (RELEASE_CATALOG.length - 1) * 60_000, fetchImpl, now: AT, + }); + expect(summary).toEqual({ examined: 1, upserted: 0, cleared: 0, notModified: 0, failed: 1 }); + expect(fetchImpl).toHaveBeenCalledTimes(1); + expect(String(fetchImpl.mock.calls[0]![0])).toContain('/repositories/' + tail.repositoryId + '/releases/latest'); + expect(f.log).toHaveBeenCalledTimes(1); + expect(f.log).toHaveBeenCalledWith('error', 'release_reconciliation.partial_failure', expect.objectContaining({ + failureDetails: [{ repositoryId: tail.repositoryId, phase: 'status', failureClass: 'http_status', httpStatus: 503 }], + failureDetailsOmitted: 0, + })); + }); }); diff --git a/worker/src/release-reconciliation.ts b/worker/src/release-reconciliation.ts index c1bd3bc..a91df79 100644 --- a/worker/src/release-reconciliation.ts +++ b/worker/src/release-reconciliation.ts @@ -26,6 +26,8 @@ const GITHUB_API = 'https://api.github.com'; const REQUEST_TIMEOUT_MS = 10_000; const MAX_RESPONSE_BYTES = 256 * 1024; const USER_AGENT = 'pegma-dev-release-reconciliation'; +// Scheduled invocations examine one repository; only explicit full passes can +// truncate details, with the omitted count retained in the same summary. const MAX_FAILURE_DETAILS = 4; /** Existing summary only: finite public metadata, never error/body/header text. @@ -146,12 +148,12 @@ async function readBoundedJson( return { ok: false, reason: 'too_large' }; } } - failure.bodyBytes = 0; - failure.bodyBytesSource = 'streamed'; const reader = response.body?.getReader(); if (reader === undefined) { return { ok: true, value: null }; } + failure.bodyBytes = 0; + failure.bodyBytesSource = 'streamed'; const chunks: Uint8Array[] = []; let total = 0; for (;;) {