From 095baa779c08c50ff556ff93f3d71e8e967ca018 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Tue, 28 Jul 2026 22:43:44 -0400 Subject: [PATCH 1/3] [D] Invalidate recon ETags when webhooks change projections. Prevents a cached GitHub ETag for an older stable release from 304-masking recon after a missed delete of a later release that a webhook had projected. --- worker/src/github-release-webhook.ts | 9 ++- worker/src/release-ops-state.test.ts | 17 ++++++ worker/src/release-ops-state.ts | 28 ++++++--- worker/src/release-reconciliation.test.ts | 73 +++++++++++++++++++++++ 4 files changed, 119 insertions(+), 8 deletions(-) diff --git a/worker/src/github-release-webhook.ts b/worker/src/github-release-webhook.ts index 09630e7..e7076b0 100644 --- a/worker/src/github-release-webhook.ts +++ b/worker/src/github-release-webhook.ts @@ -342,7 +342,14 @@ export async function handleGitHubReleaseWebhook( await applyReleaseProjection(store, decision); await ledger.markProcessed(deliveryId); try { - await markReleaseWebhookSuccess(store, observedAt); + // Invalidate recon ETag for this repository whenever projection may + // have changed local truth (upsert/delete). Drafts/ignores leave the + // ETag so conditional GETs keep working. + const repositoryId = + decision.kind === 'upsert' || decision.kind === 'delete' + ? facts.repositoryId + : undefined; + await markReleaseWebhookSuccess(store, observedAt, repositoryId); } catch (markerError) { // Projection and ledger are already final; health-marker failure must // not re-enter markFailed or flip the delivery outcome. diff --git a/worker/src/release-ops-state.test.ts b/worker/src/release-ops-state.test.ts index 6a35672..0126852 100644 --- a/worker/src/release-ops-state.test.ts +++ b/worker/src/release-ops-state.test.ts @@ -27,6 +27,23 @@ describe('release ops state', () => { expect(ops.repositoryEtags).toEqual({ '1313911960': '"etag"' }); }); + it('clears a repository ETag when a webhook projects a change', async () => { + const store = createMemoryStore(); + await markReleaseReconciliationSuccess( + store, + '2026-07-28T12:00:00.000Z', + { '1313911960': '"etag-a"', '1312512520': '"keep"' }, + ); + await markReleaseWebhookSuccess( + store, + '2026-07-28T13:00:00.000Z', + '1313911960', + ); + const ops = await readReleaseOpsState(store); + expect(ops.repositoryEtags).toEqual({ '1312512520': '"keep"' }); + expect(ops.lastSuccessfulWebhookAt).toBe('2026-07-28T13:00:00.000Z'); + }); + it('saves etags without claiming reconciliation success', async () => { const store = createMemoryStore(); await saveReleaseRepositoryEtags(store, { a: '1' }); diff --git a/worker/src/release-ops-state.ts b/worker/src/release-ops-state.ts index e887977..facf350 100644 --- a/worker/src/release-ops-state.ts +++ b/worker/src/release-ops-state.ts @@ -93,17 +93,31 @@ export async function readReleaseOpsState(store: Store): Promise { - await store.collection(releaseOpsCollection()).update(opsKey(), (current) => ({ - action: 'write', - value: { - ...(current ?? EMPTY), - lastSuccessfulWebhookAt: at, - }, - })); + await store.collection(releaseOpsCollection()).update(opsKey(), (current) => { + const base = current ?? EMPTY; + const etags = { ...base.repositoryEtags }; + if (typeof repositoryId === 'string' && repositoryId.length > 0) { + delete etags[repositoryId]; + } + return { + action: 'write', + value: { + ...base, + lastSuccessfulWebhookAt: at, + repositoryEtags: etags, + }, + }; + }); } export async function markReleaseReconciliationSuccess( diff --git a/worker/src/release-reconciliation.test.ts b/worker/src/release-reconciliation.test.ts index cbbdd49..12c18e8 100644 --- a/worker/src/release-reconciliation.test.ts +++ b/worker/src/release-reconciliation.test.ts @@ -251,6 +251,79 @@ describe('runReleaseReconciliation', () => { expect(await releases.get(componentReleaseKey(WEBHOOKS_ID))).not.toBeNull(); }); + it('does not 304-mask a missed delete after a later webhook projection', async () => { + const store = createMemoryStore(); + const { markReleaseWebhookSuccess } = await import('./release-ops-state'); + + // Recon caches etag for A. + await runReleaseReconciliation({ + store, + logger, + config: { allowedRepositoryIds: new Set([WEBHOOKS_ID]) }, + now: '2026-07-28T10:00:00.000Z', + fetchImpl: (async () => + new Response( + JSON.stringify({ + id: 100, + tag_name: 'v0.1.0', + published_at: '2026-06-01T00:00:00.000Z', + draft: false, + prerelease: false, + }), + { status: 200, headers: { ETag: '"etag-a"' } }, + )) as unknown as typeof fetch, + }); + + // Webhook later projects B and must drop etag-a. + const releases = store.collection(componentReleaseCollection()); + await releases.update(componentReleaseKey(WEBHOOKS_ID), () => ({ + action: 'write', + value: { + repositoryId: WEBHOOKS_ID, + repositoryName: 'webhooks', + releaseId: '200', + tagName: 'v0.2.0', + publishedAt: '2026-07-20T00:00:00.000Z', + releaseUrl: 'https://github.com/pegma-dev/webhooks/releases/tag/v0.2.0', + observedAt: '2026-07-28T11:00:00.000Z', + }, + })); + await markReleaseWebhookSuccess(store, '2026-07-28T11:00:00.000Z', WEBHOOKS_ID); + + // Missed delete of B: GitHub is A again. Without ETag invalidation this + // would 304 and leave B; with invalidation we re-fetch A. + let sawIfNoneMatch = false; + const summary = await runReleaseReconciliation({ + store, + logger, + config: { allowedRepositoryIds: new Set([WEBHOOKS_ID]) }, + now: NOW, + fetchImpl: (async (_input: RequestInfo | URL, init?: RequestInit) => { + const headers = new Headers(init?.headers); + if (headers.get('If-None-Match')) { + sawIfNoneMatch = true; + } + return new Response( + JSON.stringify({ + id: 100, + tag_name: 'v0.1.0', + published_at: '2026-06-01T00:00:00.000Z', + draft: false, + prerelease: false, + }), + { status: 200, headers: { ETag: '"etag-a"' } }, + ); + }) as unknown as typeof fetch, + }); + + expect(sawIfNoneMatch).toBe(false); + expect(summary.upserted).toBe(1); + expect(await releases.get(componentReleaseKey(WEBHOOKS_ID))).toMatchObject({ + releaseId: '100', + tagName: 'v0.1.0', + }); + }); + it('replaces a local newer release with GitHub preceding stable after delete', async () => { const store = createMemoryStore(); const releases = store.collection(componentReleaseCollection()); From b7badbfaa3582b2546b19164ba086b761aba85bf Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Tue, 28 Jul 2026 22:48:28 -0400 Subject: [PATCH 2/3] [D] Harden ETag invalidation and merge-only recon updates. Invalidate repository ETags on the webhook critical path before markProcessed, and merge recon ETag updates into the live map so concurrent invalidations are not restored. --- worker/src/github-release-webhook.ts | 23 +++++---- worker/src/release-ops-state.test.ts | 37 ++++++++------ worker/src/release-ops-state.ts | 62 ++++++++++++++--------- worker/src/release-reconciliation.test.ts | 7 +-- worker/src/release-reconciliation.ts | 55 ++++++++++---------- 5 files changed, 101 insertions(+), 83 deletions(-) diff --git a/worker/src/github-release-webhook.ts b/worker/src/github-release-webhook.ts index e7076b0..4d929d8 100644 --- a/worker/src/github-release-webhook.ts +++ b/worker/src/github-release-webhook.ts @@ -8,7 +8,10 @@ import { decideReleaseProjection, type ReleaseEventFacts, } from './release-projection'; -import { markReleaseWebhookSuccess } from './release-ops-state'; +import { + invalidateReleaseRepositoryEtag, + markReleaseWebhookSuccess, +} from './release-ops-state'; export const GITHUB_RELEASE_EVENT_TYPE = 'github.release.published'; export const MAX_GITHUB_WEBHOOK_BODY_BYTES = 1024 * 1024; @@ -340,19 +343,17 @@ export async function handleGitHubReleaseWebhook( const observedAt = options.now ?? new Date().toISOString(); const decision = decideReleaseProjection(facts, observedAt); await applyReleaseProjection(store, decision); + // ETag invalidation is correctness-critical (not best-effort): a later + // 304 must not mask a missed delete after this projection change. + if (decision.kind === 'upsert' || decision.kind === 'delete') { + await invalidateReleaseRepositoryEtag(store, facts.repositoryId); + } await ledger.markProcessed(deliveryId); try { - // Invalidate recon ETag for this repository whenever projection may - // have changed local truth (upsert/delete). Drafts/ignores leave the - // ETag so conditional GETs keep working. - const repositoryId = - decision.kind === 'upsert' || decision.kind === 'delete' - ? facts.repositoryId - : undefined; - await markReleaseWebhookSuccess(store, observedAt, repositoryId); + await markReleaseWebhookSuccess(store, observedAt); } catch (markerError) { - // Projection and ledger are already final; health-marker failure must - // not re-enter markFailed or flip the delivery outcome. + // Projection, ETag invalidation, and ledger are already final; health + // marker failure must not re-enter markFailed or flip the delivery. logger.log('error', 'github_release_webhook.ops_marker_failed', { deliveryId, error: diff --git a/worker/src/release-ops-state.test.ts b/worker/src/release-ops-state.test.ts index 0126852..2789f0a 100644 --- a/worker/src/release-ops-state.test.ts +++ b/worker/src/release-ops-state.test.ts @@ -1,22 +1,22 @@ import { createMemoryStore } from '@pegma/storage-core'; import { describe, expect, it } from 'vitest'; import { + invalidateReleaseRepositoryEtag, isReconciliationStale, - markReleaseReconciliationSuccess, markReleaseWebhookSuccess, + mergeReleaseRepositoryEtagUpdates, readReleaseOpsState, RECONCILIATION_STALE_AFTER_MS, - saveReleaseRepositoryEtags, } from './release-ops-state'; describe('release ops state', () => { it('records webhook and reconciliation markers independently', async () => { const store = createMemoryStore(); await markReleaseWebhookSuccess(store, '2026-07-28T10:00:00.000Z'); - await markReleaseReconciliationSuccess( + await mergeReleaseRepositoryEtagUpdates( store, - '2026-07-28T12:00:00.000Z', { '1313911960': '"etag"' }, + '2026-07-28T12:00:00.000Z', ); const ops = await readReleaseOpsState(store); @@ -27,29 +27,34 @@ describe('release ops state', () => { expect(ops.repositoryEtags).toEqual({ '1313911960': '"etag"' }); }); - it('clears a repository ETag when a webhook projects a change', async () => { + it('invalidates a repository ETag without clobbering siblings', async () => { const store = createMemoryStore(); - await markReleaseReconciliationSuccess( + await mergeReleaseRepositoryEtagUpdates( store, - '2026-07-28T12:00:00.000Z', { '1313911960': '"etag-a"', '1312512520': '"keep"' }, + '2026-07-28T12:00:00.000Z', ); - await markReleaseWebhookSuccess( - store, - '2026-07-28T13:00:00.000Z', - '1313911960', - ); + await invalidateReleaseRepositoryEtag(store, '1313911960'); const ops = await readReleaseOpsState(store); expect(ops.repositoryEtags).toEqual({ '1312512520': '"keep"' }); - expect(ops.lastSuccessfulWebhookAt).toBe('2026-07-28T13:00:00.000Z'); + expect(ops.lastSuccessfulReconciliationAt).toBe( + '2026-07-28T12:00:00.000Z', + ); }); - it('saves etags without claiming reconciliation success', async () => { + it('merges etag updates without restoring concurrent invalidations', async () => { const store = createMemoryStore(); - await saveReleaseRepositoryEtags(store, { a: '1' }); + await mergeReleaseRepositoryEtagUpdates( + store, + { a: '1', b: '2' }, + null, + ); + await invalidateReleaseRepositoryEtag(store, 'a'); + // Partial recon only updates b — must not restore a. + await mergeReleaseRepositoryEtagUpdates(store, { b: '2b' }, null); const ops = await readReleaseOpsState(store); + expect(ops.repositoryEtags).toEqual({ b: '2b' }); expect(ops.lastSuccessfulReconciliationAt).toBeNull(); - expect(ops.repositoryEtags).toEqual({ a: '1' }); }); it('classifies reconciliation staleness', () => { diff --git a/worker/src/release-ops-state.ts b/worker/src/release-ops-state.ts index facf350..aa60424 100644 --- a/worker/src/release-ops-state.ts +++ b/worker/src/release-ops-state.ts @@ -94,62 +94,74 @@ export async function readReleaseOpsState(store: Store): Promise { await store.collection(releaseOpsCollection()).update(opsKey(), (current) => { const base = current ?? EMPTY; - const etags = { ...base.repositoryEtags }; - if (typeof repositoryId === 'string' && repositoryId.length > 0) { - delete etags[repositoryId]; + if (!(repositoryId in base.repositoryEtags)) { + return { action: 'keep' }; } + const etags = { ...base.repositoryEtags }; + delete etags[repositoryId]; return { action: 'write', value: { ...base, - lastSuccessfulWebhookAt: at, repositoryEtags: etags, }, }; }); } -export async function markReleaseReconciliationSuccess( +/** Record last successful webhook time only (health detail). */ +export async function markReleaseWebhookSuccess( store: Store, at: string, - repositoryEtags: Readonly>, ): Promise { await store.collection(releaseOpsCollection()).update(opsKey(), (current) => ({ action: 'write', value: { ...(current ?? EMPTY), - lastSuccessfulReconciliationAt: at, - repositoryEtags: { ...repositoryEtags }, + lastSuccessfulWebhookAt: at, }, })); } /** - * Persist advanced per-repo ETags after a partial run without claiming a - * successful reconciliation completion. + * Merge per-repository ETag updates into the live ops map. `null` deletes a + * key; omitted keys are left untouched so concurrent webhook invalidations + * are not restored by a full-map replace. */ -export async function saveReleaseRepositoryEtags( +export async function mergeReleaseRepositoryEtagUpdates( store: Store, - repositoryEtags: Readonly>, + updates: Readonly>, + markSuccessAt: string | null, ): Promise { - await store.collection(releaseOpsCollection()).update(opsKey(), (current) => ({ - action: 'write', - value: { - ...(current ?? EMPTY), - repositoryEtags: { ...repositoryEtags }, - }, - })); + await store.collection(releaseOpsCollection()).update(opsKey(), (current) => { + const base = current ?? EMPTY; + const etags = { ...base.repositoryEtags }; + for (const [repositoryId, value] of Object.entries(updates)) { + if (value === null) { + delete etags[repositoryId]; + } else { + etags[repositoryId] = value; + } + } + return { + action: 'write', + value: { + ...base, + repositoryEtags: etags, + lastSuccessfulReconciliationAt: + markSuccessAt ?? base.lastSuccessfulReconciliationAt, + }, + }; + }); } /** Reconciliation is stale when last success is older than this. */ diff --git a/worker/src/release-reconciliation.test.ts b/worker/src/release-reconciliation.test.ts index 12c18e8..65b153c 100644 --- a/worker/src/release-reconciliation.test.ts +++ b/worker/src/release-reconciliation.test.ts @@ -253,8 +253,6 @@ describe('runReleaseReconciliation', () => { it('does not 304-mask a missed delete after a later webhook projection', async () => { const store = createMemoryStore(); - const { markReleaseWebhookSuccess } = await import('./release-ops-state'); - // Recon caches etag for A. await runReleaseReconciliation({ store, @@ -288,7 +286,10 @@ describe('runReleaseReconciliation', () => { observedAt: '2026-07-28T11:00:00.000Z', }, })); - await markReleaseWebhookSuccess(store, '2026-07-28T11:00:00.000Z', WEBHOOKS_ID); + const { invalidateReleaseRepositoryEtag } = await import( + './release-ops-state' + ); + await invalidateReleaseRepositoryEtag(store, WEBHOOKS_ID); // Missed delete of B: GitHub is A again. Without ETag invalidation this // would 304 and leave B; with invalidation we re-fetch A. diff --git a/worker/src/release-reconciliation.ts b/worker/src/release-reconciliation.ts index 635fb76..47a2b83 100644 --- a/worker/src/release-reconciliation.ts +++ b/worker/src/release-reconciliation.ts @@ -9,9 +9,8 @@ import { type ReleaseCatalogEntry, } from './release-catalog'; import { - markReleaseReconciliationSuccess, + mergeReleaseRepositoryEtagUpdates, readReleaseOpsState, - saveReleaseRepositoryEtags, } from './release-ops-state'; import { applyAuthoritativeCurrentRelease, @@ -284,8 +283,9 @@ export async function runReleaseReconciliation( const observedAt = options.now ?? new Date().toISOString(); const fetchImpl = options.fetchImpl ?? fetch; const catalog = allowedReleaseCatalog(config.allowedRepositoryIds); - const prior = await readReleaseOpsState(store); - const nextEtags: Record = { ...prior.repositoryEtags }; + // Per-repo ETag merges only (never full-map replace) so a concurrent webhook + // invalidation is not restored by this run's end write. + const etagUpdates: Record = {}; let examined = 0; let upserted = 0; @@ -295,6 +295,8 @@ export async function runReleaseReconciliation( for (const entry of catalog) { examined += 1; + // Re-read live ETags each repo so mid-run webhook invalidations apply. + const live = await readReleaseOpsState(store); let result: { readonly outcome: | 'upserted' @@ -308,37 +310,34 @@ export async function runReleaseReconciliation( result = await reconcileOneRepository({ store, entry, - etag: nextEtags[entry.repositoryId], + etag: live.repositoryEtags[entry.repositoryId], observedAt, fetchImpl, }); } catch { // Version conflicts and unexpected store errors stay per-repository so // one hot key cannot abort the catalog pass or skip etag persistence. - result = { outcome: 'failed', etag: nextEtags[entry.repositoryId] }; + result = { outcome: 'failed', etag: undefined }; } - if (result.etag === undefined) { - delete nextEtags[entry.repositoryId]; + if (result.outcome === 'failed') { + failed += 1; + // Leave this repository's ETag untouched in the merge map. + } else if (result.outcome === 'cleared') { + cleared += 1; + etagUpdates[entry.repositoryId] = null; + } else if (result.outcome === 'not_modified') { + notModified += 1; + // No ETag map change; live entry already correct. } else { - nextEtags[entry.repositoryId] = result.etag; - } - - switch (result.outcome) { - case 'upserted': + if (result.outcome === 'upserted') { upserted += 1; - break; - case 'cleared': - cleared += 1; - break; - case 'not_modified': - notModified += 1; - break; - case 'failed': - failed += 1; - break; - default: - break; + } + if (result.etag !== undefined) { + etagUpdates[entry.repositoryId] = result.etag; + } else { + etagUpdates[entry.repositoryId] = null; + } } } @@ -351,9 +350,9 @@ export async function runReleaseReconciliation( }; // Persist success only when every repository completed without failure so - // health "stale" stays honest. Always advance etags for successful repos. + // health "stale" stays honest. Merge ETag updates for successful repos. if (summary.failed === 0) { - await markReleaseReconciliationSuccess(store, observedAt, nextEtags); + await mergeReleaseRepositoryEtagUpdates(store, etagUpdates, observedAt); logger.log('info', 'release_reconciliation.completed', { examined: summary.examined, upserted: summary.upserted, @@ -361,7 +360,7 @@ export async function runReleaseReconciliation( notModified: summary.notModified, }); } else { - await saveReleaseRepositoryEtags(store, nextEtags); + await mergeReleaseRepositoryEtagUpdates(store, etagUpdates, null); logger.log('error', 'release_reconciliation.partial_failure', { examined: summary.examined, upserted: summary.upserted, From 2e50ea98a44c6796c8aa8a5d65f267b7001d6efa Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Tue, 28 Jul 2026 22:52:25 -0400 Subject: [PATCH 3/3] Add per-repo ETag epochs so recon cannot restore stale tags. --- worker/src/release-ops-state.test.ts | 40 ++++++++++--- worker/src/release-ops-state.ts | 86 ++++++++++++++++++++++------ worker/src/release-reconciliation.ts | 27 +++++---- 3 files changed, 114 insertions(+), 39 deletions(-) diff --git a/worker/src/release-ops-state.test.ts b/worker/src/release-ops-state.test.ts index 2789f0a..244c25d 100644 --- a/worker/src/release-ops-state.test.ts +++ b/worker/src/release-ops-state.test.ts @@ -15,7 +15,13 @@ describe('release ops state', () => { await markReleaseWebhookSuccess(store, '2026-07-28T10:00:00.000Z'); await mergeReleaseRepositoryEtagUpdates( store, - { '1313911960': '"etag"' }, + [ + { + repositoryId: '1313911960', + etag: '"etag"', + expectedEpoch: 0, + }, + ], '2026-07-28T12:00:00.000Z', ); @@ -27,34 +33,50 @@ describe('release ops state', () => { expect(ops.repositoryEtags).toEqual({ '1313911960': '"etag"' }); }); - it('invalidates a repository ETag without clobbering siblings', async () => { + it('invalidates a repository ETag and bumps its epoch', async () => { const store = createMemoryStore(); await mergeReleaseRepositoryEtagUpdates( store, - { '1313911960': '"etag-a"', '1312512520': '"keep"' }, + [ + { + repositoryId: '1313911960', + etag: '"etag-a"', + expectedEpoch: 0, + }, + { + repositoryId: '1312512520', + etag: '"keep"', + expectedEpoch: 0, + }, + ], '2026-07-28T12:00:00.000Z', ); await invalidateReleaseRepositoryEtag(store, '1313911960'); const ops = await readReleaseOpsState(store); expect(ops.repositoryEtags).toEqual({ '1312512520': '"keep"' }); + expect(ops.repositoryEtagEpochs['1313911960']).toBe(1); expect(ops.lastSuccessfulReconciliationAt).toBe( '2026-07-28T12:00:00.000Z', ); }); - it('merges etag updates without restoring concurrent invalidations', async () => { + it('does not restore ETags after concurrent invalidation', async () => { const store = createMemoryStore(); await mergeReleaseRepositoryEtagUpdates( store, - { a: '1', b: '2' }, + [{ repositoryId: 'a', etag: '1', expectedEpoch: 0 }], null, ); + // Recon observed epoch 0 for a, then webhook invalidates. await invalidateReleaseRepositoryEtag(store, 'a'); - // Partial recon only updates b — must not restore a. - await mergeReleaseRepositoryEtagUpdates(store, { b: '2b' }, null); + await mergeReleaseRepositoryEtagUpdates( + store, + [{ repositoryId: 'a', etag: 'stale', expectedEpoch: 0 }], + null, + ); const ops = await readReleaseOpsState(store); - expect(ops.repositoryEtags).toEqual({ b: '2b' }); - expect(ops.lastSuccessfulReconciliationAt).toBeNull(); + expect(ops.repositoryEtags).toEqual({}); + expect(ops.repositoryEtagEpochs['a']).toBe(1); }); it('classifies reconciliation staleness', () => { diff --git a/worker/src/release-ops-state.ts b/worker/src/release-ops-state.ts index aa60424..a93f5ff 100644 --- a/worker/src/release-ops-state.ts +++ b/worker/src/release-ops-state.ts @@ -15,23 +15,29 @@ export interface ReleaseOpsState { readonly lastSuccessfulReconciliationAt: string | null; /** Per-repository ETag for GitHub conditional requests (repoId → etag). */ readonly repositoryEtags: Readonly>; + /** + * Per-repository generation bumped on every ETag invalidation so recon + * cannot restore a stale ETag after a concurrent webhook projection. + */ + readonly repositoryEtagEpochs: Readonly>; } type EncodedReleaseOpsState = { readonly lastSuccessfulWebhookAt: StoredValue; readonly lastSuccessfulReconciliationAt: StoredValue; readonly repositoryEtagsJson: StoredValue; + readonly repositoryEtagEpochsJson: StoredValue; }; function opsKey(): EntityKey { return { partition: OPS_PARTITION, id: OPS_ID }; } -function encodeEtags(etags: Readonly>): string { - return JSON.stringify(etags); +function encodeStringMap(map: Readonly>): string { + return JSON.stringify(map); } -function decodeEtags(value: StoredValue): Record { +function decodeStringMap(value: StoredValue): Record { if (typeof value !== 'string' || value.length === 0 || value.length > 32_768) { return {}; } @@ -52,11 +58,37 @@ function decodeEtags(value: StoredValue): Record { } } +function encodeEpochMap(map: Readonly>): string { + return JSON.stringify(map); +} + +function decodeEpochMap(value: StoredValue): Record { + if (typeof value !== 'string' || value.length === 0 || value.length > 32_768) { + return {}; + } + try { + const parsed: unknown = JSON.parse(value); + if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { + return {}; + } + const result: Record = {}; + for (const [key, entry] of Object.entries(parsed)) { + if (typeof entry === 'number' && Number.isSafeInteger(entry) && entry >= 0) { + result[key] = entry; + } + } + return result; + } catch { + return {}; + } +} + function encode(value: ReleaseOpsState): EncodedReleaseOpsState { return { lastSuccessfulWebhookAt: value.lastSuccessfulWebhookAt, lastSuccessfulReconciliationAt: value.lastSuccessfulReconciliationAt, - repositoryEtagsJson: encodeEtags(value.repositoryEtags), + repositoryEtagsJson: encodeStringMap(value.repositoryEtags), + repositoryEtagEpochsJson: encodeEpochMap(value.repositoryEtagEpochs), }; } @@ -70,7 +102,10 @@ function decode(record: StoredRecord): ReleaseOpsState { typeof record['lastSuccessfulReconciliationAt'] === 'string' ? record['lastSuccessfulReconciliationAt'] : null, - repositoryEtags: decodeEtags(record['repositoryEtagsJson'] ?? null), + repositoryEtags: decodeStringMap(record['repositoryEtagsJson'] ?? null), + repositoryEtagEpochs: decodeEpochMap( + record['repositoryEtagEpochsJson'] ?? null, + ), }; } @@ -86,6 +121,7 @@ const EMPTY: ReleaseOpsState = { lastSuccessfulWebhookAt: null, lastSuccessfulReconciliationAt: null, repositoryEtags: {}, + repositoryEtagEpochs: {}, }; export async function readReleaseOpsState(store: Store): Promise { @@ -94,8 +130,8 @@ export async function readReleaseOpsState(store: Store): Promise { await store.collection(releaseOpsCollection()).update(opsKey(), (current) => { const base = current ?? EMPTY; - if (!(repositoryId in base.repositoryEtags)) { - return { action: 'keep' }; - } const etags = { ...base.repositoryEtags }; + const epochs = { ...base.repositoryEtagEpochs }; delete etags[repositoryId]; + epochs[repositoryId] = (epochs[repositoryId] ?? 0) + 1; return { action: 'write', value: { ...base, repositoryEtags: etags, + repositoryEtagEpochs: epochs, }, }; }); @@ -132,24 +168,37 @@ export async function markReleaseWebhookSuccess( })); } +/** One repository ETag update conditioned on the epoch observed at fetch time. */ +export interface ConditionalEtagUpdate { + readonly repositoryId: string; + /** ETag to store, or null to clear. */ + readonly etag: string | null; + /** Epoch value read when reconciliation began this repository. */ + readonly expectedEpoch: number; +} + /** - * Merge per-repository ETag updates into the live ops map. `null` deletes a - * key; omitted keys are left untouched so concurrent webhook invalidations - * are not restored by a full-map replace. + * Merge conditional ETag updates. An update applies only when the live epoch + * still matches `expectedEpoch`, so a concurrent invalidation wins. */ export async function mergeReleaseRepositoryEtagUpdates( store: Store, - updates: Readonly>, + updates: readonly ConditionalEtagUpdate[], markSuccessAt: string | null, ): Promise { await store.collection(releaseOpsCollection()).update(opsKey(), (current) => { const base = current ?? EMPTY; const etags = { ...base.repositoryEtags }; - for (const [repositoryId, value] of Object.entries(updates)) { - if (value === null) { - delete etags[repositoryId]; + const epochs = { ...base.repositoryEtagEpochs }; + for (const update of updates) { + const liveEpoch = epochs[update.repositoryId] ?? 0; + if (liveEpoch !== update.expectedEpoch) { + continue; + } + if (update.etag === null) { + delete etags[update.repositoryId]; } else { - etags[repositoryId] = value; + etags[update.repositoryId] = update.etag; } } return { @@ -157,6 +206,7 @@ export async function mergeReleaseRepositoryEtagUpdates( value: { ...base, repositoryEtags: etags, + repositoryEtagEpochs: epochs, lastSuccessfulReconciliationAt: markSuccessAt ?? base.lastSuccessfulReconciliationAt, }, diff --git a/worker/src/release-reconciliation.ts b/worker/src/release-reconciliation.ts index 47a2b83..f22d034 100644 --- a/worker/src/release-reconciliation.ts +++ b/worker/src/release-reconciliation.ts @@ -11,6 +11,7 @@ import { import { mergeReleaseRepositoryEtagUpdates, readReleaseOpsState, + type ConditionalEtagUpdate, } from './release-ops-state'; import { applyAuthoritativeCurrentRelease, @@ -283,9 +284,8 @@ export async function runReleaseReconciliation( const observedAt = options.now ?? new Date().toISOString(); const fetchImpl = options.fetchImpl ?? fetch; const catalog = allowedReleaseCatalog(config.allowedRepositoryIds); - // Per-repo ETag merges only (never full-map replace) so a concurrent webhook - // invalidation is not restored by this run's end write. - const etagUpdates: Record = {}; + // Epoch-conditioned ETag updates so a concurrent webhook invalidation wins. + const etagUpdates: ConditionalEtagUpdate[] = []; let examined = 0; let upserted = 0; @@ -295,8 +295,9 @@ export async function runReleaseReconciliation( for (const entry of catalog) { examined += 1; - // Re-read live ETags each repo so mid-run webhook invalidations apply. + // Re-read live ETags/epochs each repo so mid-run invalidations apply. const live = await readReleaseOpsState(store); + const expectedEpoch = live.repositoryEtagEpochs[entry.repositoryId] ?? 0; let result: { readonly outcome: | 'upserted' @@ -322,22 +323,24 @@ export async function runReleaseReconciliation( if (result.outcome === 'failed') { failed += 1; - // Leave this repository's ETag untouched in the merge map. } else if (result.outcome === 'cleared') { cleared += 1; - etagUpdates[entry.repositoryId] = null; + etagUpdates.push({ + repositoryId: entry.repositoryId, + etag: null, + expectedEpoch, + }); } else if (result.outcome === 'not_modified') { notModified += 1; - // No ETag map change; live entry already correct. } else { if (result.outcome === 'upserted') { upserted += 1; } - if (result.etag !== undefined) { - etagUpdates[entry.repositoryId] = result.etag; - } else { - etagUpdates[entry.repositoryId] = null; - } + etagUpdates.push({ + repositoryId: entry.repositoryId, + etag: result.etag ?? null, + expectedEpoch, + }); } }