Adversarial re-review of df275bb found the two-guard ready-flip fix still left a
narrow double-race open, plus test-hygiene drift from the banUser param removal.
MED — residual stale-keepsake race the `export_released_at` guard alone missed
The flip relied on two guards defeating two clearers: the `release_seq` EXISTS
check (vs a re-release bump) and `export_released_at IS NOT NULL` (vs open_event's
clear). But release_gallery re-arms `export_released_at = NOW()` and bumps
`release_seq` as SEPARATE statements, so a stale worker's flip landing in the gap
between them satisfies BOTH guards (released re-armed, seq not yet bumped) and
resurrects a pre-reopen keepsake — the next re-release then skips regeneration and
serves an archive missing the reopen-window uploads.
Root-cause fix: `open_event` now bumps every `export_job.release_seq`, making a
reopen a supersession point symmetric with a re-release. A worker that captured the
pre-reopen seq can never match its `release_seq`-guarded finalize/flip again,
regardless of when the re-release re-arms `export_released_at`. The released-anchor
guard stays as defense-in-depth. Added a deterministic e2e asserting the reopen
bumps the seq (the invariant that closes the race without depending on
sub-millisecond worker timing).
LOW
- Gate the `export-progress: 100` SSE + `prune_stale_export_files` on the ready-flip
actually flipping (rows_affected > 0). A superseded worker no longer advertises a
misleading 100% or prunes on a fresh generation's behalf.
- moderation.spec.ts: the two ban tests had become byte-identical after the
hide_uploads param removal; drop the one whose "hide_uploads=true" title no longer
matched what it exercised, keep the accurate "always hides" test.
- host-dashboard page-object: drop the dead `banUser(hideUploads)` param + its
checkbox branch (the UI no longer renders that checkbox — a latent hang trap).
- sse-eviction.spec.ts: rename the test whose title referenced the removed flag.
Verified: backend 40 tests, e2e 156 passed / 1 skipped on chromium-desktop
(incl. the new reopen-supersession regression).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
269 lines
13 KiB
TypeScript
269 lines
13 KiB
TypeScript
/**
|
|
* Regression guard — reopen→re-release export integrity + the stale-keepsake data-loss fix (H1).
|
|
*
|
|
* Two related bugs on this path:
|
|
*
|
|
* (1) Temp-file race: a second worker spawned by a re-release could stomp the first
|
|
* worker's FIXED temp path → a corrupt/truncated keepsake ZIP.
|
|
*
|
|
* (2) Stale keepsake (silent data loss): a worker from the PRIOR release, still streaming a
|
|
* snapshot taken BEFORE a reopen, would finish and unconditionally re-flip
|
|
* `export_*_ready = TRUE` on an archive that predated the reopen — so uploads added
|
|
* during the reopen window were permanently missing from a "ready" keepsake.
|
|
*
|
|
* The fix: a per-(event,type) generation counter `release_seq`, bumped on every (re)release.
|
|
* A worker captures the seq it claimed and writes per-generation temp/final paths
|
|
* (`Gallery.<seq>.zip`); its finalize and ready-flag flip are guarded by `release_seq`, so a
|
|
* superseded worker discards its output instead of resurrecting a stale keepsake. The
|
|
* download follows the current `done` row's `file_path`, never a fixed name.
|
|
*
|
|
* A second, narrower window on the SAME class of bug (fixed alongside): a reopen (`open_event`)
|
|
* landing between a *current* worker's `finalize_job` and its ready-flag flip could resurrect
|
|
* `export_zip_ready=TRUE` on a pre-reopen snapshot, and the next re-release would
|
|
* `if ready { continue }` and skip regeneration. Two layers close it: (1) `open_event` now bumps
|
|
* every `export_job.release_seq`, so a reopen is itself a supersession point — a stale worker's
|
|
* captured seq no longer matches its `release_seq`-guarded flip; (2) the flip UPDATEs are also
|
|
* anchored on `export_released_at IS NOT NULL` as belt-and-suspenders. Layer (1) is what defeats
|
|
* the double-race where a re-release re-arms `export_released_at` before it bumps the seq.
|
|
*
|
|
* Coverage:
|
|
* - churn integrity: rapid reopen→re-release yields exactly one INTACT ZIP, no stuck jobs.
|
|
* - completeness: an upload added during the reopen window IS present in the re-released
|
|
* keepsake (the direct data-loss regression).
|
|
* - supersession (re-release): a re-release SUPERSEDES an in-flight (running) job — it bumps the
|
|
* generation and regenerates, rather than leaving the stale worker to finalize.
|
|
* - supersession (reopen): a reopen ALONE bumps the generation, so a worker holding the
|
|
* pre-reopen seq can never flip a stale ready flag (closes the finalize↔flip double-race
|
|
* deterministically, without depending on sub-millisecond worker timing).
|
|
*/
|
|
import { test, expect } from '../../fixtures/test';
|
|
import { Client } from 'pg';
|
|
import { execFileSync } from 'node:child_process';
|
|
import { writeFileSync, mkdtempSync, readFileSync } from 'node:fs';
|
|
import { tmpdir } from 'node:os';
|
|
import { join } from 'node:path';
|
|
import { seedUpload } from '../../helpers/seed';
|
|
import { uploadRaw } from '../../helpers/upload-client';
|
|
|
|
const BASE = process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101';
|
|
const SLUG = 'e2e-test-event';
|
|
const N_UPLOADS = 6;
|
|
|
|
const PG = {
|
|
host: process.env.E2E_DB_HOST ?? 'localhost',
|
|
port: Number(process.env.E2E_DB_PORT ?? '55432'),
|
|
user: process.env.E2E_DB_USER ?? 'eventsnap_test',
|
|
password: process.env.E2E_DB_PASSWORD ?? 'eventsnap_test',
|
|
database: process.env.E2E_DB_NAME ?? 'eventsnap_test',
|
|
};
|
|
|
|
async function pgQuery<T = any>(sql: string): Promise<T[]> {
|
|
const c = new Client(PG);
|
|
await c.connect();
|
|
try {
|
|
return (await c.query(sql)).rows as T[];
|
|
} finally {
|
|
await c.end();
|
|
}
|
|
}
|
|
|
|
function post(path: string, jwt: string) {
|
|
return fetch(BASE + path, { method: 'POST', headers: { Authorization: `Bearer ${jwt}` } });
|
|
}
|
|
|
|
async function exportStatus(jwt: string): Promise<any> {
|
|
const res = await fetch(BASE + '/api/v1/export/status', { headers: { Authorization: `Bearer ${jwt}` } });
|
|
return res.json();
|
|
}
|
|
|
|
async function mintTicket(jwt: string): Promise<string> {
|
|
const res = await post('/api/v1/export/ticket', jwt);
|
|
return (await res.json()).ticket;
|
|
}
|
|
|
|
async function waitExportDone(jwt: string) {
|
|
await expect
|
|
.poll(async () => {
|
|
const s = await exportStatus(jwt);
|
|
return s.released === true && s.zip?.status === 'done' && s.html?.status === 'done';
|
|
}, { timeout: 60_000, intervals: [500] })
|
|
.toBe(true);
|
|
}
|
|
|
|
/** Download the current ZIP keepsake and return its (non-directory) entry names. */
|
|
async function downloadZipEntries(jwt: string): Promise<string[]> {
|
|
const ticket = await mintTicket(jwt);
|
|
const res = await fetch(BASE + '/api/v1/export/zip?ticket=' + encodeURIComponent(ticket));
|
|
expect(res.status).toBe(200);
|
|
const bytes = Buffer.from(await res.arrayBuffer());
|
|
expect(bytes.subarray(0, 2).toString('latin1')).toBe('PK'); // ZIP magic — not a stomped file
|
|
const dir = mkdtempSync(join(tmpdir(), 'es-zip-'));
|
|
const zipPath = join(dir, 'Gallery.zip');
|
|
writeFileSync(zipPath, bytes);
|
|
execFileSync('unzip', ['-t', zipPath], { stdio: 'pipe' }); // CRC integrity; throws on corruption
|
|
return execFileSync('unzip', ['-Z1', zipPath], { encoding: 'utf8' })
|
|
.split('\n')
|
|
.map((l) => l.trim())
|
|
.filter((l) => l.length > 0 && !l.endsWith('/'));
|
|
}
|
|
|
|
async function zipReleaseSeq(): Promise<number> {
|
|
const [row] = await pgQuery<{ release_seq: string }>(
|
|
`SELECT ej.release_seq FROM export_job ej JOIN event e ON e.id = ej.event_id
|
|
WHERE e.slug = '${SLUG}' AND ej.type = 'zip'`
|
|
);
|
|
return Number(row.release_seq);
|
|
}
|
|
|
|
test.describe('Flow re-review — reopen→re-release export integrity + stale-keepsake (H1)', () => {
|
|
// The real export job runs image processing; give it head-room over the tiny fixtures.
|
|
test.setTimeout(120_000);
|
|
|
|
test('rapid release/reopen/re-release yields exactly one INTACT ZIP and no stuck jobs', async ({
|
|
host,
|
|
}) => {
|
|
// Seed real, decodable uploads while the event is open.
|
|
for (let i = 0; i < N_UPLOADS; i++) {
|
|
await seedUpload(host.jwt, { caption: `pic ${i}` });
|
|
}
|
|
|
|
// First release → export starts and uploads lock (release ⇒ lock).
|
|
expect((await post('/api/v1/host/gallery/release', host.jwt)).status).toBe(204);
|
|
|
|
// Post-release uploads must be rejected (belt-and-suspenders on top of the lock).
|
|
const rejected = await uploadRaw(host.jwt, readFileSync(join(process.cwd(), 'fixtures', 'media', 'sample.jpg')), {
|
|
filename: 'late.jpg',
|
|
contentType: 'image/jpeg',
|
|
});
|
|
expect(rejected.status).toBe(403);
|
|
|
|
// Churn: reopen (clears release + ready flags) then re-release, several times in
|
|
// quick succession. This is the path that used to be able to double-spawn workers
|
|
// over the shared temp file. End on a release so the gallery is left released.
|
|
for (let i = 0; i < 4; i++) {
|
|
expect((await post('/api/v1/host/event/open', host.jwt)).status).toBe(204);
|
|
const rel = await post('/api/v1/host/gallery/release', host.jwt);
|
|
expect(rel.status).toBe(204);
|
|
}
|
|
|
|
await waitExportDone(host.jwt);
|
|
|
|
// No export_job may be left stuck 'running'.
|
|
const jobs = await pgQuery<{ type: string; status: string }>(
|
|
`SELECT ej.type::text AS type, ej.status::text AS status
|
|
FROM export_job ej JOIN event e ON e.id = ej.event_id
|
|
WHERE e.slug = '${SLUG}'`
|
|
);
|
|
expect(jobs.length).toBe(2);
|
|
for (const j of jobs) expect(j.status, `${j.type} job status`).toBe('done');
|
|
|
|
// Exactly one entry per seeded upload — no entry lost to a stomped temp file, none
|
|
// duplicated by a second worker.
|
|
const listing = await downloadZipEntries(host.jwt);
|
|
expect(listing.length, `zip entries:\n${listing.join('\n')}`).toBe(N_UPLOADS);
|
|
});
|
|
|
|
test('an upload added during the reopen window IS present in the re-released keepsake (H1)', async ({
|
|
host,
|
|
}) => {
|
|
// Release an initial keepsake of 3 uploads.
|
|
for (let i = 0; i < 3; i++) await seedUpload(host.jwt, { caption: `orig ${i}` });
|
|
expect((await post('/api/v1/host/gallery/release', host.jwt)).status).toBe(204);
|
|
await waitExportDone(host.jwt);
|
|
expect((await downloadZipEntries(host.jwt)).length).toBe(3);
|
|
|
|
// Reopen (invalidates the release) → add a 4th upload while unlocked → re-release.
|
|
expect((await post('/api/v1/host/event/open', host.jwt)).status).toBe(204);
|
|
await seedUpload(host.jwt, { caption: 'added-during-reopen' });
|
|
expect((await post('/api/v1/host/gallery/release', host.jwt)).status).toBe(204);
|
|
await waitExportDone(host.jwt);
|
|
|
|
// The re-released keepsake MUST contain all 4 — the stale-keepsake bug would have left
|
|
// the download at the pre-reopen snapshot of 3, silently dropping the new upload.
|
|
const listing = await downloadZipEntries(host.jwt);
|
|
expect(listing.length, `zip entries:\n${listing.join('\n')}`).toBe(4);
|
|
});
|
|
|
|
test('re-release SUPERSEDES an in-flight (running) export — bumps the generation', async ({
|
|
host,
|
|
}) => {
|
|
// Deterministic proof of the generation guard, independent of export timing. We pin the
|
|
// zip job to `running` with a sentinel to mimic a worker from a prior release that is
|
|
// still mid-export, then drive reopen→re-release.
|
|
//
|
|
// OLD behavior (the bug): the re-enqueue left a `running` row alone, so the stale worker
|
|
// would eventually finalize and re-flip the ready flag on its pre-reopen snapshot.
|
|
// NEW behavior (the fix): the re-enqueue bumps `release_seq` and resets the row, so the
|
|
// stale generation is superseded — its sentinel is wiped and a fresh worker regenerates.
|
|
await seedUpload(host.jwt, { caption: 'a' });
|
|
await seedUpload(host.jwt, { caption: 'b' });
|
|
|
|
expect((await post('/api/v1/host/gallery/release', host.jwt)).status).toBe(204);
|
|
await waitExportDone(host.jwt);
|
|
const seqBefore = await zipReleaseSeq();
|
|
|
|
// Simulate an in-flight worker owning the zip job at the current generation.
|
|
await pgQuery(
|
|
`UPDATE export_job ej SET status = 'running', progress_pct = 77
|
|
FROM event e
|
|
WHERE e.id = ej.event_id AND e.slug = '${SLUG}' AND ej.type = 'zip'`
|
|
);
|
|
|
|
// Reopen (clears release + ready flags AND bumps every export_job's release_seq) then
|
|
// re-release (bumps + resets again). Either bump alone supersedes the pinned running row.
|
|
expect((await post('/api/v1/host/event/open', host.jwt)).status).toBe(204);
|
|
expect((await post('/api/v1/host/gallery/release', host.jwt)).status).toBe(204);
|
|
|
|
// The fresh generation must settle to done at a HIGHER release_seq — proving the stale
|
|
// running row was superseded (not left to finalize) and the sentinel is gone.
|
|
await waitExportDone(host.jwt);
|
|
const [row] = await pgQuery<{ status: string; progress_pct: number; release_seq: string }>(
|
|
`SELECT ej.status::text AS status, ej.progress_pct, ej.release_seq
|
|
FROM export_job ej JOIN event e ON e.id = ej.event_id
|
|
WHERE e.slug = '${SLUG}' AND ej.type = 'zip'`
|
|
);
|
|
expect(row.status, 'zip job status').toBe('done');
|
|
expect(Number(row.progress_pct), 'zip job progress').toBe(100);
|
|
expect(Number(row.release_seq), 'release_seq advanced past the superseded generation').toBeGreaterThan(
|
|
seqBefore
|
|
);
|
|
});
|
|
|
|
test('a reopen ALONE bumps release_seq — a pre-reopen worker can never flip a stale ready flag', async ({
|
|
host,
|
|
}) => {
|
|
// Deterministic proof of the reopen-supersession that closes the finalize↔flip double-race.
|
|
// The nasty interleaving (worker finalized `done@S`, THEN reopen, THEN a re-release re-arms
|
|
// `export_released_at` BEFORE it bumps the seq, THEN the stale worker's flip runs and both
|
|
// guards pass) can't be forced by sub-millisecond timing — but its ROOT cause is observable:
|
|
// whether a reopen retires the current generation's seq. If it does, the seq the worker
|
|
// captured (S) is gone for good, so its `release_seq = S`-guarded flip matches nothing no
|
|
// matter when it lands. We assert exactly that invariant.
|
|
await seedUpload(host.jwt, { caption: 'x' });
|
|
expect((await post('/api/v1/host/gallery/release', host.jwt)).status).toBe(204);
|
|
await waitExportDone(host.jwt);
|
|
const seqAtRelease = await zipReleaseSeq();
|
|
|
|
// Reopen only — no re-release. The export_job row is left `done` at the OLD seq by the old
|
|
// code; the fix bumps it here.
|
|
expect((await post('/api/v1/host/event/open', host.jwt)).status).toBe(204);
|
|
|
|
const seqAfterReopen = await zipReleaseSeq();
|
|
expect(
|
|
seqAfterReopen,
|
|
'reopen must bump export_job.release_seq so a pre-reopen worker (seq=' +
|
|
seqAtRelease +
|
|
') is superseded and can never flip a stale ready flag'
|
|
).toBeGreaterThan(seqAtRelease);
|
|
|
|
// And the reopen must have cleared readiness (belt-and-suspenders: the stale worker also
|
|
// can't satisfy `export_released_at IS NOT NULL`).
|
|
const [ev] = await pgQuery<{ zip_ready: boolean; released_at: string | null }>(
|
|
`SELECT export_zip_ready AS zip_ready, export_released_at AS released_at
|
|
FROM event WHERE slug = '${SLUG}'`
|
|
);
|
|
expect(ev.zip_ready, 'reopen clears zip readiness').toBe(false);
|
|
expect(ev.released_at, 'reopen clears the release timestamp').toBeNull();
|
|
});
|
|
});
|