import { afterEach, describe, expect, test } from 'bun:test'; import { parseFinancialDecimal } from '@stock-bot/types'; import { compareEventKeys } from '../../apps/stock/orchestrator/src/execution/canonical-paper'; import { CanonicalPaperExecution } from '../../apps/stock/orchestrator/src/execution/CanonicalPaperExecution'; import { counterProgram, quoteInput } from '../fixtures/canonical-paper'; import { paperConfig, paperFixture, paperFrame } from '../fixtures/paper-runtime'; const connection = { sourceId: 'fixture', connectionId: 'one' }; test('host event keys preserve Rust UTF-8 instrument ordering for supplementary Unicode', () => { const key = { at: 1, phase: 'Execution' as const, sourceSequence: 1 }; expect( compareEventKeys({ ...key, instrumentId: '\u{10000}' }, { ...key, instrumentId: '\ue000' }) ).toBeGreaterThan(0); }); const cleanup: (() => Promise)[] = []; afterEach(async () => { for (const close of cleanup.splice(0).reverse()) { await close(); } }); async function fixture(config = paperConfig(), program = counterProgram()) { const f = await paperFixture(config, program); cleanup.push(f.close); return f; } async function start(f: Awaited>) { await f.runtime.connect(connection); expect((await f.runtime.ingest(paperFrame(1))).disposition).toBe('health-only'); await f.runtime.activate({ recoverPending: false }); } function deferred() { let resolve!: () => void; const promise = new Promise(done => { resolve = done; }); return { promise, resolve }; } describe.skipIf(!process.env.PIPELINE_TEST_DATABASE_URL)( 'controlled canonical paper on real PostgreSQL', () => { test('requires initial activation, retains inactive retry disposition, and freezes active retries after halt', async () => { const f = await fixture(); const initial = await f.runtime.status(); expect(initial).toMatchObject({ active: false, ready: false, connected: false, operatorHalted: true, }); await start(f); expect(await f.runtime.ingest(paperFrame(1))).toMatchObject({ duplicate: true, disposition: 'health-only', }); expect((await f.snapshot()).account.inputSequence).toBe(0); f.clock(20); const frame = paperFrame(2); expect((await f.runtime.ingest(frame)).disposition).toBe('admitted'); const before = await f.snapshot(); expect(before.owners[0]!.diagnostic.nextDecisionSequence).toBe(1); await f.runtime.halt('human stop'); expect(await f.runtime.ingest(frame)).toMatchObject({ duplicate: true, disposition: 'admitted', readiness: { active: false, operatorHalted: true }, }); expect((await f.snapshot()).account.checkpoint).toEqual(before.account.checkpoint); f.clock(30); expect((await f.runtime.ingest(paperFrame(3))).disposition).toBe('health-only'); expect((await f.snapshot()).owners).toEqual(before.owners); }); test('persists halt and fences all stale-generation controls, ingestion and shutdown after replacement', async () => { const f = await fixture(); await start(f); await f.runtime.halt('persist me'); const replacement = await f.make(); expect(await replacement.status()).toMatchObject({ active: false, connected: false, operatorHalted: true, }); f.clock(20); await expect(f.runtime.ingest(paperFrame(2))).rejects.toThrow('generation'); await expect(f.runtime.activate({ recoverPending: true })).rejects.toThrow('generation'); await expect(f.runtime.shutdown()).rejects.toThrow('generation'); await expect( (f.runtime as unknown as { execution: CanonicalPaperExecution }).execution.drain() ).rejects.toThrow('generation'); await replacement.connect({ ...connection, connectionId: 'two' }); f.clock(20); await replacement.ingest(paperFrame(2, 20, 'two')); await replacement.activate({ recoverPending: false }); expect(await replacement.status()).toMatchObject({ active: true, connected: true, operatorHalted: false, }); await replacement.disconnect(connection); expect((await replacement.status()).active).toBe(true); await replacement.connect({ ...connection, connectionId: 'two' }); expect((await replacement.status()).active).toBe(true); await replacement.connect({ ...connection, connectionId: 'three' }); expect(await replacement.status()).toMatchObject({ active: false, connected: true, ready: false, }); }); test('long idle then a fresh frame revokes activation without a preceding status poll', async () => { const f = await fixture(); await start(f); f.clock(200); const result = await f.runtime.ingest(paperFrame(2, 200)); expect(result).toMatchObject({ disposition: 'health-only', readiness: { active: false } }); expect((await f.snapshot()).account.inputSequence).toBe(0); await f.runtime.activate({ recoverPending: false }); expect((await f.runtime.status()).active).toBe(true); }); test('frame inputs, health and receipts commit atomically and conflicting retries cannot alter them', async () => { const f = await fixture(); await start(f); const before = await f.snapshot(); let writes = 0; f.wrap(tx => ({ ...tx, async putInput(input) { if (++writes === 2) { throw new Error('atomic enqueue failure'); } await tx.putInput(input); }, })); f.clock(20); await expect(f.runtime.ingest(paperFrame(2))).rejects.toThrow('atomic enqueue failure'); expect((await f.snapshot()).account).toEqual(before.account); f.wrap(tx => tx); expect(await f.runtime.ingest(paperFrame(2))).toMatchObject({ duplicate: false, disposition: 'admitted', }); const saved = await f.snapshot(); const conflict = paperFrame(2); conflict.quotes[0]!.ask = parseFinancialDecimal('11'); await expect(f.runtime.ingest(conflict)).rejects.toThrow('conflicting content'); expect((await f.snapshot()).account).toEqual(saved.account); }); test('new frame IDs cannot turn inactive probe quotes into later tradable liquidity', async () => { const f = await fixture(); await start(f); f.clock(20); const recycled = paperFrame(2); recycled.quotes = paperFrame(1).quotes; await expect(f.runtime.ingest(recycled)).rejects.toThrow('known physical quote'); recycled.quotes[0]!.bidSize = parseFinancialDecimal('11'); await expect(f.runtime.ingest(recycled)).rejects.toThrow('conflicting content'); expect((await f.snapshot()).account.inputSequence).toBe(0); }); test('new quote identities cannot regress a fresh inactive probe or hide stale executable quotes', async () => { const f = await fixture(); await start(f); f.clock(20); const old = paperFrame(2); old.quotes[0]!.observedAt = 5; await expect(f.runtime.ingest(old)).rejects.toThrow('regresses'); expect((await f.snapshot()).account.inputSequence).toBe(0); await f.runtime.halt('probe'); f.clock(200); await f.runtime.ingest(paperFrame(3, 200)); await f.runtime.activate({ recoverPending: false }); f.clock(210); const stale = paperFrame(4, 210); stale.quotes[0]!.observedAt = 100; await expect(f.runtime.ingest(stale)).rejects.toThrow('regresses'); expect((await f.snapshot()).account.inputSequence).toBe(0); }); test('equal-time quotes require nonregressing physical sequence; a newer sequence remains admissible', async () => { const f = await fixture(); await start(f); f.clock(20); const newer = paperFrame(2); newer.quotes[0]!.observedAt = 10; expect((await f.runtime.ingest(newer)).disposition).toBe('admitted'); const saved = await f.snapshot(); f.clock(30); const older = paperFrame(3); older.quotes[0]!.observedAt = 10; older.quotes[0]!.sourceSequence = 0; await expect(f.runtime.ingest(older)).rejects.toThrow('regresses'); expect((await f.snapshot()).account.checkpoint).toEqual(saved.account.checkpoint); }); test.each(['reconnect', 'restart'] as const)( '%s preserves quote highwater while requiring new connection health', async kind => { const f = await fixture(); await f.runtime.connect(connection); f.clock(30); await f.runtime.ingest(paperFrame(3)); const runtime = kind === 'restart' ? await f.make() : f.runtime; await runtime.connect({ ...connection, connectionId: 'two' }); expect((await runtime.status()).reasons).toContain('quote-stale:X'); f.clock(40); const old = paperFrame(4, 40, 'two'); old.quotes[0]!.observedAt = 20; old.quotes[0]!.sourceSequence = 2; await expect(runtime.ingest(old)).rejects.toThrow('regresses'); expect((await f.snapshot()).account.inputSequence).toBe(0); await runtime.ingest(paperFrame(4, 40, 'two')); expect((await runtime.activate({ recoverPending: false })).active).toBe(true); } ); test.each(['malformed', 'conflict', 'activation'] as const)( 'a rejected %s request durably latches stale inactivity without polling or admitting its input', async kind => { const f = await fixture(); await start(f); const before = await f.snapshot(); f.clock(200); if (kind === 'activation') { await expect(f.runtime.activate({ recoverPending: false })).rejects.toThrow( 'unavailable' ); } else { const rejected = kind === 'conflict' ? paperFrame(1) : paperFrame(2, 200); if (kind === 'conflict') { rejected.quotes[0]!.ask = parseFinancialDecimal('11'); } else { rejected.quotes[0]!.ask = parseFinancialDecimal('0'); } await expect(f.runtime.ingest(rejected)).rejects.toThrow(); } // Read persisted custody directly: status() must not be what latches the halt. const stopped = await f.snapshot(); expect(stopped.account.host?.active).toBe(false); expect(stopped.account.checkpoint).toEqual(before.account.checkpoint); expect(stopped.account.inputSequence).toBe(0); expect(stopped.account.host!.frames).toEqual(before.account.host!.frames); expect(stopped.account.host!.lastAvailableAt).toBe(before.account.host!.lastAvailableAt); } ); test('fresh transport and asset A cannot certify a stale required asset B or exhausted calendars', async () => { const config = paperConfig(); config.matching.series.push({ instrumentId: 'Y', seriesId: 'Y:quote', mode: 'Quote' }); config.policy.calendars.push({ ...config.policy.calendars[0]!, instrumentId: 'Y' }); const f = await fixture(config); await f.runtime.connect(connection); await f.runtime.ingest(paperFrame(1)); await expect(f.runtime.activate({ recoverPending: false })).rejects.toThrow('quote-stale:Y'); f.clock(20); const frame = paperFrame(2); frame.quotes.push({ ...frame.quotes[0]!, instrumentId: 'Y', seriesId: 'Y:quote' }); await f.runtime.ingest(frame); await f.runtime.activate({ recoverPending: false }); f.clock(110); await f.runtime.ingest(paperFrame(3, 110)); f.clock(121); expect(await f.runtime.status()).toMatchObject({ active: false, ready: false }); expect((await f.runtime.status()).reasons).toContain('quote-stale:Y'); f.clock(10000); expect((await f.runtime.status()).reasons).toContain('calendar-uncovered:X'); }); test('binds configured capital and policy and refuses uncontrolled reopening or direct enqueue', async () => { const f = await fixture(); expect((await f.snapshot()).account.view.portfolio.cash).toBe(parseFinancialDecimal('1000')); const changed = paperConfig(); changed.matching.risk.ledger.initialCapital = '2000'; await expect(f.make(changed)).rejects.toThrow('configuration'); const plain = new CanonicalPaperExecution({ repository: f.repository, programs: [ { ...counterProgram(), strategyId: 'sma_crossover', strategyVersion: 'sma-crossover-long-only/v1', }, ], }); await expect(plain.initialize(f.configuration.matching)).rejects.toThrow('configuration'); const privileged = (f.runtime as unknown as { execution: CanonicalPaperExecution }).execution; await expect(privileged.enqueue(quoteInput(1))).rejects.toThrow('atomic producer frames'); expect((await f.snapshot()).account.inputSequence).toBe(0); }); test('requires explicit historical recovery, preserves original times, and retains poisoned decisions', async () => { let fail = true; const base = counterProgram(); const f = await fixture(paperConfig(), { ...base, decide: context => { if (fail) { throw new Error('poisoned strategy'); } return base.decide(context); }, }); await start(f); f.clock(20); await expect(f.runtime.ingest(paperFrame(2))).rejects.toThrow('poisoned strategy'); const pending = await f.runtime.status(); expect(pending).toMatchObject({ active: false, requiresHistoricalRecovery: true }); f.clock(200); await f.runtime.ingest(paperFrame(3, 200)); await f.repository.transact(f.configuration.matching.risk.ledger.accountId, async tx => { if (tx.account.host) { tx.account.host.diagnostic = null; } }); expect(await f.runtime.status()).toMatchObject({ ready: false, reasons: ['historical-recovery-required'], }); await expect(f.runtime.activate({ recoverPending: false })).rejects.toThrow('recoverPending'); await expect(f.runtime.activate({ recoverPending: true })).rejects.toThrow( 'poisoned strategy' ); expect(await f.runtime.status()).toMatchObject({ active: false, requiresHistoricalRecovery: true, }); fail = false; expect(await f.runtime.activate({ recoverPending: true })).toMatchObject({ active: true, ready: true, requiresHistoricalRecovery: false, }); const snapshot = await f.snapshot(); const decisions = snapshot.journal.filter(row => row.payload.kind === 'decision'); expect(decisions).toHaveLength(1); expect(decisions[0]!.payload.kind === 'decision' && decisions[0]!.payload.key.at).toBe(20); expect(snapshot.owners[0]!.diagnostic.observationCount).toBe(1); }); test('explicit recovery after an hour fills an already admitted quote at its original price/time exactly once', async () => { const config = paperConfig(); config.policy.calendars[0]!.sessions[0]!.closesAt = 7_200_000; const f = await fixture(config); await start(f); f.clock(20); await f.runtime.ingest(paperFrame(2)); let armed = true; f.wrap(tx => ({ ...tx, async appendJournal(payload) { if (armed) { armed = false; throw new Error('crash before quote commit'); } return tx.appendJournal(payload); }, })); f.clock(30); const admitted = paperFrame(3); await expect(f.runtime.ingest(admitted)).rejects.toThrow('crash before quote commit'); expect((await f.snapshot()).account.view.portfolio.positions).toHaveLength(0); const restored = await f.make(); await restored.connect({ ...connection, connectionId: 'two' }); f.clock(3_600_030); const probe = paperFrame(4, 3_600_030, 'two'); probe.quotes[0]!.bid = parseFinancialDecimal('99'); probe.quotes[0]!.ask = parseFinancialDecimal('99'); expect((await restored.ingest(probe)).disposition).toBe('health-only'); await expect(restored.activate({ recoverPending: false })).rejects.toThrow('recoverPending'); expect(await restored.activate({ recoverPending: true })).toMatchObject({ active: true, ready: true, requiresHistoricalRecovery: false, }); const recovered = await f.snapshot(); expect(recovered.account.view.portfolio.cash).toBe(parseFinancialDecimal('979.8')); expect(recovered.account.view.portfolio.positions[0]!.quantity).toBe( parseFinancialDecimal('2') ); expect(recovered.account.view.portfolio.fees[0]!.amount).toBe(parseFinancialDecimal('0.2')); const quotes = recovered.journal.filter( row => row.payload.kind === 'command' && row.payload.command.key.at === 30 && row.payload.command.body.kind === 'execute' ); expect(quotes).toHaveLength(1); const payload = quotes[0]!.payload; if (payload.kind !== 'command' || payload.command.body.kind !== 'execute') { throw new Error('Missing quote command'); } expect(payload.command.body.observation).toMatchObject({ kind: 'quote', observedAt: 30, ask: parseFinancialDecimal('10'), }); expect(await restored.ingest(admitted)).toMatchObject({ duplicate: true, disposition: 'admitted', }); expect((await f.snapshot()).account.checkpoint).toEqual(recovered.account.checkpoint); }); test('a halt waiting on the real account lock stops the next financial step without discarding work', async () => { const f = await fixture(); await start(f); const reached = deferred(); const release = deferred(); let armed = true; f.wrap(tx => ({ ...tx, async appendJournal(payload) { if (armed && payload.kind === 'decision') { armed = false; reached.resolve(); await release.promise; } return tx.appendJournal(payload); }, })); f.clock(20); const ingest = f.runtime.ingest(paperFrame(2)); await reached.promise; const halt = f.runtime.halt('race stop'); // Verify PostgreSQL sees a lock waiter before allowing the financial step to commit. let waiting = false; for (let attempt = 0; attempt < 100; attempt++) { const rows = await f.pool.query( "SELECT 1 FROM pg_stat_activity WHERE datname=current_database() AND wait_event_type='Lock' AND query LIKE 'SELECT state FROM simulation_accounts%' " ); if (rows.rowCount) { waiting = true; break; } await new Promise(resolve => setTimeout(resolve, 5)); } release.resolve(); expect(waiting).toBe(true); expect(await halt).toMatchObject({ active: false, operatorHalted: true }); await ingest; const snapshot = await f.snapshot(); expect(snapshot.account.pendingDecisionSequence).not.toBeNull(); expect(snapshot.owners[0]!.diagnostic.nextDecisionSequence).toBe(0); expect(snapshot.account.view.orders).toHaveLength(0); }); test.each(['input', 'batch'] as const)( 'explicit recovery retains %s work across transient SQL or acknowledgement failures', async stage => { const f = await fixture(); await start(f); let armed = true; let lostAcknowledgement = false; f.wrap(tx => ({ ...tx, async appendJournal(payload) { if (stage === 'input' && armed) { armed = false; throw new Error('transient SQL failure'); } return tx.appendJournal(payload); }, async putBatch(batch) { await tx.putBatch(batch); if (stage === 'batch' && armed) { armed = false; lostAcknowledgement = true; } }, })); f.afterCommit(() => { if (lostAcknowledgement) { lostAcknowledgement = false; throw new Error('lost batch acknowledgement'); } }); f.clock(20); await expect(f.runtime.ingest(paperFrame(2))).rejects.toThrow(); const stopped = await f.runtime.status(); expect(stopped.active).toBe(false); expect(stage === 'input' ? stopped.pendingInput : stopped.pendingBatch).not.toBeNull(); f.clock(200); await f.runtime.ingest(paperFrame(3, 200)); await expect(f.runtime.activate({ recoverPending: false })).rejects.toThrow( 'recoverPending' ); expect(await f.runtime.activate({ recoverPending: true })).toMatchObject({ active: true, requiresHistoricalRecovery: false, }); expect((await f.snapshot()).owners[0]!.diagnostic.nextDecisionSequence).toBe(1); } ); test('auxiliary cadence survives restart; known old physical bars dedup while new delayed bars remain visible', async () => { const config = paperConfig(); config.policy.observations.push({ seriesId: 'X:slow', instrumentId: 'X', intervalMs: 10, staleAfterMs: 100, }); config.policy.cadence[0]!.seriesIds = ['X:slow']; config.strategies[0]!.seriesId = 'X:slow'; const f = await fixture(config); await start(f); f.clock(20); const fast = paperFrame(2); await f.runtime.ingest(fast); expect((await f.snapshot()).owners[0]!.pendingObservations).toHaveLength(1); const restored = await f.make(); await restored.connect({ ...connection, connectionId: 'two' }); f.clock(30); await restored.ingest(paperFrame(3, 30, 'two')); await restored.activate({ recoverPending: false }); f.clock(40); const slow = paperFrame(4, 40, 'two'); slow.observations = [ fast.observations[0]!, { ...fast.observations[0]!, series_id: 'X:slow', event_time: 20, available_at: 40, source_sequence: 99, }, ]; await restored.ingest(slow); const snapshot = await f.snapshot(); expect(snapshot.owners[0]!.diagnostic.observationCount).toBe(2); expect(snapshot.owners[0]!.diagnostic.nextDecisionSequence).toBe(1); expect(snapshot.owners[0]!.diagnostic.state).toMatchObject({ seen: [2, 99] }); f.clock(50); const conflict = paperFrame(5, 50, 'two'); conflict.observations = [{ ...fast.observations[0]!, volume: parseFinancialDecimal('11') }]; await expect(restored.ingest(conflict)).rejects.toThrow('conflicting content'); expect((await f.snapshot()).account.checkpoint).toEqual(snapshot.account.checkpoint); }); } );