/** * V1-2.1 two-session scenarios on the real stack (contract §15: two saves, * save against submit, publish against withdraw, two publishers, deprecate * against publish, completion against withdrawal), plus archive against * approve (§6.7, audit M1), two deprecations of one sheet (§6.1), two working * copies (§14.3) and revoke against grant (§5.7). Each case holds the lock the * two calls compete for in a blocking session, makes both calls queue behind * it in a known order (checked in pg_stat_activity), lets go, and asserts the * outcome of that serial order; both orders are run where they differ. The * worker of M6 does not exist yet: the verdict and the completion are written * by a postgres session standing in for it (§12.2). Run through * `pnpm db:sandbox test tests/sandbox/sheets-concurrency.sandbox.ts`. */ import { randomUUID } from 'node:crypto' import { readFile } from 'node:fs/promises' import { join } from 'node:path' import { rpc, sql, stack } from './stack' import type { SteppedAccount } from './mfa' import { approvedRound, holder, inOrder, message, ok, openRound, openRoundAcknowledged, officialSheet, session, sessionHolds, sessionWaits, callsWait, sheetDoc, type Sheet, } from './sheet-fixtures' import { repoRoot } from '../db/harness' const HISTORICAL = '503dc301-a8b1-50d4-9e44-0919b2fc2916' let E: SteppedAccount let E2: SteppedAccount let V: SteppedAccount beforeAll(async () => { E = await holder('cc-editor', 'admin', ['sheet_editor', 'sheet_publisher']) E2 = await holder('cc-editor2', 'admin', ['sheet_editor', 'sheet_publisher']) V = await holder('cc-reviewer', null, ['sheet_reviewer']) }, 120_000) const lockVersion = (s: Sheet) => `select 1 from public.anatomical_sheet_versions where id = '${s.draft}' for update` const lockSheet = (id: string) => `select 1 from public.anatomical_sheets where id = '${id}' for update` const save = (who: SteppedAccount, s: Sheet, revision: number, text: string) => () => rpc('save_sheet_draft', { version_id: s.draft, expected_revision: revision, document: sheetDoc(s.asset, text), change_note: text }, who.aal2) const submit = (who: SteppedAccount, s: Sheet, revision: number) => () => rpc('submit_sheet_review', { version_id: s.draft, expected_revision: revision, note: 'r' }, who.aal2) const publish = (who: SteppedAccount, review: string) => () => rpc('publish_sheet_version', { review_id: review }, who.aal2) const withdraw = (who: SteppedAccount, review: string) => () => rpc('withdraw_sheet_review', { review_id: review, note: 'w' }, who.aal2) const deprecate = (who: SteppedAccount, version: string) => () => rpc('deprecate_sheet_version', { version_id: version, reason: 'c' }, who.aal2) const roundStatus = (review: string) => sql(`select status from public.anatomical_sheet_reviews where id = '${review}'`) const versionStatus = (version: string) => sql(`select status from public.anatomical_sheet_versions where id = '${version}'`) const currentOf = (sheet: string) => sql(`select coalesce(current_version_id::text, 'none') from public.anatomical_sheets where id = '${sheet}'`) /** A sheet with v1 published through a round and v2 drafted from it, approved (same digests: covered by the base). */ async function publishedThenApprovedDraft(): Promise<{ s: Sheet; v1: string; v2: Sheet; r2: string }> { const s = await officialSheet(E) ok(await publish(E, await approvedRound(E, V, s))()) const v2draft = ok(await rpc('create_sheet_draft', { sheet_id: s.id, from_version_id: null, change_note: 'v2' }, E.aal2)) as string const v2 = { ...s, draft: v2draft } ok(await save(E, v2, 0, 'v2')()) const r2 = ok(await submit(E, v2, 1)()) as string await openRound(r2, v2) ok(await rpc('decide_sheet_review', { review_id: r2, approve: true, note: 'ok' }, V.aal2)) return { s, v1: s.draft, v2, r2 } } describe('two saves (§6.2)', () => { it('the first save in line wins, the second answers draft_conflict and overwrites nothing', async () => { const s = await officialSheet(E) const [a, b] = await inOrder(lockVersion(s), ['save_sheet_draft', save(E, s, 1, 'first')], ['save_sheet_draft', save(E2, s, 1, 'second')]) expect([a.status, message(b)]).toEqual([200, 'draft_conflict']) expect(await sql(`select revision || ' ' || (content -> 'description' ->> 'fr') from public.anatomical_sheet_versions where id = '${s.draft}'`)) .toBe('2 first') }, 60_000) }) describe('save against submit (§6.1, §6.2)', () => { it('save first: the submission of the old revision answers draft_conflict', async () => { const s = await officialSheet(E) const [a, b] = await inOrder(lockVersion(s), ['save_sheet_draft', save(E, s, 1, 'edit')], ['submit_sheet_review', submit(E2, s, 1)]) expect([a.status, message(b)]).toEqual([200, 'draft_conflict']) expect(await sql(`select count(*) from public.anatomical_sheet_reviews where version_id = '${s.draft}'`)).toBe('0') }, 60_000) it('submit first: the save answers draft.frozen and the round keeps its revision', async () => { const s = await officialSheet(E) const [a, b] = await inOrder(lockVersion(s), ['submit_sheet_review', submit(E, s, 1)], ['save_sheet_draft', save(E2, s, 1, 'late')]) expect([a.status, message(b)]).toEqual([200, 'draft.frozen']) expect(await sql(`select r.revision || ' ' || v.revision from public.anatomical_sheet_reviews r join public.anatomical_sheet_versions v on v.id = r.version_id where r.id = '${a.body}'`)).toBe('1 1') }, 60_000) }) describe('publish against withdraw (§6.1, §6.8)', () => { it('publish first: the round of the published version is never withdrawn', async () => { const s = await officialSheet(E) const r = await approvedRound(E, V, s) const [a, b] = await inOrder(lockVersion(s), ['publish_sheet_version', publish(E, r)], ['withdraw_sheet_review', withdraw(E2, r)]) expect([a.status, message(b)]).toEqual([200, 'draft.not_a_draft']) expect([await versionStatus(s.draft), await roundStatus(r)]).toEqual(['published', 'approved']) }, 60_000) it('withdraw first: the publication finds no approved round', async () => { const s = await officialSheet(E) const r = await approvedRound(E, V, s) const [a, b] = await inOrder(lockVersion(s), ['withdraw_sheet_review', withdraw(E2, r)], ['publish_sheet_version', publish(E, r)]) expect([a.status, message(b)]).toEqual([200, 'publish.review.missing']) expect([await versionStatus(s.draft), await roundStatus(r)]).toEqual(['draft', 'withdrawn']) }, 60_000) }) describe('two publishers (§6.8)', () => { it('one publication only: the second publisher answers draft.not_a_draft', async () => { const s = await officialSheet(E) const r = await approvedRound(E, V, s) const [a, b] = await inOrder(lockSheet(s.id), ['publish_sheet_version', publish(E, r)], ['publish_sheet_version', publish(E2, r)]) expect([a.status, message(b)]).toEqual([200, 'draft.not_a_draft']) expect(await sql(`select published_by || ' ' || (select count(*) from audit.audit_logs where action = 'anatomical_sheet_version.published' and resource_id = '${s.draft}') from public.anatomical_sheet_versions where id = '${s.draft}'`)).toBe(`${E.id} 1`) }, 60_000) }) describe('deprecate against publish (§6.9)', () => { it('deprecate first: the new version becomes current', async () => { const { s, v1, v2, r2 } = await publishedThenApprovedDraft() const [a, b] = await inOrder(lockSheet(s.id), ['deprecate_sheet_version', deprecate(E, v1)], ['publish_sheet_version', publish(E2, r2)]) expect([a.status, b.status]).toEqual([200, 200]) expect([await currentOf(s.id), await versionStatus(v1), await versionStatus(v2.draft)]).toEqual([v2.draft, 'deprecated', 'published']) }, 120_000) it('publish first: the deprecation of the old version keeps the new one current', async () => { const { s, v1, v2, r2 } = await publishedThenApprovedDraft() const [a, b] = await inOrder(lockSheet(s.id), ['publish_sheet_version', publish(E2, r2)], ['deprecate_sheet_version', deprecate(E, v1)]) expect([a.status, b.status]).toEqual([200, 200]) expect([await currentOf(s.id), await versionStatus(v1), await versionStatus(v2.draft)]).toEqual([v2.draft, 'deprecated', 'published']) }, 120_000) }) describe('two deprecations of one sheet (§6.1, §6.9)', () => { it('serialised on the sheet: the current version never names a deprecated one', async () => { const { s, v1, r2 } = await publishedThenApprovedDraft() const v2 = (await sql(`select version_id from public.anatomical_sheet_reviews where id = '${r2}'`)) ok(await publish(E, r2)()) const [a, b] = await inOrder(lockSheet(s.id), ['deprecate_sheet_version', deprecate(E, v2)], ['deprecate_sheet_version', deprecate(E2, v1)]) expect([a.status, b.status]).toEqual([200, 200]) expect([await currentOf(s.id), await versionStatus(v1), await versionStatus(v2)]).toEqual(['none', 'deprecated', 'deprecated']) }, 120_000) }) describe('completion against withdrawal (§6.4, §6.5)', () => { // The completion the worker will run (M6): lock the round while it is // verifying, write the verdict and open it; a round no longer verifying is // left alone. Returns 'updated' when it wrote. const completion = (review: string, s: Sheet, pause: string) => ` select id from public.anatomical_sheet_reviews where id = '${review}' and status = 'verifying' for update; ${pause}; update public.anatomical_sheet_reviews set status = 'open', verified_at = now(), verified_with = 'stand-in', verdict = '${JSON.stringify({ fingerprint: 'a'.repeat(64), drawings: [{ asset_id: s.asset, sha256: s.sha }], groups: [] })}'::jsonb where id = '${review}' and status = 'verifying' returning 'updated'` it('completion first: the withdrawal waits, then withdraws the opened round; the draft unfreezes', async () => { const s = await officialSheet(E) const r = ok(await submit(E, s, 1)()) as string const tag = `sandbox-worker-${randomUUID().slice(0, 8)}` const worker = session(tag, completion(r, s, 'select pg_sleep(2)')) await sessionHolds(tag) const w = withdraw(E2, r)() await callsWait('withdraw_sheet_review') expect(await worker).toContain('updated') expect((await w).status).toBe(200) expect([await roundStatus(r), await sql(`select verdict is not null from public.anatomical_sheet_reviews where id = '${r}'`)]) .toEqual(['withdrawn', 't']) expect((await save(E, s, 1, 'after')()).status).toBe(200) }, 60_000) it('withdrawal first: the completion finds no verifying round and writes nothing', async () => { const s = await officialSheet(E) const r = ok(await submit(E, s, 1)()) as string const blockerTag = `sandbox-blocker-${randomUUID().slice(0, 8)}` const blocker = session(blockerTag, `select 1 from public.anatomical_sheet_reviews where id = '${r}' for update; select pg_sleep(3)`) await sessionHolds(blockerTag) const w = withdraw(E2, r)() await callsWait('withdraw_sheet_review') const tag = `sandbox-worker-${randomUUID().slice(0, 8)}` const worker = session(tag, completion(r, s, 'select 1')) await sessionWaits(tag) await blocker expect((await w).status).toBe(200) expect(await worker).not.toContain('updated') expect([await roundStatus(r), await sql(`select verdict is null from public.anatomical_sheet_reviews where id = '${r}'`)]) .toEqual(['withdrawn', 't']) expect((await save(E, s, 1, 'after')()).status).toBe(200) }, 60_000) }) describe('archive against approve (§6.7, audit M1)', () => { it('archive first: the approval answers sheet.inactive and the round stays open', async () => { const s = await officialSheet(E) const r = await openRoundAcknowledged(E, V, s) const [a, b] = await inOrder(lockSheet(s.id), ['archive_anatomical_sheet', () => rpc('archive_anatomical_sheet', { sheet_id: s.id }, E.aal2)], ['decide_sheet_review', () => rpc('decide_sheet_review', { review_id: r, approve: true, note: 'ok' }, V.aal2)]) expect([a.status, message(b)]).toEqual([200, 'sheet.inactive']) expect(await roundStatus(r)).toBe('open') }, 60_000) it('approve first: the approval happened on an active sheet, the archive follows', async () => { const s = await officialSheet(E) const r = await openRoundAcknowledged(E, V, s) const [a, b] = await inOrder(lockSheet(s.id), ['decide_sheet_review', () => rpc('decide_sheet_review', { review_id: r, approve: true, note: 'ok' }, V.aal2)], ['archive_anatomical_sheet', () => rpc('archive_anatomical_sheet', { sheet_id: s.id }, E.aal2)]) expect([a.status, b.status]).toEqual([200, 200]) expect(await roundStatus(r)).toBe('approved') }, 60_000) }) describe('two working copies of the historical sheet (§14.3)', () => { let setAside: string[] = [] const created: string[] = [] beforeAll(async () => { // The historical drawing confirmed by the operator path, as on DEV (§9.5): // the object written with the service key, the row confirmed by the // service role. Done once per stack; a confirmed row is left as it is. const row = (await sql(`select id || ' ' || sha256 || ' ' || (uploaded_at is null)::text from public.anatomical_sheet_assets where sheet_id = '${HISTORICAL}'`)).split(' ') if (row[2] === 'true') { const bytes = await readFile(join(repoRoot, 'supabase/seed/anatomical-sheets/equine/draft/assets/horse.svg')) const res = await fetch(`${stack.storageUrl}/object/anatomical-sheet-assets/${row[1]}.svg`, { method: 'POST', headers: { Authorization: `Bearer ${stack.serviceKey}`, 'Content-Type': 'image/svg+xml' }, body: new Uint8Array(bytes), }) // Storage reports an existing object as HTTP 400 with statusCode "409" in the body. const body = await res.text() const duplicate = res.status === 400 && (JSON.parse(body) as { statusCode?: string }).statusCode === '409' expect(res.status === 200 || res.status === 409 || duplicate, `${res.status} ${body}`).toBe(true) ok(await rpc('confirm_sheet_asset_upload', { asset_id: row[0] }, stack.serviceKey)) } // A copy left active by an earlier run is set aside and put back after. setAside = (await sql(`update public.anatomical_sheets set status = 'archived', archived_at = now() where status = 'active' and private.is_historical_working_copy(id) returning id`)) .split('\n').filter(Boolean) }, 60_000) afterAll(async () => { for (const id of created) await rpc('archive_anatomical_sheet', { sheet_id: id }, E.aal2) if (setAside.length > 0) await sql(`update public.anatomical_sheets set status = 'active', archived_at = null where id in (${setAside.map((id) => `'${id}'`).join(', ')})`) }) it('serialised on the historical sheet row: one copy, the other answers working_copy.exists', async () => { const source = await sql(`select id from public.anatomical_sheet_versions where sheet_id = '${HISTORICAL}'`) const copy = (who: SteppedAccount) => () => rpc('create_sheet_working_copy', { source_version_id: source, slug: `wc-${randomUUID().slice(0, 12)}` }, who.aal2) const [a, b] = await inOrder(`select 1 from public.anatomical_sheets where id = '${HISTORICAL}' for no key update`, ['create_sheet_working_copy', copy(E)], ['create_sheet_working_copy', copy(E2)]) if (a.status === 200) created.push(a.body as string) if (b.status === 200) created.push(b.body as string) expect([a.status, message(b)]).toEqual([200, 'working_copy.exists']) }, 60_000) }) describe('revoke against grant of platform roles (§5.7, F18)', () => { const lock = `select pg_advisory_xact_lock(hashtextextended('faunosteo.platform_roles', 0))` let accounts: SteppedAccount[] = [] afterAll(async () => { if (accounts.length > 0) await sql(`delete from auth.users where id in (${accounts.map((a) => `'${a.id}'`).join(', ')})`) }) it('revoke first: the revoked owner can no longer grant', async () => { const a = await holder('rg-a', 'owner', []) const b = await holder('rg-b', 'owner', []) const c = await holder('rg-c', null, []) accounts = accounts.concat([a, b, c]) const [revoke, grant] = await inOrder(lock, ['revoke_platform_role', () => rpc('revoke_platform_role', { target_user_id: b.id, role: 'owner', reason: 'race' }, a.aal2)], ['grant_platform_role', () => rpc('grant_platform_role', { target_user_id: c.id, role: 'support' }, b.aal2)]) expect([revoke.status, grant.status, message(grant)]).toEqual([200, 403, 'forbidden']) expect(await sql(`select count(*) from public.profile_roles where user_id = '${c.id}' and revoked_at is null`)).toBe('0') }, 60_000) it('grant first: the grant was made by an owner, then the revocation applies', async () => { const a = await holder('rg-a', 'owner', []) const b = await holder('rg-b', 'owner', []) const c = await holder('rg-c', null, []) accounts = accounts.concat([a, b, c]) const [grant, revoke] = await inOrder(lock, ['grant_platform_role', () => rpc('grant_platform_role', { target_user_id: c.id, role: 'support' }, b.aal2)], ['revoke_platform_role', () => rpc('revoke_platform_role', { target_user_id: b.id, role: 'owner', reason: 'race' }, a.aal2)]) expect([grant.status, revoke.status]).toEqual([200, 200]) expect(await sql(`select string_agg(role::text, ',') from public.profile_roles where user_id = '${c.id}' and revoked_at is null`)) .toBe('support') }, 60_000) })