import { isDeepStrictEqual } from 'node:util' import fc from 'fast-check' import { activeWindowBeforeReload, pivotOf, rootReceiptHistories, sourceFacts, terminalSourceInterruption, } from './queued-answer-progress-history.js' import type { Observation, Verdict } from '../../db/tests/oracle-property.js' import type { ProgressHistory, WindowRow, } from './queued-answer-progress-history.js' /** * A finite backend answer already queued while live query demand reenters the * graph must get its host turn. The same obligation covers runnable delivery * of an already produced answer for the current Query. The maintainer's H02 * decision supplies progress, and architecture laws 6, 7, 9 and 11 supply * current-demand fencing, applied settlement, graph publication and ownership. * * The relational judgment recomputes the ordered anti-join window from the * authored finite provider facts, as in the retained-publication model. The * progress judgment is over events, independently of the number of graph * passes: it requires real queue/application premises and cannot credit a * setup timeout or an inactive request. A bound in the receiver limits the * experiment, not application latency. This grammar starts with a ready * result and replays predicate-only requests. It can fail the replay, * supersede it with a truncate or second reload, or clean up while graph work * is paused or while accepted root output waits behind persistence. A separate * recovery can finish while two accepted root transactions remain parked. * Widening an underfilled window then still waits for the previously accepted * output even when the new choice adds no rows to the private result. * A paused graph also hands a publication receipt to the active-window * tracker. That receipt stays pending across both provider and accepted-write * holds, and preserves a replay's failure after a synchronous replacement. * A fresh move deferred by a different source's replay still retries an * earlier failed ordered acquisition after the current graph turn can proceed. * Cleanup also retires paused work with no application waiter. The native * host must neither retain that turn nor report its private abort. * A source crash or failed first load ends the query and rejects its * unfinished window with the source error, including moves admitted before a * pause and moves whose graph never pauses (architecture law 16 and Atomic * window publication). The old published result is visible at failure. * An accepted root write may apply later, without settling the failed move or * restarting a retired downstream graph. The terminal run also rejects * later valid window requests with that source error. */ export const law = { statement: 'Finite Query answers can run and apply while an ordered live query retains coherent results and row ownership.', authority: 'H02 maintainer decision, live-query ARCHITECTURE.md laws 6, 7, 9, 11, 16, and Atomic window publication.', limits: 'Finite Query DB replies, one ordered anti-join, inline and Collection-valued includes, and one independently keyed peer or one independent replay. Covers one superseding recovery of the marker replay.', } const pass: Verdict = { kind: 'pass' } function violation( checkpoint: string, difference: string, law: string, ): Verdict { return { kind: 'violation', checkpoint, difference, law } } function differs( checkpoint: string, law: string, actual: unknown, expected: unknown, ): Verdict | undefined { if (!isDeepStrictEqual(actual, expected)) return { kind: 'violation', checkpoint, difference: 'observed value differs', law, values: { actual, expected }, } return undefined } // A window may enter before the source replay, during replay, or once the // graph has paused. Use shared-key controls to supply the same terminal // failure and independent provider completion without a graph pause. const terminalWindowSchedules = [ { route: 'conflict', admission: 'after-pause', label: 'after a graph pause' }, { route: 'conflict', admission: 'during-replay', label: 'before a later graph pause', }, { route: 'shared-key', admission: 'during-replay', label: 'during a replay without a pause', }, { route: 'conflict', admission: 'before-reload', label: 'active before a later graph pause', }, { route: 'shared-key', admission: 'before-reload', label: 'active without a graph pause', }, ] as const const terminalFailures = [ { interruptPause: 'source-crash', description: 'a source crash', pauseState: 'source crash with paused work', }, { interruptPause: 'source-first-load-failure', description: 'a first source load failure', pauseState: 'first source load fails with paused work', }, ] as const const terminalWindowCases = terminalFailures.flatMap((failure) => terminalWindowSchedules.map((schedule) => ({ ...failure, ...schedule, state: `${failure.description} with a window ${schedule.label}`, })), ) const constructionStates = new WeakMap>() const nextTerminalWindow = 'terminal window admission with and without provider work' const states = [ 'opposed caches', 'peer-owned pivot', 'peer answer eligible', 'inline materialization', 'facade materialization', 'window waits for replay', 'output application held', 'paused graph with accepted output held', 'truncate supersedes reload', 'cleanup with paused work', 'cleanup-unawaited with paused work', 'source crash with paused work', 'first source load fails with paused work', nextTerminalWindow, ...terminalWindowCases.map(({ state }) => state), 'a window waits through repeated pauses', 'reload with paused work', 'failed replay with paused work', 'failed replay with loading sibling', 'repaired replay with loading sibling', 'late sibling fails beside earlier replay', 'abort error from current replay', 'same-run replacement of a published replay failure', 'active window through replaced replay failure', 'prior ordered failure with a new move held by unrelated replay', 'current ordered request held through unrelated replay', 'nonempty facade behind held root', 'cleanup with applied receipt held', 'recovered replay with two root receipts held (conflict)', 'recovered replay with two root receipts held (shared-key)', ...rootReceiptHistories, ] as const export const histories = { arbitrary: fc .record({ route: fc.constantFrom('conflict', 'peer', 'shared-key', 'no-include'), host: fc.constantFrom('microtask', 'timer'), nonempty: fc.boolean(), materialization: fc.constantFrom('inline', 'facade'), shift: fc.integer({ min: 0, max: 20 }), rankScale: fc.integer({ min: 1, max: 20 }), moveWindow: fc.boolean(), orderedFailureBeforeReload: fc.option( fc.constantFrom('previous', 'current'), { nil: undefined, }, ), holdOutput: fc.boolean(), cleanupHeldOutput: fc.option(fc.constant(true), { nil: undefined }), rootReceipt: fc.option(fc.constantFrom(...rootReceiptHistories), { nil: undefined, }), siblingReplay: fc.option( fc.constantFrom( 'held', 'recovers', 'fails', 'abort-error', 'replaces-abort-error', 'recovers-with-held-output', ), { nil: undefined }, ), holdFacade: fc.boolean(), truncateDuringReload: fc.boolean(), terminalWindowAdmission: fc.option( fc.constantFrom('before-reload', 'during-replay', 'after-pause'), { nil: undefined, freq: 8 }, ), interruptPause: fc.option( fc.constantFrom( 'cleanup', 'cleanup-unawaited', 'reload', 'failure', 'repeat', 'source-crash', 'source-first-load-failure', ), { nil: undefined, }, ), }) .filter( ({ moveWindow, orderedFailureBeforeReload, holdOutput, cleanupHeldOutput, rootReceipt, siblingReplay, holdFacade, nonempty, route, host, truncateDuringReload, interruptPause, terminalWindowAdmission, }) => { if ( interruptPause === 'source-crash' || interruptPause === 'source-first-load-failure' ) return ( host === 'timer' && nonempty && moveWindow && !holdOutput && !holdFacade && !cleanupHeldOutput && !rootReceipt && !orderedFailureBeforeReload && !siblingReplay && !truncateDuringReload && terminalWindowSchedules.some( (schedule) => schedule.route === route && schedule.admission === (terminalWindowAdmission ?? 'after-pause'), ) ) if (terminalWindowAdmission) return false if (orderedFailureBeforeReload) return ( route === 'conflict' && host === 'timer' && nonempty && moveWindow === (orderedFailureBeforeReload === 'previous') && !holdOutput && !rootReceipt && !holdFacade && !cleanupHeldOutput && !interruptPause && !siblingReplay && !truncateDuringReload ) if (rootReceipt) return ( route === 'conflict' && host === 'timer' && nonempty && moveWindow && holdOutput && !holdFacade && !cleanupHeldOutput && !interruptPause && !siblingReplay && !truncateDuringReload ) if (siblingReplay === 'recovers-with-held-output') return ( (route === 'conflict' || route === 'shared-key') && host === 'timer' && nonempty && !moveWindow && holdOutput && !holdFacade && !cleanupHeldOutput && !interruptPause && !truncateDuringReload ) if (siblingReplay && interruptPause !== 'failure') return false if (cleanupHeldOutput) return ( route === 'conflict' && host === 'timer' && nonempty && moveWindow && holdOutput && !holdFacade && !interruptPause && !truncateDuringReload ) if (holdFacade) return ( route === 'conflict' && host === 'timer' && nonempty && moveWindow && holdOutput && !interruptPause && !truncateDuringReload ) if (interruptPause) return ( route === 'conflict' && host === 'timer' && nonempty && (moveWindow === (interruptPause !== 'cleanup-unawaited') || siblingReplay === 'replaces-abort-error') && !holdOutput && !truncateDuringReload ) if (truncateDuringReload) return ( route === 'conflict' && host === 'timer' && nonempty && !moveWindow && !holdOutput ) if (moveWindow && route !== 'conflict' && route !== 'shared-key') return false return !holdOutput || (moveWindow && nonempty) }, ) as fc.Arbitrary, runs: 12, fixedSeeds: [20261123], bases: 1, drawnBases: 1, states, constructed: [ { name: 'independent cache overlap with a queued microtask', enters: ['opposed caches'], build: (base: ProgressHistory): ProgressHistory => ({ ...base, holdFacade: false, interruptPause: undefined, truncateDuringReload: false, holdOutput: false, route: 'conflict', host: 'microtask', materialization: 'inline', nonempty: false, moveWindow: false, }), }, { name: 'independent cache overlap with a queued timer and a facade', enters: ['opposed caches', 'facade materialization'], build: (base: ProgressHistory): ProgressHistory => ({ ...base, holdFacade: false, interruptPause: undefined, truncateDuringReload: false, holdOutput: false, route: 'conflict', host: 'timer', materialization: 'facade', nonempty: true, moveWindow: false, }), }, { name: 'the peer keeps a pivot until its own empty answer', enters: ['peer-owned pivot', 'peer answer eligible'], build: (base: ProgressHistory): ProgressHistory => ({ ...base, holdFacade: false, interruptPause: undefined, truncateDuringReload: false, holdOutput: false, route: 'peer', nonempty: true, moveWindow: false, }), }, { name: 'shared scope retains a nonempty inline window while held', enters: ['inline materialization'], build: (base: ProgressHistory): ProgressHistory => ({ ...base, holdFacade: false, interruptPause: undefined, truncateDuringReload: false, holdOutput: false, route: 'shared-key', materialization: 'inline', nonempty: true, moveWindow: false, }), }, { name: 'shared scope retains a nonempty facade window while held', enters: ['facade materialization'], build: (base: ProgressHistory): ProgressHistory => ({ ...base, holdFacade: false, interruptPause: undefined, truncateDuringReload: false, holdOutput: false, route: 'shared-key', materialization: 'facade', nonempty: true, moveWindow: false, }), }, { name: 'a window move waits while the shared-scope answer is held', enters: ['window waits for replay'], build: (base: ProgressHistory): ProgressHistory => ({ ...base, holdFacade: false, interruptPause: undefined, truncateDuringReload: false, holdOutput: false, route: 'shared-key', nonempty: true, moveWindow: true, }), }, { name: 'a window move joins a replay with competing cached rows', enters: ['opposed caches'], build: (base: ProgressHistory): ProgressHistory => ({ ...base, holdFacade: false, interruptPause: undefined, truncateDuringReload: false, holdOutput: false, route: 'conflict', host: 'timer', materialization: 'inline', nonempty: true, moveWindow: true, }), }, { name: 'an applied root receipt holds the window promise through persistence', enters: ['window waits for replay', 'output application held'], build: (base: ProgressHistory): ProgressHistory => ({ ...base, holdFacade: false, interruptPause: undefined, truncateDuringReload: false, route: 'shared-key', materialization: 'inline', nonempty: true, moveWindow: true, holdOutput: true, }), }, { name: 'a paused window also waits for parked output to apply', enters: [ 'opposed caches', 'output application held', 'paused graph with accepted output held', ], build: (base: ProgressHistory): ProgressHistory => ({ ...base, holdFacade: false, interruptPause: undefined, truncateDuringReload: false, route: 'conflict', host: 'timer', materialization: 'inline', nonempty: true, moveWindow: true, holdOutput: true, }), }, { name: 'a truncate replaces held reload acquisitions before the next answer', enters: ['truncate supersedes reload'], build: (base: ProgressHistory): ProgressHistory => ({ ...base, holdFacade: false, interruptPause: undefined, route: 'conflict', host: 'timer', materialization: 'facade', nonempty: true, moveWindow: false, holdOutput: false, truncateDuringReload: true, }), }, ...(['cleanup', 'reload'] as const).map((interruptPause) => ({ name: `a waiting window rejects when ${interruptPause} retires paused work`, enters: [`${interruptPause} with paused work`, 'window waits for replay'], build: (base: ProgressHistory): ProgressHistory => ({ ...base, holdFacade: false, route: 'conflict', host: 'timer', nonempty: true, moveWindow: true, holdOutput: false, truncateDuringReload: false, interruptPause, }), })), { name: 'cleanup retires an unawaited graph turn at the host boundary', enters: ['cleanup-unawaited with paused work'], build: (base: ProgressHistory): ProgressHistory => ({ ...base, route: 'conflict', host: 'timer', nonempty: true, moveWindow: false, holdOutput: false, holdFacade: false, cleanupHeldOutput: undefined, truncateDuringReload: false, siblingReplay: undefined, interruptPause: 'cleanup-unawaited', }), }, ...terminalWindowCases.map( ({ interruptPause, description, pauseState, route, admission, state, }) => ({ name: admission === 'after-pause' ? `${description} retires a paused graph before another provider answers` : state, enters: [ state, nextTerminalWindow, ...(route === 'conflict' ? [pauseState] : []), ...(admission !== 'before-reload' ? ['window waits for replay'] : []), ], build: (base: ProgressHistory): ProgressHistory => ({ ...base, route, host: 'timer', nonempty: true, moveWindow: true, holdOutput: false, holdFacade: false, cleanupHeldOutput: undefined, orderedFailureBeforeReload: undefined, rootReceipt: undefined, siblingReplay: undefined, truncateDuringReload: false, interruptPause, terminalWindowAdmission: admission, }), }), ), { name: 'one waiting window survives two pauses before the answer', enters: ['a window waits through repeated pauses'], build: (base: ProgressHistory): ProgressHistory => ({ ...base, route: 'conflict', host: 'timer', nonempty: true, moveWindow: true, holdOutput: false, holdFacade: false, truncateDuringReload: false, interruptPause: 'repeat', }), }, { name: 'a finite replay failure rejects a waiting window and retains the prior result', enters: ['failed replay with paused work', 'window waits for replay'], build: (base: ProgressHistory): ProgressHistory => ({ ...base, holdFacade: false, route: 'conflict', host: 'timer', nonempty: true, moveWindow: true, holdOutput: false, truncateDuringReload: false, interruptPause: 'failure', }), }, ...(['inline', 'facade'] as const).map((materialization) => ({ name: `a fresh move retries an earlier ordered failure after unrelated replay (${materialization})`, enters: [ 'prior ordered failure with a new move held by unrelated replay', ], build: (base: ProgressHistory): ProgressHistory => ({ ...base, route: 'conflict', host: 'timer', nonempty: true, moveWindow: true, orderedFailureBeforeReload: 'previous', holdOutput: false, holdFacade: false, materialization, truncateDuringReload: false, interruptPause: undefined, }), })), { name: 'an active ordered move keeps its own failure after unrelated replay', enters: ['current ordered request held through unrelated replay'], build: (base: ProgressHistory): ProgressHistory => ({ ...base, route: 'conflict', host: 'timer', nonempty: true, moveWindow: false, orderedFailureBeforeReload: 'current', holdOutput: false, holdFacade: false, materialization: 'inline', truncateDuringReload: false, interruptPause: undefined, }), }, ...(['inline', 'facade'] as const).map((materialization) => ({ name: `a failed replay rejects a window retry while an independent replay is loading (${materialization})`, enters: [ 'failed replay with paused work', 'failed replay with loading sibling', ], build: (base: ProgressHistory): ProgressHistory => ({ ...base, route: 'conflict', host: 'timer', nonempty: true, moveWindow: true, holdOutput: false, holdFacade: false, siblingReplay: 'held', materialization, truncateDuringReload: false, interruptPause: 'failure', }), })), ...(['inline', 'facade'] as const).map((materialization) => ({ name: `a window waiting on an independent replay can succeed after the earlier failure clears (${materialization})`, enters: ['repaired replay with loading sibling'], build: (base: ProgressHistory): ProgressHistory => ({ ...base, route: 'conflict', host: 'timer', nonempty: true, moveWindow: true, holdOutput: false, holdFacade: false, siblingReplay: 'recovers', materialization, truncateDuringReload: false, interruptPause: 'failure', }), })), { name: 'a provider AbortError rejects the waiting window when its replay is still current', enters: ['abort error from current replay', 'window waits for replay'], build: (base: ProgressHistory): ProgressHistory => ({ ...base, route: 'conflict', host: 'timer', nonempty: true, moveWindow: true, holdOutput: false, holdFacade: false, siblingReplay: 'abort-error', truncateDuringReload: false, interruptPause: 'failure', }), }, ...(['inline', 'facade'] as const).map((materialization) => ({ name: `a same-run truncate preserves the error owed to an existing window (${materialization})`, enters: ['same-run replacement of a published replay failure'], build: (base: ProgressHistory): ProgressHistory => ({ ...base, route: 'conflict', host: 'timer', nonempty: true, moveWindow: true, holdOutput: false, holdFacade: false, materialization, siblingReplay: 'replaces-abort-error', truncateDuringReload: false, interruptPause: 'failure', }), })), ...(['inline', 'facade'] as const).map((materialization) => ({ name: `a replay started after the window request rejects it while the earlier replay is still held (${materialization})`, enters: ['late sibling fails beside earlier replay'], build: (base: ProgressHistory): ProgressHistory => ({ ...base, route: 'conflict', host: 'timer', nonempty: true, moveWindow: true, holdOutput: false, holdFacade: false, siblingReplay: 'fails', materialization, truncateDuringReload: false, interruptPause: 'failure', }), })), ...(['inline', 'facade'] as const).map((materialization) => ({ name: `a window active before reload keeps the failure of its paused graph (${materialization})`, enters: [ 'active window through replaced replay failure', 'same-run replacement of a published replay failure', ], build: (base: ProgressHistory): ProgressHistory => ({ ...base, route: 'conflict', host: 'timer', nonempty: true, moveWindow: false, holdOutput: false, holdFacade: false, materialization, siblingReplay: 'replaces-abort-error', truncateDuringReload: false, cleanupHeldOutput: undefined, interruptPause: 'failure', }), })), { name: 'a held root keeps its nonempty facade until replacement applies', enters: ['nonempty facade behind held root'], build: (base: ProgressHistory): ProgressHistory => ({ ...base, route: 'conflict', host: 'timer', nonempty: true, moveWindow: true, holdOutput: true, holdFacade: true, materialization: 'inline', truncateDuringReload: false, interruptPause: undefined, }), }, { name: 'cleanup rejects a waiting window with an accepted root receipt still held', enters: ['cleanup with applied receipt held', 'output application held'], build: (base: ProgressHistory): ProgressHistory => ({ ...base, route: 'conflict', host: 'timer', nonempty: true, moveWindow: true, holdOutput: true, cleanupHeldOutput: true, holdFacade: false, materialization: 'inline', truncateDuringReload: false, interruptPause: undefined, }), }, ...(['conflict', 'shared-key'] as const).map((route) => ({ name: `a recovered replay cannot bypass two accepted root receipts (${route})`, enters: [`recovered replay with two root receipts held (${route})`], build: (base: ProgressHistory): ProgressHistory => ({ ...base, route, host: 'timer', nonempty: true, moveWindow: false, holdOutput: true, holdFacade: false, siblingReplay: 'recovers-with-held-output', truncateDuringReload: false, interruptPause: undefined, }), })), ...rootReceiptHistories.map((rootReceipt) => ({ name: rootReceipt, enters: [rootReceipt], build: (base: ProgressHistory): ProgressHistory => ({ ...base, rootReceipt, route: 'conflict', host: 'timer', nonempty: true, materialization: 'inline', moveWindow: true, holdOutput: true, holdFacade: false, truncateDuringReload: false, interruptPause: undefined, }), })), ].map((construction) => ({ ...construction, build: (base: ProgressHistory) => { const history = construction.build({ ...base, orderedFailureBeforeReload: undefined, cleanupHeldOutput: undefined, rootReceipt: undefined, siblingReplay: undefined, terminalWindowAdmission: undefined, }) constructionStates.set(history, construction.enters) return history }, })), } export function model(history: ProgressHistory) { const { rows, marked } = sourceFacts(history) const window = (offset: number, limit = 1): Array => rows .filter(({ id }) => !marked.has(id)) .sort((a, b) => a.rank - b.rank) .slice(offset, offset + limit) .map(({ id, rank }) => ({ id, rank, markers: [], ...(history.holdFacade ? { details: [id] } : {}), })) const prior = window(1) const pivot = pivotOf(history) marked.delete(pivot) if (history.siblingReplay === 'recovers-with-held-output') { marked.add(history.shift + 4) const replayReplacement = window(1) rows.find(({ id }) => id === pivot)!.rank++ return { prior, replayReplacement, final: window(1, 2), rootAfterAcceptedApplication: prior, } } return { prior, replayReplacement: window(1), final: history.orderedFailureBeforeReload === 'current' || terminalSourceInterruption(history) || (history.interruptPause === 'failure' && history.siblingReplay !== 'recovers' && history.siblingReplay !== 'fails' && history.siblingReplay !== 'replaces-abort-error') ? prior : window( history.moveWindow && (!history.interruptPause || history.interruptPause === 'repeat' || history.siblingReplay === 'recovers') && !history.cleanupHeldOutput ? 0 : 1, ), // An earlier accepted root rank write still applies when persistence // releases. The terminal query cannot advance its window or downstream. rootAfterAcceptedApplication: terminalSourceInterruption(history) && history.terminalWindowAdmission === 'before-reload' ? prior.map((row) => ({ ...row, rank: row.rank + 1 })) : prior, } } type Counters = { attempts: number fetches: number releases: number turns: number } type PausePosition = { pauseCheckpoints: number graphResumptions: number } type TerminalSourceCut = { graphCompletion: string exactGraphError: boolean exactLifecycleError: boolean exactWindowError: boolean scheduledGraphTasks: number retiredGraphEntries: number sourceStatus: string liveStatus: string downstreamStatus: string window: { offset: number; limit: number } } type TerminalWindowRelease = { windowSettled: boolean exactWindowError: boolean heldAcquisitions: number acceptedRootReceipts: number window: { offset: number; limit: number } } type TerminalWindowAdmission = { retry: string exactError: boolean heldAcquisitions: number live: Array window: { offset: number; limit: number } } type Cache = { queryId: number active: boolean key: unknown data: unknown fetchStatus: string updateCount: number } type Load = Counters & { scope: Array caches: Array pivotPresent: boolean } type Snapshot = Counters & { live: Array downstream: Array> rawHasPivot: boolean pivotCaches?: Array status: string inFlight: number materialization: Array } type Conflict = Counters & { actual: unknown sibling: unknown actualIds: Array siblingIds: Array cacheStates: Array requestAborted: boolean liveIds: Array downstreamIds: Array } type Answer = Counters & { atom: string scope: Array ids: Array startCount: number queryId: number active: boolean stale: boolean aborted: boolean } type Installation = { queryId: number updateCount: number rowIds: unknown } function installsEmptyAnswer( installation: Installation, queryId: number, startCount: number, ) { return ( installation.queryId === queryId && installation.updateCount === startCount + 1 && isDeepStrictEqual(installation.rowIds, []) ) } const progress = 'finite answer progress' const publication = 'complete graph publication' const ownership = 'cached row ownership' function facts(trace: ReadonlyArray, checkpoint: string) { return trace .filter((event) => event.checkpoint === checkpoint) .map((event) => event.value as T) } type RootReceiptCut = { accepted: number realPause: boolean receiptVerdict: string prior: Array beforeWindow: { offset: number; limit: number } graphCompletion: string windowSettled: boolean windowError: string | null sameRootError: boolean applicationSchedules: Array live: Array window: { offset: number; limit: number } status: string } function rootReceiptCut(trace: ReadonlyArray) { return facts(trace, 'paused root receipt outcome')[0] } // An accepted pair applies in FIFO order. Receipt delivery before the last // write owes no extra graph turn. A canceled pre-acceptance write leaves the // previous rows intact. Cleanup from a publication callback retires its // graph and window while the already-applied write's own receipt can fulfill. function expectedRootReceipt( action: Exclude< ProgressHistory['rootReceipt'], 'ignore an application rejection from the retired root' | undefined >, rows: ReturnType, ): RootReceiptCut { const pair = action === 'apply two accepted root receipts' const canceled = action === 'cancel root commit before acceptance' const beforeWindow = { offset: 1, limit: 1 } return { accepted: pair ? 2 : canceled ? 0 : 1, realPause: true, receiptVerdict: canceled ? 'rejected' : 'fulfilled', prior: rows.prior, beforeWindow, graphCompletion: pair ? 'fulfilled' : 'rejected', windowSettled: pair, windowError: pair ? null : 'AbortError', sameRootError: canceled, applicationSchedules: pair ? [0, 1] : canceled ? [] : [0], live: pair ? rows.final : canceled ? rows.prior : [], window: pair ? { offset: 0, limit: 1 } : beforeWindow, status: pair || canceled ? 'ready' : 'cleaned-up', } } function reachedReplacementReceipt( history: ProgressHistory, trace: ReadonlyArray, ) { const oldEnd = trace.findIndex( ({ checkpoint }) => checkpoint === 'replacement before its replay', ) const [retired] = facts<{ accepted: number realPause: boolean deliveryReady: boolean }>(trace, 'retire before old application rejection') const [replacement] = facts<{ newRun: boolean }>( trace, 'replacement before its replay', ) const [overlap] = facts<{ realPause: boolean; delivered: boolean }>( trace, 'replacement pause after old receipt', ) return ( retired?.accepted === 1 && retired.realPause && retired.deliveryReady && replacement?.newRun && overlap?.realPause && overlap.delivered && validConflict(history, trace.slice(oldEnd + 1)) ) } function checkReplacementReceipt( history: ProgressHistory, trace: ReadonlyArray, rows: ReturnType, ): Verdict { const law = 'a retired application rejection cannot decide a fresh paused graph' if (!reachedReplacementReceipt(history, trace)) return violation( 'replacement pause receipt premise', 'expected one accepted old root receipt and a different paused sync run receiving its rejection', law, ) return ( differs( 'retire before old application rejection', law, facts(trace, 'retire before old application rejection'), [ { accepted: 1, realPause: true, deliveryReady: true, status: 'cleaned-up', windowError: 'AbortError', }, ], ) ?? differs( 'replacement before its replay', law, facts(trace, 'replacement before its replay'), [{ newRun: true, live: rows.prior }], ) ?? differs( 'replacement pause after old receipt', law, facts(trace, 'replacement pause after old receipt'), [ { realPause: true, delivered: true, graphCompletion: 'pending', windowSettled: false, windowError: null, sameRootError: false, }, ], ) ?? differs( 'replacement window after old application rejection', law, facts(trace, 'replacement window after old application rejection'), [ { graphCompletion: 'fulfilled', windowSettled: true, windowError: null, live: rows.final, window: { offset: 0, limit: 1 }, status: 'ready', }, ], ) ?? pass ) } function validConflict( history: ProgressHistory, trace: ReadonlyArray, ) { const [conflict] = facts(trace, 'cache-conflict') return ( conflict && !conflict.requestAborted && !isDeepStrictEqual(conflict.actual, conflict.sibling) && isDeepStrictEqual(conflict.actualIds, [pivotOf(history)]) && conflict.siblingIds.length === 0 ) } type WindowCut = { held: boolean pending: boolean window: { offset: number; limit: number } live: Array } type Peer = { rawHasPivot: boolean; peerHasPivot: boolean } type TruncateCut = { retired: number replacement: number live: Array downstream: Array> } type RetiringCut = { pauseCheckpoints: number live: Array downstream: Array> } type HeldOutputRecovery = WindowCut & { retry: string sameRun: boolean pauseCheckpoints: number siblingHeld: boolean failureReported: boolean failureCleared: boolean firstAccepted: number secondAccepted: number retainedFirst: boolean pendingRoot: number retainedBoth: boolean } function heldOutputRecovery( history: ProgressHistory, trace: ReadonlyArray, ) { if (history.siblingReplay !== 'recovers-with-held-output') return undefined return facts( trace, 'recovered replay and root receipts held', ).find( (cut) => cut.sameRun && (history.route === 'conflict' ? cut.pauseCheckpoints > 0 : cut.pauseCheckpoints === 0) && cut.siblingHeld && cut.failureReported && cut.failureCleared && cut.firstAccepted === 1 && cut.secondAccepted === 2 && cut.retainedFirst && cut.pendingRoot === 2 && cut.retainedBoth, ) } function supersedingTruncate(trace: ReadonlyArray) { return facts(trace, 'truncate-replaced-reload').find( ({ retired, replacement }) => retired > 0 && replacement > 0, ) } export function reached( history: ProgressHistory, trace: ReadonlyArray, ) { const result: Array = [] if (validConflict(history, trace)) result.push('opposed caches') if ( history.rootReceipt === 'ignore an application rejection from the retired root' ) { if (reachedReplacementReceipt(history, trace)) result.push(history.rootReceipt) } else if (history.rootReceipt && validConflict(history, trace)) { const observed = rootReceiptCut(trace) const expected = expectedRootReceipt(history.rootReceipt, model(history)) if ( observed?.realPause && observed.accepted === expected.accepted && observed.receiptVerdict === expected.receiptVerdict ) result.push(history.rootReceipt) } if ( facts(trace, 'held-peer').some( (peer) => peer.rawHasPivot && peer.peerHasPivot, ) ) result.push('peer-owned pivot') if ( facts(trace, 'window-request').some( (cut) => cut.held && cut.pending, ) ) { result.push('window waits for replay') } if ( facts<{ retry: string rootHeld: boolean pauseCheckpoints: number }>(trace, 'ordered receipt held after independent replay').some( (cut) => cut.retry === 'pending' && cut.rootHeld && cut.pauseCheckpoints > 0, ) ) result.push('current ordered request held through unrelated replay') if ( facts<{ retry: string rootProviderFailed: boolean exactFailure: boolean }>(trace, 'ordered failure before reload').some( (cut) => cut.retry === 'rejected' && cut.rootProviderFailed && cut.exactFailure, ) && facts(trace, 'window-request').some( (cut) => cut.held && cut.pending, ) && facts<{ pauseCheckpoints: number }>( trace, 'window after unrelated replay', ).some((cut) => cut.pauseCheckpoints > 0) ) { result.push( 'prior ordered failure with a new move held by unrelated replay', ) } if ( facts<{ persisting: boolean }>(trace, 'output-hold-start').some( (cut) => cut.persisting, ) && facts<{ rawHasPivot: boolean; acceptedReplacement: boolean }>( trace, 'output-held', ).some((cut) => !cut.rawHasPivot && cut.acceptedReplacement) ) { result.push('output application held') if ( facts<{ pauseCheckpoints: number; acceptedReceipts: number }>( trace, 'output-held', ).some((cut) => cut.pauseCheckpoints > 0 && cut.acceptedReceipts > 0) ) result.push('paused graph with accepted output held') if (facts(trace, 'settled-after-cleanup').length === 1) result.push('cleanup with applied receipt held') if ( facts<{ detailIds: Array }>(trace, 'retained-facade-start').some( ({ detailIds }) => detailIds.length > 0, ) ) result.push('nonempty facade behind held root') } if (history.route === 'peer' && eligibleFollowOn(history, trace)) result.push('peer answer eligible') if (heldOutputRecovery(history, trace)) result.push( `recovered replay with two root receipts held (${history.route})`, ) if (supersedingTruncate(trace)) result.push('truncate supersedes reload') if ( facts<{ pauseCheckpoints: number graphResumptions: number requests: number }>(trace, 'reject-paused-replay').some( (cut) => cut.pauseCheckpoints > 0 && cut.graphResumptions > 0 && cut.requests > 0, ) ) result.push('failed replay with paused work') if ( facts<{ siblingHeld: boolean; failureReported: boolean }>( trace, 'failed-window-retry', ).some(({ siblingHeld, failureReported }) => siblingHeld && failureReported) ) result.push('failed replay with loading sibling') if ( facts<{ siblingHeld: boolean; failureCleared: boolean }>( trace, 'repaired-replay-with-held-sibling', ).some(({ siblingHeld, failureCleared }) => siblingHeld && failureCleared) ) result.push('repaired replay with loading sibling') if ( facts<{ siblingHeld: boolean }>(trace, 'fail-loaded-sibling').some( ({ siblingHeld }) => siblingHeld, ) && facts<{ earlierReplayHeld: boolean; failureReported: boolean }>( trace, 'late-sibling-failure', ).some( ({ earlierReplayHeld, failureReported }) => earlierReplayHeld && failureReported, ) ) result.push('late sibling fails beside earlier replay') if ( facts<{ failureReported: boolean sameSourceRuns: boolean siblingHeld: boolean }>(trace, 'current-abort-error').some( ({ failureReported, sameSourceRuns, siblingHeld }) => failureReported && sameSourceRuns && siblingHeld, ) ) result.push('abort error from current replay') if ( facts<{ sameSourceRuns: boolean pendingReplacement: boolean retainedFailure: boolean }>(trace, 'same-run-truncate-replaces-failure').some( ({ sameSourceRuns, pendingReplacement, retainedFailure }) => sameSourceRuns && pendingReplacement && !retainedFailure, ) ) result.push('same-run replacement of a published replay failure') if (activeWindowBeforeReload(history) && activeWindowReached(trace)) result.push('active window through replaced replay failure') if (history.interruptPause === 'repeat' && repeatedPause(trace)) result.push('a window waits through repeated pauses') const terminal = terminalWindowCase(history) if (terminal && reachedTerminalSource(history, trace)) { result.push(terminal.state) if (terminal.route === 'conflict') result.push(terminal.pauseState) const [held, settled] = terminalWindowNextUses(trace) if (held && held.heldAcquisitions > 0 && settled?.heldAcquisitions === 0) result.push(nextTerminalWindow) } if (history.interruptPause === 'cleanup-unawaited') { if ( facts<{ pendingAtCleanup: number; completionObserved: boolean }>( trace, 'retired pause host work', ).some( ({ pendingAtCleanup, completionObserved }) => pendingAtCleanup > 0 && completionObserved, ) ) result.push('cleanup-unawaited with paused work') } else if ( history.interruptPause && facts(trace, 'retire-paused-run').some( (cut) => cut.pauseCheckpoints > 0, ) ) result.push(`${history.interruptPause} with paused work`) for (const form of new Set( facts(trace, 'held').flatMap((cut) => cut.materialization), )) { if (history.route !== 'no-include') result.push(`${form} materialization`) } return result } function terminalWindowCase(history: ProgressHistory) { return terminalWindowCases.find( ({ route, admission, interruptPause }) => route === history.route && admission === (history.terminalWindowAdmission ?? 'after-pause') && interruptPause === history.interruptPause, ) } function terminalWindowNextUses(trace: ReadonlyArray) { return [ facts( trace, 'terminal window admission with held provider', )[0], facts( trace, 'terminal window admission after provider settlement', )[0], ] as const } function reachedTerminalSource( history: ProgressHistory, trace: ReadonlyArray, ) { const firstLoad = history.interruptPause === 'source-first-load-failure' const pause = history.route === 'conflict' const admission = history.terminalWindowAdmission ?? 'after-pause' const [admitted] = facts<{ pending: boolean pauseCheckpoints: number heldAcquisitions: number acceptedRootReceipts: number }>(trace, 'terminal window admission') const [before] = facts<{ graphCompletion: string pauseCheckpoints: number scheduledGraphTasks: number heldMarkerReplay: boolean status: string }>(trace, 'before terminal source failure') const [after] = facts( trace, 'paused work after terminal source failure', ) return ( admitted?.pending && (admission === 'after-pause' ? admitted.pauseCheckpoints > 0 : admitted.pauseCheckpoints === 0) && (admission === 'before-reload' ? admitted.heldAcquisitions === 0 && admitted.acceptedRootReceipts > 0 : admitted.heldAcquisitions > 0) && before?.graphCompletion === (pause ? 'pending' : 'missing') && (pause ? before.pauseCheckpoints > 0 : before.pauseCheckpoints === 0) && before.scheduledGraphTasks === (pause ? 1 : 0) && before.heldMarkerReplay && before.status === (firstLoad ? 'loading' : 'ready') && after?.sourceStatus === (firstLoad ? 'error' : 'crashed') ) } function activeWindowReached(trace: ReadonlyArray) { const [admission] = facts<{ pending: boolean persisting: boolean pauseCheckpoints: number }>(trace, 'window admitted before reload') const [after] = facts<{ siblingHeld: boolean replacedFailure: boolean pauseCheckpoints: number }>(trace, 'active window after releasing persistence') return ( admission?.pending && admission.persisting && admission.pauseCheckpoints === 0 && after?.siblingHeld && after.replacedFailure && after.pauseCheckpoints > 0 ) } function repeatedPause(trace: ReadonlyArray) { const [requested] = facts( trace, 'window-request', ) const [first] = facts(trace, 'window at first pause') const [again] = facts( trace, 'paused again before answer', ) return ( requested?.pending && first && first.pauseCheckpoints > 0 && again && again.pauseCheckpoints > first.pauseCheckpoints && again.graphResumptions > first.graphResumptions && again ) } function eligibleFollowOn( history: ProgressHistory, trace: ReadonlyArray, ) { if (history.route !== 'peer' && !history.truncateDuringReload) return undefined const [returned] = facts(trace, 'answer-callback-returned') return ( returned && facts(trace, 'provider-answer').find( (answer) => answer.attempts > returned.attempts && isDeepStrictEqual(answer.scope, [pivotOf(history)]) && answer.ids.length === 0 && !answer.aborted && answer.active && answer.stale, ) ) } // The independent replay can release the complete replacement at the prior // offset before the requested window settles. Both receivers move forward // through the same complete cuts, regardless of how many cuts coalesce. function compareReplayPublications( checkpoint: string, law: string, actual: ReadonlyArray, completeCuts: ReadonlyArray, ): Verdict | undefined { let position = 0 for (const rows of actual) { const next = completeCuts.findIndex( (cut, index) => index >= position && isDeepStrictEqual(cut, rows), ) if (next < 0) return violation( checkpoint, 'observed an incomplete or superseded replay result', law, ) position = next } return undefined } export function check( history: ProgressHistory, trace: ReadonlyArray, expected: ReturnType, ) { const result = checkProgress(history, trace, expected) if (result.kind !== 'pass') return result // The pinned runner checks enters in each dedicated construction unit. // Check the same obligations for constructed values sampled by generated units. const owed = constructionStates.get(history) if (!owed) return result const entered = new Set(reached(history, trace)) const missing = owed.filter((state) => !entered.has(state)) return missing.length ? violation( 'constructed history reach', `the history did not enter ${missing.join(', ')}`, 'generated constructions reach their declared states', ) : result } function checkProgress( history: ProgressHistory, trace: ReadonlyArray, expected: ReturnType, ) { if (terminalSourceInterruption(history)) { const cut = 'paused work after terminal source failure' if (!reachedTerminalSource(history, trace)) return violation( cut, 'terminal failure must interrupt the requested window and scheduled provider work', 'receiver premise', ) const [after] = facts(trace, cut) const releaseCut = 'terminal window after independent work settles' const [released] = facts(trace, releaseCut) const [retained] = facts(trace, 'terminal retained result') const [final] = facts(trace, 'final') const terminal = 'terminal source failure retires the graph turn' const windowLaw = 'terminal source failure rejects the unfinished window' const pause = history.route === 'conflict' const active = history.terminalWindowAdmission === 'before-reload' const priorWindow = { offset: 1, limit: 1 } const [heldNext, settledNext] = terminalWindowNextUses(trace) const status = history.interruptPause === 'source-crash' ? 'crashed' : 'error' return ( differs( cut, terminal, [ after?.graphCompletion, after?.exactGraphError, after?.exactLifecycleError, ], [pause ? 'rejected' : 'missing', pause, true], ) ?? differs( cut, terminal, [ after?.liveStatus, after?.downstreamStatus, after?.scheduledGraphTasks, after?.retiredGraphEntries, ], [status, status, 0, 0], ) ?? (!active ? differs(cut, windowLaw, after?.exactWindowError, true) : undefined) ?? differs( 'terminal retained result', publication, [after?.window, retained?.live, retained?.downstream], [priorWindow, expected.prior, downstream(expected.prior)], ) ?? differs( releaseCut, windowLaw, [released?.windowSettled, released?.exactWindowError, released?.window], [false, true, priorWindow], ) ?? differs( releaseCut, publication, [ final?.live, final?.downstream, released?.heldAcquisitions, released?.acceptedRootReceipts, ], [ expected.rootAfterAcceptedApplication, downstream(expected.prior), 0, 0, ], ) ?? differs( 'terminal window admission after failure', 'a terminal query rejects new window requests', [heldNext, settledNext].map((next) => [ next?.retry, next?.exactError, next?.window, next?.live, ]), [ ['rejected', true, priorWindow, expected.prior], [ 'rejected', true, priorWindow, expected.rootAfterAcceptedApplication, ], ], ) ?? differs( 'terminal invalid window validation', 'invalid window options reject before admission', facts<{ rejectsInvalidLimit: boolean }>( trace, 'terminal invalid window validation', )[0]?.rejectsInvalidLimit, true, ) ?? pass ) } if (history.rootReceipt) { if ( history.rootReceipt === 'ignore an application rejection from the retired root' ) return checkReplacementReceipt(history, trace, expected) if (!validConflict(history, trace)) return violation( 'paused root receipt premise', 'real Query DB demand never reached a cache conflict', 'receiver premise', ) return ( differs( 'paused root receipt outcome', 'root application belongs to the graph that awaited it', rootReceiptCut(trace), expectedRootReceipt(history.rootReceipt, expected), ) ?? pass ) } const watchPausedHost = history.interruptPause === 'cleanup-unawaited' if (watchPausedHost) { const [cut] = facts<{ pendingAtCleanup: number outstandingAfterCleanup: number enteredAfterCleanup: number completionObserved: boolean unhandledCompletions: number }>(trace, 'retired pause host work') if (!cut?.pendingAtCleanup || !cut.completionObserved) return violation( 'retired pause host work', 'cleanup did not reach a pending graph continuation', 'receiver premise', ) const fault = differs( 'retired pause host work', 'cleanup retires the graph turn without a host error', [ cut.outstandingAfterCleanup, cut.enteredAfterCleanup, cut.unhandledCompletions, ], [0, 0, 0], ) if (fault) return fault } if (history.interruptPause === 'repeat') { const again = repeatedPause(trace) if (!again) return violation( 'repeated pause before the finite answer', 'the first window request must precede another pause of its graph', 'receiver premise', ) const [settled] = facts< WindowCut & { windowSettled: boolean; rawHasPivot: boolean } >(trace, 'window after repeated pause') const fault = differs( 'second graph pause', publication, [again.windowSettled, again.live, again.window], [false, expected.prior, { offset: 1, limit: 1 }], ) ?? differs( 'window after repeated pause', publication, [ settled?.rawHasPivot, settled?.windowSettled, settled?.live, settled?.window, ], [false, true, expected.final, { offset: 0, limit: 1 }], ) if (fault) return fault } const [initial] = facts(trace, 'initial') const [held] = facts(trace, 'held') const [conflict] = facts(trace, 'cache-conflict') const [queued] = facts(trace, 'answer-enqueued') const [executed] = facts(trace, 'answer-executed') const [returned] = facts(trace, 'answer-callback-returned') const [guard] = facts(trace, 'guard') const [final] = facts(trace, 'final') const loads = facts(trace, 'load') const pivot = pivotOf(history) const staleScope = conflict?.cacheStates.find((cache) => isDeepStrictEqual(cache.key, conflict.actual), ) // Keep a shrink in the same receiving path and scheduler when reporting a stall. const progressPath = `${progress} (${history.route}, ${history.host}, ${history.materialization}, window move ${history.moveWindow})` const unloads = facts<{ scope: Array; pivotPresent: boolean }>( trace, 'unload', ) const pivotFeedback = loads.filter( (load) => isDeepStrictEqual(load.scope, [pivot]) && !load.pivotPresent, ).length > 1 && unloads.filter( (unload) => isDeepStrictEqual(unload.scope, [pivot]) && unload.pivotPresent, ).length > 1 for (const [point, cut] of [ ['initial', initial], ['held', held], ] as const) { const mismatch = differs(point, publication, cut?.status, 'ready') ?? differs(point, publication, cut?.live, expected.prior) ?? differs(point, publication, cut?.downstream, downstream(expected.prior)) if (mismatch) return mismatch } if (history.nonempty && history.route !== 'no-include') { const fault = differs( 'held materialization', publication, held?.materialization, [history.materialization], ) if (fault) return fault } if (!held?.inFlight) return violation( 'held', 'finite provider hold did not reach the receiver', 'receiver premise', ) if (history.truncateDuringReload) { const overlap = supersedingTruncate(trace) if (!overlap) { return violation( 'superseding truncate', 'the truncate did not retire held reload work and start fresh work', 'receiver premise', ) } const fault = differs( 'superseding truncate', publication, overlap.live, expected.prior, ) ?? differs( 'superseding truncate downstream', publication, overlap.downstream, downstream(expected.prior), ) if (fault) return fault } else if (history.route === 'conflict') { if (!validConflict(history, trace) || !conflict || !staleScope) return violation( 'cache conflict', 'opposing installed Query results and current finite request were not observed', 'receiver premise', ) const priorIds = expected.prior.map(({ id }) => id) const mismatch = differs('conflict', publication, conflict.liveIds, priorIds) ?? differs( 'conflict downstream', publication, conflict.downstreamIds, priorIds, ) if (mismatch) return mismatch } if (history.route === 'peer') { const [peer] = facts(trace, 'held-peer') const mismatch = differs( 'held peer', ownership, peer, peer && { ...peer, rawHasPivot: true, peerHasPivot: true, }, ) if (!peer) return violation('held peer', 'peer read did not run', 'receiver premise') if (mismatch) return mismatch } if ( guard === 'awaiting callback' && pivotFeedback && queued && conflict && !executed && loads.some( (load) => load.attempts >= queued.attempts + 32 && load.turns === queued.turns && load.fetches === queued.fetches, ) ) { return violation( 'host callback', 'queued finite answer was starved by repeated acquisitions', progressPath, ) } if (guard === 'awaiting application' && returned && !final) { const tail = eligibleFollowOn(history, trace) if ( tail && pivotFeedback && loads.some( (load) => load.attempts >= tail.attempts + 32 && load.caches.some( (cache) => cache.queryId === tail.queryId && cache.active && isDeepStrictEqual(cache.data, [pivot]) && cache.updateCount === tail.startCount && cache.fetchStatus === 'fetching', ), ) ) { return violation( 'answer application', 'produced finite answer was starved before Query installation', progressPath, ) } } if (guard || !queued || !executed || !returned || !final) return violation( 'receiver completion', 'receiver was incomplete without a measured progress failure', 'receiver premise', ) if (history.orderedFailureBeforeReload === 'current') { const [active] = facts( trace, 'ordered receipt held after independent replay', ) const [failed] = facts< WindowCut & { retry: string; exactFailure: boolean } >(trace, 'owned ordered failure while graph waits') const fault = differs( 'active window keeps its own ordered request', publication, [active?.retry, active?.window, active?.live], ['pending', { offset: 1, limit: 1 }, expected.prior], ) ?? differs( 'active ordered window keeps its own failure', publication, [failed?.retry, failed?.exactFailure, failed?.window, failed?.live], ['rejected', true, { offset: 1, limit: 1 }, expected.prior], ) if (fault) return fault } if (history.orderedFailureBeforeReload === 'previous') { const [old] = facts( trace, 'ordered failure before reload', ) const [fresh] = facts< WindowCut & { committed: boolean previousFailure: boolean orderedRecoveryCalls: number } >(trace, 'window after unrelated replay') const fault = differs( 'original ordered failure', publication, [old?.retry, old?.exactFailure, old?.window, old?.live], ['rejected', true, { offset: 1, limit: 1 }, expected.prior], ) ?? differs( 'fresh window after unrelated replay', publication, [fresh?.committed, fresh?.previousFailure, fresh?.window], [true, false, { offset: 0, limit: 1 }], ) ?? differs( 'fresh ordered acquisition after unrelated replay', publication, (fresh?.orderedRecoveryCalls ?? 0) > 0, true, ) if (fault) return fault } if (history.interruptPause === 'failure') { // A move admitted before reload has its own receipt. That receipt owns // the graph's replay failure after persistence ends, even when the // provider's failed replay is already replaced and its peer still loads. if (activeWindowBeforeReload(history)) { if (!activeWindowReached(trace)) return violation( 'active window reaches a replaced replay failure', 'the admitted window must overlap a real pause and a replaced failure', 'receiver premise', ) const [cut] = facts<{ windowSettled: boolean windowReplayError: boolean window: WindowCut['window'] }>(trace, 'active window after releasing persistence') const error = differs( 'active window after releasing persistence', publication, [cut?.windowSettled, cut?.windowReplayError, cut?.window], [false, true, { offset: 1, limit: 1 }], ) if (error) return error const [retry] = facts( trace, 'retry after active window failure', ) const recovery = differs( 'retry after active window failure', publication, [retry?.retry, retry?.window, retry?.live], ['fulfilled', { offset: 1, limit: 1 }, expected.final], ) if (recovery) return recovery } const [beforeFailure] = facts<{ graphCompletion: string }>( trace, 'reject-paused-replay', ) const [graphVerdict] = facts<{ state: string; replayFailure: boolean }>( trace, 'first paused graph verdict', ) const receiptFault = differs( 'paused graph during replay', publication, beforeFailure?.graphCompletion, 'pending', ) ?? differs( 'first paused graph replay failure', publication, [graphVerdict?.state, graphVerdict?.replayFailure], ['rejected', true], ) if (receiptFault) return receiptFault const replacesFailure = history.siblingReplay === 'replaces-abort-error' const retriesFailure = history.siblingReplay !== 'fails' && !replacesFailure const errors = facts<{ replayFailure: boolean window: WindowCut['window'] }>(trace, 'window-rejected') const releaseCut = history.siblingReplay === 'fails' ? 'late-sibling-failure' : replacesFailure ? 'replaced-failure-before-release' : 'repaired-replay-with-held-sibling' const beforeRelease = trace.findIndex( ({ checkpoint }) => checkpoint === releaseCut, ) const retainedTrace = beforeRelease < 0 ? trace : trace.slice(0, beforeRelease) const rootCuts = facts(retainedTrace, 'live-callback') const downstreamCuts = facts(retainedTrace, 'downstream-callback') const releasedTrace = beforeRelease < 0 ? [] : trace.slice(beforeRelease) const completeCuts = [ expected.prior, expected.replayReplacement, expected.final, ] const releasedRoot = facts(releasedTrace, 'live-callback') const releasedDownstream = facts( releasedTrace, 'downstream-callback', ) const [retry] = facts< WindowCut & { retry: string sameError: boolean siblingHeld: boolean failureReported: boolean } >(trace, 'failed-window-retry') const lateFailure = history.siblingReplay === 'fails' ? differs( 'later failure before earlier replay settles', publication, facts< WindowCut & { earlierReplayHeld: boolean failureReported: boolean windowReplayError: boolean } >(trace, 'late-sibling-failure').map( ({ earlierReplayHeld, failureReported, windowReplayError, live, window, }) => ({ earlierReplayHeld, failureReported, windowReplayError, live, window, }), ), [ { earlierReplayHeld: true, failureReported: true, windowReplayError: true, live: expected.prior, window: { offset: 1, limit: 1 }, }, ], ) : undefined return ( lateFailure ?? (history.siblingReplay === 'abort-error' ? differs( 'abort error from current replay', publication, facts<{ failureReported: boolean sameSourceRuns: boolean siblingHeld: boolean windowReplayError: boolean }>(trace, 'current-abort-error').map( ({ failureReported, sameSourceRuns, siblingHeld, windowReplayError, }) => [ failureReported, sameSourceRuns, siblingHeld, windowReplayError, ], ), [[true, true, true, true]], ) : undefined) ?? differs( 'failed replay window', publication, errors.map(({ replayFailure, window }) => ({ replayFailure, window })), [{ replayFailure: true, window: { offset: 1, limit: 1 } }], ) ?? (replacesFailure ? differs( 'publication before the replacement can apply', publication, facts( trace, 'replaced-failure-before-release', ).map(({ siblingHeld, live, window }) => ({ siblingHeld, live, window, })), [ { siblingHeld: true, live: expected.prior, window: { offset: 1, limit: 1 }, }, ], ) : undefined) ?? differs( 'failed replay success', publication, facts(trace, 'window-settled').length, 0, ) ?? (!retriesFailure ? undefined : differs( 'retry after failed replay', publication, [retry?.retry, retry?.sameError], ['rejected', true], )) ?? (history.siblingReplay && retriesFailure ? differs( 'failed replay beside loading sibling', publication, [ retry?.siblingHeld, retry?.failureReported, retry?.live, retry?.window, ], [true, true, expected.prior, { offset: 1, limit: 1 }], ) : undefined) ?? (history.siblingReplay === 'recovers' ? (differs( 'window after replay recovery with loading sibling', publication, facts< WindowCut & { retry: string sameError: boolean siblingHeld: boolean failureCleared: boolean } >(trace, 'repaired-replay-with-held-sibling').map( ({ retry, sameError, siblingHeld, failureCleared, live, window, }) => ({ retry, sameError, siblingHeld, failureCleared, live, window, }), ), [ { retry: 'pending', sameError: false, siblingHeld: true, failureCleared: true, live: expected.prior, window: { offset: 1, limit: 1 }, }, ], ) ?? differs( 'window after recovered replay applies', publication, facts( trace, 'repaired-window-settled', ).map(({ retry, live, window }) => ({ retry, live, window })), [ { retry: 'fulfilled', live: expected.final, window: { offset: 0, limit: 1 }, }, ], )) : undefined) ?? differs( 'settled publication after replay', publication, [final.status, final.live, final.downstream], ['ready', expected.final, downstream(expected.final)], ) ?? differs( 'failed replay provider settlement', progress, final.inFlight, 0, ) ?? rootCuts .map(({ live }) => differs( 'failed replay root callback', publication, live, expected.prior, ), ) .find(Boolean) ?? downstreamCuts .map((cut) => differs( 'failed replay downstream callback', publication, cut.downstream, downstream(expected.prior), ), ) .find(Boolean) ?? compareReplayPublications( 'root after releasing sibling replay', publication, releasedRoot.map(({ live }) => live), completeCuts, ) ?? compareReplayPublications( 'downstream after releasing sibling replay', publication, releasedDownstream.map(({ downstream: rows }) => rows), completeCuts.map(downstream), ) ?? (beforeRelease < 0 ? undefined : differs( 'final publication to both receivers', publication, [releasedRoot.at(-1)?.live, releasedDownstream.at(-1)?.downstream], [expected.final, downstream(expected.final)], )) ?? pass ) } const mismatch = differs('settled readiness', publication, final.status, 'ready') ?? differs('settled live', publication, final.live, expected.final) ?? differs( 'settled downstream', publication, final.downstream, downstream(expected.final), ) ?? differs('applied source', ownership, final.rawHasPivot, false) ?? differs('final provider hold', progress, final.inFlight, 0) ?? differs( 'receiver cleanup', 'receiver premise', facts(trace, 'cleanup-complete').length, 1, ) if (mismatch) return mismatch if (history.interruptPause && history.interruptPause !== 'repeat') { const [before] = facts(trace, 'retire-paused-run') const [retired] = facts< WindowCut & { status: string; aborted: number; runChanged: boolean } >(trace, 'retired-run') const [request] = facts(trace, 'window-request') const rejected = facts<{ error: string; window: WindowCut['window'] }>( trace, 'window-rejected', ) if ( !before?.pauseCheckpoints || (!watchPausedHost && !request?.pending) || !retired?.aborted || !retired.runChanged ) return violation( 'retiring paused work', 'the interruption must retire the paused graph and its outstanding work', 'receiver premise', ) const window = { offset: 1, limit: 1 } const cleanup = history.interruptPause === 'cleanup' || watchPausedHost // Source reload and graph publication settle at separate cuts. At source // completion the graph may retain the old window or have applied the new // complete rows for its unchanged window. const possibleRows = cleanup ? [[]] : [expected.prior, expected.final] return ( differs('before retirement', publication, before.live, expected.prior) ?? differs( 'downstream before retirement', publication, before.downstream, downstream(expected.prior), ) ?? differs( 'retired window operation', publication, rejected.map(({ error, window }) => ({ error, window })), watchPausedHost ? [] : [{ error: 'AbortError', window }], ) ?? differs( 'retired window success', publication, facts(trace, 'window-settled').length, 0, ) ?? differs( 'retired sync run', publication, [retired.status, retired.window], [cleanup ? 'cleaned-up' : 'ready', window], ) ?? (possibleRows.some((rows) => isDeepStrictEqual(rows, retired.live)) ? undefined : violation( 'retired sync run', 'rows at retirement were incomplete', publication, )) ?? pass ) } // A scope that still has an observer at the quiet cut owes its fresh // result. If the demand retired, other scopes may establish the public // answer. Cache-listener notification order does not gate publication. if (history.route === 'conflict' && staleScope) { const current = final.pivotCaches?.find( (cache) => cache.queryId === staleScope.queryId && cache.active, ) if ( current && (current.updateCount <= staleScope.updateCount || !isDeepStrictEqual(current.data, [])) ) { return violation( 'Query installation', 'the still-observed Query retained its stale answer', progress, ) } } if (history.holdOutput) { const [heldOutput] = facts< WindowCut & { windowSettled: boolean rawHasPivot: boolean acceptedReplacement: boolean sameFacade?: boolean graphCompletion: string pauseCheckpoints: number acceptedReceipts: number } >(trace, 'output-held') const fault = differs( 'held root output', publication, [ heldOutput?.live, heldOutput?.window, heldOutput?.windowSettled, heldOutput?.rawHasPivot, heldOutput?.acceptedReplacement, ], [expected.prior, { offset: 1, limit: 1 }, false, false, true], ) if (fault) return fault if (history.route === 'conflict') { const [graphVerdict] = facts<{ state: string }>( trace, 'first paused graph verdict', ) const receiptFault = differs( 'paused graph during root application', publication, heldOutput?.graphCompletion, 'pending', ) ?? differs( 'first paused graph after root application or retirement', publication, graphVerdict?.state, history.cleanupHeldOutput || history.siblingReplay === 'recovers-with-held-output' ? 'rejected' : 'fulfilled', ) if (receiptFault) return receiptFault } if (history.siblingReplay === 'recovers-with-held-output') { const recovered = heldOutputRecovery(history, trace) const [released] = facts< WindowCut & { retry: string; pendingRoot: number } >(trace, 'recovered window after releasing root output') const recoveryFault = differs( `recovered window with two accepted root receipts (${history.route})`, publication, [recovered?.retry, recovered?.window, recovered?.live], ['pending', { offset: 1, limit: 1 }, expected.prior], ) ?? differs( `recovered window after applied root receipts (${history.route})`, publication, [ released?.retry, released?.window, released?.live, released?.pendingRoot, ], ['fulfilled', { offset: 1, limit: 2 }, expected.final, 0], ) if (recoveryFault) return recoveryFault } if (history.cleanupHeldOutput) { const [closed] = facts( trace, 'settled-after-cleanup', ) const rejected = facts<{ error: string; window: WindowCut['window'] }>( trace, 'window-rejected', ) const window = { offset: 1, limit: 1 } return ( differs( 'held receipt cleanup', publication, [closed?.status, closed?.window, closed?.live], ['cleaned-up', window, []], ) ?? differs( 'held receipt retirement', publication, rejected.map(({ error, window }) => ({ error, window })), [{ error: 'AbortError', window }], ) ?? differs( 'retired receipt success', publication, facts(trace, 'window-settled').length, 0, ) ?? pass ) } if (history.holdFacade) { const identity = differs( 'held facade identity', publication, heldOutput?.sameFacade, true, ) if (identity) return identity } } if (history.holdFacade) { const [prior] = expected.prior const events = facts<{ live: Array detailIds: Array changes: Array<{ type: string; id: number }> }>(trace, 'facade-callback') const fault = differs( 'retained facade deletion', publication, events.map(({ live, detailIds, changes }) => ({ retainsRoot: live.some(({ id }) => id === prior?.id), detailIds, changes, })), [ { retainsRoot: false, detailIds: [], changes: [{ type: 'delete', id: prior?.id }], }, ], ) if (fault) return fault } if (history.moveWindow) { const [admission] = facts(trace, 'window-request') const [settled] = facts(trace, 'window-settled') const fault = differs('held window', publication, admission?.live, expected.prior) ?? differs( 'window admission', publication, [admission?.held, admission?.pending, admission?.window], [true, true, { offset: 1, limit: 1 }], ) ?? differs( 'settled window', publication, [settled?.window, settled?.live], [{ offset: 0, limit: 1 }, expected.final], ) if (fault) return fault } const tail = eligibleFollowOn(history, trace) if (tail) { const installed = facts(trace, 'answer-installed') if ( !installed.some((answer) => installsEmptyAnswer(answer, tail.queryId, tail.startCount), ) ) { return violation( 'Query installation', 'eligible follow-on answer never installed', progress, ) } } for (const answer of facts(trace, 'provider-answer')) { if ( answer.aborted || !answer.active || !isDeepStrictEqual(answer.scope, [pivot]) ) continue if (!isDeepStrictEqual(answer.ids, [])) return violation( 'authored answer', 'the pivot was removed from the backend', 'receiver premise', ) } const cuts = [expected.prior, expected.replayReplacement, expected.final] let rootPublished = 0 let downstreamPublished = 0 const rows = new Map(expected.prior.map((row) => [row.id, row])) let reloading = false let callbackReturned = false for (const { checkpoint, value } of trace) { if (checkpoint === 'reload-start') reloading = true if (checkpoint === 'answer-callback-returned') callbackReturned = true if (!reloading || checkpoint === 'cleanup-complete') continue if (checkpoint === 'root-events') { const { changes } = value as { changes: Array<{ type: string; value: WindowRow }> } for (const change of changes) { const row = change.value const prior = rows.get(row.id) if (change.type === 'delete') { // The removed row can carry a facade whose active interval ended // in this publication. Its identity is tested through the root, // while a live facade read is compared at its own cut. const matches = history.holdFacade ? prior?.id === row.id && prior.rank === row.rank && isDeepStrictEqual(prior.markers, row.markers) : isDeepStrictEqual(prior, row) if (!matches) return violation( 'root event', 'delete payload must match the prior row', publication, ) rows.delete(row.id) } else { if (Boolean(prior) !== (change.type === 'update')) return violation( 'root event', 'operation does not match prior membership', publication, ) rows.set(row.id, row) } } } if (checkpoint === 'live-callback') { const { live, rawHasPivot } = value as Snapshot const next = cuts.findIndex( (cut, index) => index >= rootPublished && isDeepStrictEqual(cut, live), ) if (callbackReturned && !rawHasPivot && next >= 0) rootPublished = next const fault = differs(checkpoint, publication, live, cuts[rootPublished]) ?? differs('root event fold', publication, [...rows.values()], live) if (fault) return fault } if (checkpoint === 'downstream-callback') { const { downstream: actual, rawHasPivot } = value as Snapshot const next = cuts.findIndex( (cut, index) => index >= downstreamPublished && isDeepStrictEqual(downstream(cut), actual), ) if (callbackReturned && !rawHasPivot && next >= 0) downstreamPublished = next const fault = differs( checkpoint, publication, actual, downstream(cuts[downstreamPublished]!), ) if (fault) return fault } } const fold = differs( 'settled root event fold', publication, [...rows.values()], expected.final, ) if (fold) return fold return pass } function downstream(rows: Array) { return rows.map(({ id, rank }) => ({ id, rank })) }