feat(reprojection): the one doors-open machinery — budget-capped, yielding, foreground-preempted, atomic-swap; poison records quarantine typed
The generic reprojection engine (pure TS; the twin of the native
implementation — same frozen contract, one shared conformance intent):
register any ProjectionAdapter; advance(family, {budgetMs}) folds facts
from the adapter's own watermark to the head in installments ≤50ms with
real macrotask yields; foreground door traffic bumps the DoorSignal and
an in-flight advance yields within one installment ('preempted');
advanceAll round-robins families fairly. swap(family, buildAdapter) is
the doors-open migration primitive: the OLD projection keeps serving
while the new one builds beside it, the flip is atomic at parity, and a
concurrent second swap refuses typed. A fact the fold cannot apply
(typed ProjectionApplyError) is QUARANTINED — skipped, ledgered,
narrated per-doubling, exposed for refuse-affected-reads — the service
class law's fourth answer: never a wedged rebuild, never a silent skip.
The engine never writes stamps: each adapter owns its durability and its
stamp-after-data discipline. Upgrade, heal, and rebuild are now the same
machinery behind open doors.
FactLogSource wires any host's fact scan in one line
(factSourceFromHost(brain)); window-contract violations are loud.
Pins: 23 unit (budget resume without refold · preemption within one
installment · round-robin fairness under a skewed backlog · build-beside
visibility mid-swap · atomic flip · single-flight refusal · quarantine
skip/ledger/doubling · non-typed throw aborts · losing adapter
discarded) + 3 integration on a real brain (fold matches ground truth ·
doors answer mid-fold with the preemption path exercised · crash
mid-fold resumes from the stamp, never refolds).
Gates: unit 2054/2054 (157 files) · integration 820 (93 files) ·
conformance 31/31.
This commit is contained in:
parent
b47787bbf7
commit
d1651f986c
4 changed files with 1636 additions and 0 deletions
141
src/reprojection/factLogSource.ts
Normal file
141
src/reprojection/factLogSource.ts
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
/**
|
||||
* @module reprojection/factLogSource
|
||||
* @description The production {@link FactSource}: adapts the database's
|
||||
* committed-fact scan to the reprojection engine's `scan(from, limit)`
|
||||
* window contract.
|
||||
*
|
||||
* DEPENDENCY-CLEAN BY DESIGN: this module never imports the database class.
|
||||
* It wraps a host-owned scan callback `(from, limit) => Promise<CommitFact[]>`
|
||||
* injected at construction, so the host wires itself in one line — either by
|
||||
* handing {@link FactLogSource} a callback built on its own scan API, or via
|
||||
* {@link factSourceFromHost}, which builds that callback from any object
|
||||
* structurally exposing `scanFacts` (the batch-handle shape the fact log
|
||||
* serves).
|
||||
*
|
||||
* CONTRACT ENFORCEMENT — loud, never quiet: every `scan` return is checked
|
||||
* (≤ limit facts, strictly ascending generations, all strictly above `from`);
|
||||
* a violating callback throws instead of silently corrupting a fold. A host
|
||||
* with NO fact log throws too — reporting "caught up" against an unscannable
|
||||
* store would be a silent lie.
|
||||
*/
|
||||
|
||||
import type { CommitFact } from '../db/factLog.js'
|
||||
import type { FactSource } from './reprojectionEngine.js'
|
||||
|
||||
/**
|
||||
* The host-owned scan callback: return up to `limit` committed facts with
|
||||
* generation strictly greater than `from`, in ascending generation order;
|
||||
* empty means caught up to the head as of the call.
|
||||
*/
|
||||
export type FactScanCallback = (from: number, limit: number) => Promise<CommitFact[]>
|
||||
|
||||
/**
|
||||
* The minimal structural surface of a fact-scanning host — matches the
|
||||
* database's `scanFacts` shape without importing it. `scanFacts` returns a
|
||||
* handle whose `batches()` yields ordered, non-empty fact batches, or `null`
|
||||
* when the store hosts no fact log.
|
||||
*/
|
||||
export interface FactScanHost {
|
||||
scanFacts(options?: { fromGeneration?: number; batchSize?: number }): {
|
||||
batches: () => AsyncGenerator<{ facts: CommitFact[] }>
|
||||
} | null
|
||||
}
|
||||
|
||||
/**
|
||||
* The production {@link FactSource}: wraps an injected scan callback and
|
||||
* enforces the window contract on every return.
|
||||
*
|
||||
* COST NOTE: each `scan` call is stateless (a fresh window above the caller's
|
||||
* watermark), which is exactly what resumable, crash-tolerant folds need —
|
||||
* at the price of the host re-opening its scan per call. Fine for
|
||||
* budget-capped maintenance; not a hot-path read primitive.
|
||||
*/
|
||||
export class FactLogSource implements FactSource {
|
||||
private readonly scanCallback: FactScanCallback
|
||||
|
||||
/** @param scanCallback - The host-owned scan (see {@link FactScanCallback}). */
|
||||
constructor(scanCallback: FactScanCallback) {
|
||||
if (typeof scanCallback !== 'function') {
|
||||
throw new Error('FactLogSource: a scan callback (from, limit) => Promise<CommitFact[]> is required')
|
||||
}
|
||||
this.scanCallback = scanCallback
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch up to `limit` committed facts strictly above generation `from`,
|
||||
* verifying the callback honored the window contract.
|
||||
* @param from - Exclusive lower bound generation (≥ 0 integer).
|
||||
* @param limit - Maximum facts to return (≥ 1 integer).
|
||||
*/
|
||||
async scan(from: number, limit: number): Promise<CommitFact[]> {
|
||||
if (!Number.isInteger(from) || from < 0) {
|
||||
throw new Error(`FactLogSource.scan: 'from' must be a non-negative integer (got ${from})`)
|
||||
}
|
||||
if (!Number.isInteger(limit) || limit < 1) {
|
||||
throw new Error(`FactLogSource.scan: 'limit' must be a positive integer (got ${limit})`)
|
||||
}
|
||||
const facts = await this.scanCallback(from, limit)
|
||||
if (!Array.isArray(facts)) {
|
||||
throw new Error('FactLogSource.scan: the scan callback must resolve to an array of facts')
|
||||
}
|
||||
if (facts.length > limit) {
|
||||
throw new Error(
|
||||
`FactLogSource.scan: the scan callback returned ${facts.length} facts for limit ${limit} — ` +
|
||||
`contract violation; refusing to fold an oversized window`
|
||||
)
|
||||
}
|
||||
let prev = from
|
||||
for (const fact of facts) {
|
||||
const g = fact?.generation
|
||||
if (typeof g !== 'number' || !Number.isFinite(g) || g <= prev) {
|
||||
throw new Error(
|
||||
`FactLogSource.scan: the scan callback violated the window contract — generation ` +
|
||||
`${String(g)} is not strictly ascending above ${prev} (from=${from}); refusing to fold`
|
||||
)
|
||||
}
|
||||
prev = g
|
||||
}
|
||||
return facts
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the production source from any host structurally exposing
|
||||
* `scanFacts` — the one-line wiring for the database side:
|
||||
*
|
||||
* ```ts
|
||||
* const source = factSourceFromHost(brain)
|
||||
* ```
|
||||
*
|
||||
* Each `scan(from, limit)` opens `scanFacts({ fromGeneration: from + 1,
|
||||
* batchSize: limit })` (the engine's `from` is exclusive; `scanFacts` bounds
|
||||
* are inclusive) and returns the FIRST batch, closing the handle — short
|
||||
* batches at segment boundaries are legal under the source contract (only
|
||||
* EMPTY means caught up). A host with no fact log throws loudly.
|
||||
*
|
||||
* @param host - Any object with the `scanFacts` batch-handle shape.
|
||||
*/
|
||||
export function factSourceFromHost(host: FactScanHost): FactLogSource {
|
||||
if (!host || typeof host.scanFacts !== 'function') {
|
||||
throw new Error('factSourceFromHost: the host must expose scanFacts(options)')
|
||||
}
|
||||
return new FactLogSource(async (from, limit) => {
|
||||
const scan = host.scanFacts({ fromGeneration: from + 1, batchSize: limit })
|
||||
if (scan === null) {
|
||||
throw new Error(
|
||||
'reprojection: this store hosts no fact log — reprojection folds committed facts, ' +
|
||||
'and reporting a caught-up fold against an unscannable store would be a silent lie'
|
||||
)
|
||||
}
|
||||
const iterator = scan.batches()
|
||||
try {
|
||||
const first = await iterator.next()
|
||||
return first.done ? [] : first.value.facts
|
||||
} finally {
|
||||
// Close the abandoned generator so its cleanup (timers) runs.
|
||||
if (typeof iterator.return === 'function') {
|
||||
await iterator.return(undefined)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
648
src/reprojection/reprojectionEngine.ts
Normal file
648
src/reprojection/reprojectionEngine.ts
Normal file
|
|
@ -0,0 +1,648 @@
|
|||
/**
|
||||
* @module reprojection/reprojectionEngine
|
||||
* @description The pure-TS reprojection engine — the ONE machinery for
|
||||
* rebuilding, healing, and migrating persisted projections from the committed
|
||||
* fact log on the JS side. It is the TypeScript twin of the native engine's
|
||||
* reprojection core: the same frozen contract (names AND semantics), so a
|
||||
* single shared conformance suite runs against both implementations and
|
||||
* TS-only deployments green the same rows without native code.
|
||||
*
|
||||
* THE AVAILABILITY LAW — maintenance never holds the doors:
|
||||
*
|
||||
* - Work proceeds in INSTALLMENTS of at most {@link MAX_INSTALLMENT_MS} (50ms)
|
||||
* of wall time each. Between installments the loop awaits a REAL macrotask
|
||||
* boundary (never a busy loop, never a bare microtask), so foreground I/O
|
||||
* and timers always interleave with a running fold.
|
||||
* - Foreground door traffic announces itself via {@link DoorSignal.bump}. An
|
||||
* in-flight {@link ReprojectionEngine.advance} yields at the next
|
||||
* installment boundary and returns `{ status: 'preempted' }` — the doors
|
||||
* never wait for maintenance to finish.
|
||||
* - Budgets are honored: `advance` stops once `budgetMs` is spent and reports
|
||||
* exactly how far it got; a later call RESUMES from the adapter's own
|
||||
* watermark. Nothing ever refolds from zero because a budget ran out.
|
||||
*
|
||||
* WATERMARK DISCIPLINE — the engine NEVER writes stamps. Each adapter's
|
||||
* `applyBatch` owns its own durability and its own stamp (stamp-after-data,
|
||||
* the law stated in src/utils/projectionWatermark.ts); the engine only READS
|
||||
* `watermark()` to decide the next scan window. Delivery is therefore
|
||||
* at-least-once: an adapter that crashed between data and stamp is re-served
|
||||
* the same facts on resume and MUST apply idempotently.
|
||||
*
|
||||
* THE FOUR ANSWER CLASSES of an advance: `'caught-up'` (folded to the head of
|
||||
* the requested window, ledger clean), `'preempted'` (a door bumped),
|
||||
* `'budget-exhausted'` (time ran out mid-stream), and `'quarantined'` (folded
|
||||
* to the head, but this family's quarantine ledger is non-empty — one or more
|
||||
* poison facts are being skipped and reads touching them are suspect).
|
||||
*/
|
||||
|
||||
import type { CommitFact } from '../db/factLog.js'
|
||||
import { prodLog } from '../utils/logger.js'
|
||||
|
||||
/**
|
||||
* The hard ceiling on one installment of fold work, in wall-clock ms. An
|
||||
* advance loop that has run this long without yielding closes the installment
|
||||
* and awaits a macrotask boundary so foreground traffic interleaves. Frozen by
|
||||
* the shared contract — both engines install the same ceiling.
|
||||
*/
|
||||
export const MAX_INSTALLMENT_MS = 50
|
||||
|
||||
/** Default facts-per-batch pulled from the {@link FactSource} per step. */
|
||||
export const DEFAULT_REPROJECTION_BATCH_SIZE = 256
|
||||
|
||||
/**
|
||||
* One registered projection family: a named consumer that folds committed
|
||||
* facts into its own persisted artifact and stamps its own watermark.
|
||||
*
|
||||
* OWNERSHIP: the adapter owns durability AND the stamp. `applyBatch` must
|
||||
* persist its data first and stamp `upTo` after (stamp-after-data), and must
|
||||
* tolerate at-least-once delivery — on resume after a crash between data and
|
||||
* stamp, the same facts arrive again.
|
||||
*/
|
||||
export interface ProjectionAdapter {
|
||||
/** Unique family name — the registry key; one adapter serves a family at a time. */
|
||||
family: string
|
||||
/**
|
||||
* The highest generation this projection's persisted state reflects, or
|
||||
* `null` when the projection is unbuilt/unstamped. The engine reads this to
|
||||
* open the next scan window; it never writes it.
|
||||
*/
|
||||
watermark(): number | null
|
||||
/**
|
||||
* Fold `facts` (ascending generations, all strictly above the current
|
||||
* watermark) into the projection, then stamp `watermark = upTo`.
|
||||
*
|
||||
* `facts` MAY be empty while `upTo` is above the current watermark: that is
|
||||
* a pure watermark advance past quarantined generations — the adapter must
|
||||
* still stamp, or the fold cannot make progress past the poison.
|
||||
*
|
||||
* FAILURE CONTRACT: throw a {@link ProjectionApplyError} to name exactly one
|
||||
* poison fact (the engine quarantines it and continues). ANY other throw
|
||||
* aborts the advance loudly — an unknown failure is never treated as a
|
||||
* poison record.
|
||||
*/
|
||||
applyBatch(facts: CommitFact[], upTo: number): Promise<void>
|
||||
/**
|
||||
* Destroy this adapter's persisted artifact(s). The engine calls this on
|
||||
* the LOSING adapter after a successful {@link ReprojectionEngine.swap},
|
||||
* and on a partially-built replacement whose build aborted.
|
||||
*/
|
||||
discard(): Promise<void>
|
||||
}
|
||||
|
||||
/**
|
||||
* The committed-fact scan the engine folds from. `from` is an EXCLUSIVE lower
|
||||
* bound generation; the source returns at most `limit` facts in ascending
|
||||
* generation order, and an empty array means caught up to the head as of this
|
||||
* call. Short non-empty returns are legal (e.g. a segment boundary) — only
|
||||
* empty means done.
|
||||
*/
|
||||
export interface FactSource {
|
||||
scan(from: number, limit: number): Promise<CommitFact[]>
|
||||
}
|
||||
|
||||
/**
|
||||
* The foreground-preemption signal. Door traffic (foreground reads/writes)
|
||||
* calls {@link DoorSignal.bump}; an in-flight `advance` observes the bump at
|
||||
* its next installment boundary, yields a macrotask, and returns
|
||||
* `{ status: 'preempted' }`. Bumps are edge-triggered per advance: only bumps
|
||||
* that arrive AFTER an advance began preempt it.
|
||||
*/
|
||||
export class DoorSignal {
|
||||
private count = 0
|
||||
|
||||
/** Announce foreground door traffic — an in-flight advance will yield. */
|
||||
bump(): void {
|
||||
this.count++
|
||||
}
|
||||
|
||||
/**
|
||||
* The current bump epoch — the engine snapshots this at advance entry and
|
||||
* compares at installment boundaries.
|
||||
* @internal
|
||||
*/
|
||||
epoch(): number {
|
||||
return this.count
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The TYPED poison-record failure an adapter throws from `applyBatch` to name
|
||||
* exactly one unfoldable fact. The engine quarantines that generation for
|
||||
* that family (skips it, ledgers it, narrates per-doubling) and keeps
|
||||
* folding. Any OTHER throw from `applyBatch` aborts the advance loudly.
|
||||
*/
|
||||
export class ProjectionApplyError extends Error {
|
||||
/** The generation of the fact that cannot be applied. */
|
||||
readonly generation: number
|
||||
/** Optional index of the offending record within the fact's ops. */
|
||||
readonly recordIndex?: number
|
||||
/** The underlying failure. */
|
||||
override readonly cause: unknown
|
||||
|
||||
/**
|
||||
* @param args - `generation` names the poison fact; `recordIndex`
|
||||
* optionally narrows to one record inside it; `cause` carries the
|
||||
* underlying failure.
|
||||
*/
|
||||
constructor(args: { generation: number; recordIndex?: number; cause: unknown }) {
|
||||
super(
|
||||
`projection apply failed at generation ${args.generation}` +
|
||||
(args.recordIndex !== undefined ? ` (record ${args.recordIndex})` : '')
|
||||
)
|
||||
this.name = 'ProjectionApplyError'
|
||||
this.generation = args.generation
|
||||
if (args.recordIndex !== undefined) this.recordIndex = args.recordIndex
|
||||
this.cause = args.cause
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The TYPED single-flight refusal: a second concurrent
|
||||
* {@link ReprojectionEngine.swap} on a family whose replacement is still
|
||||
* building. The caller retries after the in-flight swap settles.
|
||||
*/
|
||||
export class SwapInFlightError extends Error {
|
||||
/** The family whose swap is already in flight. */
|
||||
readonly family: string
|
||||
|
||||
/** @param family - The family whose swap is already in flight. */
|
||||
constructor(family: string) {
|
||||
super(
|
||||
`reprojection: a swap is already in flight for family '${family}' — ` +
|
||||
`swaps are single-flight per family; retry after the current build settles`
|
||||
)
|
||||
this.name = 'SwapInFlightError'
|
||||
this.family = family
|
||||
}
|
||||
}
|
||||
|
||||
/** One quarantined fact in a family's ledger. */
|
||||
export interface QuarantineEntry {
|
||||
/** The generation being skipped for this family. */
|
||||
generation: number
|
||||
/** The typed apply failure that condemned it. */
|
||||
error: ProjectionApplyError
|
||||
/** Wall-clock ms when it was quarantined (diagnostic). */
|
||||
at: number
|
||||
}
|
||||
|
||||
/** How an advance ended — the four answer classes (see the module header). */
|
||||
export type AdvanceStatus = 'caught-up' | 'preempted' | 'budget-exhausted' | 'quarantined'
|
||||
|
||||
/** The result of one advance over one family. */
|
||||
export interface AdvanceResult {
|
||||
/** The answer class. */
|
||||
status: AdvanceStatus
|
||||
/** The family's watermark as stamped by its own adapter, after this advance. */
|
||||
watermark: number | null
|
||||
/**
|
||||
* Facts delivered in SUCCESSFUL `applyBatch` calls during this advance.
|
||||
* At-least-once delivery means retried facts (after a quarantine or a
|
||||
* resume) count again; this is delivered work, not distinct generations.
|
||||
*/
|
||||
applied: number
|
||||
}
|
||||
|
||||
/** The result of a completed {@link ReprojectionEngine.swap}. */
|
||||
export interface SwapResult {
|
||||
/** The NEW adapter's watermark at the flip (parity with the head). */
|
||||
watermark: number | null
|
||||
/** Facts delivered to the replacement during its beside-build. */
|
||||
applied: number
|
||||
}
|
||||
|
||||
/** Constructor options for {@link ReprojectionEngine}. */
|
||||
export interface ReprojectionEngineOptions {
|
||||
/** The committed-fact scan every family folds from. */
|
||||
source: FactSource
|
||||
/** The preemption signal; a fresh one is created when omitted. */
|
||||
doorSignal?: DoorSignal
|
||||
/**
|
||||
* Installment ceiling in ms, `(0, MAX_INSTALLMENT_MS]`. Out-of-range values
|
||||
* throw — the 50ms law is a ceiling, never a suggestion.
|
||||
*/
|
||||
installmentMs?: number
|
||||
/** Facts per {@link FactSource.scan} pull (default {@link DEFAULT_REPROJECTION_BATCH_SIZE}). */
|
||||
batchSize?: number
|
||||
}
|
||||
|
||||
/** The fold-side state shared by a serving family and a swap's beside-build. */
|
||||
interface FoldState {
|
||||
adapter: ProjectionAdapter
|
||||
/** The quarantine ledger, in condemnation order. */
|
||||
quarantine: QuarantineEntry[]
|
||||
/** Generations filtered out of every batch served to this adapter. */
|
||||
skip: Set<number>
|
||||
/** Next ledger size that triggers a narration (1, 2, 4, 8, …). */
|
||||
nextWarnAt: number
|
||||
}
|
||||
|
||||
/** A registered family: fold state plus the single-flight swap latch. */
|
||||
interface FamilyState extends FoldState {
|
||||
swapInFlight: boolean
|
||||
}
|
||||
|
||||
/** One real macrotask boundary — foreground I/O and timers run before resume. */
|
||||
function yieldToDoors(): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
if (typeof setImmediate === 'function') {
|
||||
setImmediate(resolve)
|
||||
} else {
|
||||
setTimeout(resolve, 0)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* The reprojection engine: registry of projection families, budget-capped
|
||||
* yielding advances, round-robin `advanceAll`, atomic build-beside `swap`,
|
||||
* and the per-family quarantine ledger. Pure TS, no storage dependencies —
|
||||
* everything durable lives behind the injected {@link FactSource} and the
|
||||
* registered {@link ProjectionAdapter}s.
|
||||
*/
|
||||
export class ReprojectionEngine {
|
||||
/** The preemption signal foreground door traffic bumps. */
|
||||
readonly doorSignal: DoorSignal
|
||||
|
||||
private readonly source: FactSource
|
||||
private readonly installmentMs: number
|
||||
private readonly batchSize: number
|
||||
private readonly registry = new Map<string, FamilyState>()
|
||||
/** Rotates the family that leads each `advanceAll`, so repeated tiny-budget calls stay fair. */
|
||||
private roundRobinCursor = 0
|
||||
|
||||
/** @param options - See {@link ReprojectionEngineOptions}. */
|
||||
constructor(options: ReprojectionEngineOptions) {
|
||||
if (!options || typeof options.source?.scan !== 'function') {
|
||||
throw new Error('reprojection: a FactSource with scan(from, limit) is required')
|
||||
}
|
||||
const installmentMs = options.installmentMs ?? MAX_INSTALLMENT_MS
|
||||
if (!(installmentMs > 0) || installmentMs > MAX_INSTALLMENT_MS) {
|
||||
throw new Error(
|
||||
`reprojection: installmentMs must be in (0, ${MAX_INSTALLMENT_MS}] — ` +
|
||||
`${installmentMs} would let maintenance hold the doors`
|
||||
)
|
||||
}
|
||||
const batchSize = options.batchSize ?? DEFAULT_REPROJECTION_BATCH_SIZE
|
||||
if (!Number.isInteger(batchSize) || batchSize < 1) {
|
||||
throw new Error(`reprojection: batchSize must be a positive integer (got ${batchSize})`)
|
||||
}
|
||||
this.source = options.source
|
||||
this.doorSignal = options.doorSignal ?? new DoorSignal()
|
||||
this.installmentMs = installmentMs
|
||||
this.batchSize = batchSize
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a projection family. Refuses a duplicate family loudly — the
|
||||
* sanctioned way to replace a serving adapter is {@link swap}, never
|
||||
* re-registration.
|
||||
* @param adapter - The adapter that will serve this family.
|
||||
*/
|
||||
register(adapter: ProjectionAdapter): void {
|
||||
if (!adapter || typeof adapter.family !== 'string' || adapter.family.length === 0) {
|
||||
throw new Error('reprojection: adapter.family must be a non-empty string')
|
||||
}
|
||||
if (this.registry.has(adapter.family)) {
|
||||
throw new Error(
|
||||
`reprojection: family '${adapter.family}' is already registered — ` +
|
||||
`replace a serving adapter via swap(), never by re-registering`
|
||||
)
|
||||
}
|
||||
this.registry.set(adapter.family, {
|
||||
adapter,
|
||||
quarantine: [],
|
||||
skip: new Set(),
|
||||
nextWarnAt: 1,
|
||||
swapInFlight: false
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* The adapter currently serving `family` (observability — e.g. asserting
|
||||
* the old adapter still serves during a swap's beside-build), or undefined
|
||||
* when the family is not registered.
|
||||
* @param family - The family name.
|
||||
*/
|
||||
getAdapter(family: string): ProjectionAdapter | undefined {
|
||||
return this.registry.get(family)?.adapter
|
||||
}
|
||||
|
||||
/**
|
||||
* This family's quarantine ledger (a defensive copy, condemnation order).
|
||||
* Non-empty means one or more generations are being skipped for this
|
||||
* family — the projection owner should refuse reads the skipped facts
|
||||
* would have affected.
|
||||
* @param family - The family name (must be registered).
|
||||
*/
|
||||
quarantined(family: string): QuarantineEntry[] {
|
||||
return [...this.mustGet(family).quarantine]
|
||||
}
|
||||
|
||||
/**
|
||||
* Advance one family toward the head of the fact log (or toward `upTo`),
|
||||
* in installments, under a wall-clock budget, preemptible by the door
|
||||
* signal. Always makes at least ONE step of progress before any budget
|
||||
* check, so a zero budget still advances.
|
||||
*
|
||||
* @param family - The registered family to advance.
|
||||
* @param options - `budgetMs` caps this call's wall time (≥ 0); `upTo`
|
||||
* optionally caps the fold at a generation (inclusive).
|
||||
* @returns The answer class with the adapter-stamped watermark and the
|
||||
* count of facts delivered in successful applyBatch calls.
|
||||
*/
|
||||
async advance(family: string, options: { budgetMs: number; upTo?: number }): Promise<AdvanceResult> {
|
||||
const state = this.mustGet(family)
|
||||
const budgetMs = options?.budgetMs
|
||||
if (typeof budgetMs !== 'number' || !(budgetMs >= 0)) {
|
||||
throw new Error(`reprojection: advance('${family}') requires budgetMs >= 0 (got ${budgetMs})`)
|
||||
}
|
||||
const start = Date.now()
|
||||
const entryEpoch = this.doorSignal.epoch()
|
||||
let installmentStart = start
|
||||
let applied = 0
|
||||
|
||||
for (;;) {
|
||||
const stepResult = await this.step(state, options.upTo)
|
||||
applied += stepResult.applied
|
||||
if (stepResult.done) {
|
||||
return this.completed(state, applied)
|
||||
}
|
||||
// A bump ends the current installment immediately: yield a macrotask so
|
||||
// the foreground work runs, then answer 'preempted'.
|
||||
if (this.doorSignal.epoch() !== entryEpoch) {
|
||||
await yieldToDoors()
|
||||
return { status: 'preempted', watermark: state.adapter.watermark(), applied }
|
||||
}
|
||||
const t = Date.now()
|
||||
if (t - start >= budgetMs) {
|
||||
return { status: 'budget-exhausted', watermark: state.adapter.watermark(), applied }
|
||||
}
|
||||
if (t - installmentStart >= this.installmentMs) {
|
||||
await yieldToDoors()
|
||||
installmentStart = Date.now()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Advance EVERY registered family toward the head under one shared budget,
|
||||
* round-robin at batch granularity — one batch per family per turn — so no
|
||||
* family starves behind another's backlog. The leading family rotates
|
||||
* across calls, keeping repeated tiny-budget calls fair too.
|
||||
*
|
||||
* @param options - `budgetMs` caps this call's total wall time (≥ 0).
|
||||
* @returns Per-family results. Families still mid-stream when the budget
|
||||
* ran out (or a door bumped) report `'budget-exhausted'` (or
|
||||
* `'preempted'`) at their current watermark.
|
||||
*/
|
||||
async advanceAll(options: { budgetMs: number }): Promise<Record<string, AdvanceResult>> {
|
||||
const budgetMs = options?.budgetMs
|
||||
if (typeof budgetMs !== 'number' || !(budgetMs >= 0)) {
|
||||
throw new Error(`reprojection: advanceAll requires budgetMs >= 0 (got ${budgetMs})`)
|
||||
}
|
||||
const start = Date.now()
|
||||
const entryEpoch = this.doorSignal.epoch()
|
||||
let installmentStart = start
|
||||
|
||||
const all = [...this.registry.values()]
|
||||
const results: Record<string, AdvanceResult> = {}
|
||||
const appliedBy = new Map<string, number>()
|
||||
if (all.length === 0) return results
|
||||
|
||||
// Rotate the leader across calls (fairness across repeated small budgets).
|
||||
const offset = this.roundRobinCursor % all.length
|
||||
this.roundRobinCursor = (this.roundRobinCursor + 1) % all.length
|
||||
let queue = [...all.slice(offset), ...all.slice(0, offset)]
|
||||
for (const s of queue) appliedBy.set(s.adapter.family, 0)
|
||||
|
||||
const finish = (
|
||||
status: 'preempted' | 'budget-exhausted',
|
||||
remaining: FamilyState[]
|
||||
): Record<string, AdvanceResult> => {
|
||||
for (const s of remaining) {
|
||||
results[s.adapter.family] = {
|
||||
status,
|
||||
watermark: s.adapter.watermark(),
|
||||
applied: appliedBy.get(s.adapter.family) ?? 0
|
||||
}
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
while (queue.length > 0) {
|
||||
const survivors: FamilyState[] = []
|
||||
for (let i = 0; i < queue.length; i++) {
|
||||
const s = queue[i]
|
||||
const fam = s.adapter.family
|
||||
const stepResult = await this.step(s, undefined)
|
||||
appliedBy.set(fam, (appliedBy.get(fam) ?? 0) + stepResult.applied)
|
||||
if (stepResult.done) {
|
||||
results[fam] = this.completed(s, appliedBy.get(fam) ?? 0)
|
||||
} else {
|
||||
survivors.push(s)
|
||||
}
|
||||
const remaining = [...survivors, ...queue.slice(i + 1)]
|
||||
if (this.doorSignal.epoch() !== entryEpoch) {
|
||||
await yieldToDoors()
|
||||
return finish('preempted', remaining)
|
||||
}
|
||||
const t = Date.now()
|
||||
if (t - start >= budgetMs && remaining.length > 0) {
|
||||
return finish('budget-exhausted', remaining)
|
||||
}
|
||||
if (t - installmentStart >= this.installmentMs) {
|
||||
await yieldToDoors()
|
||||
installmentStart = Date.now()
|
||||
}
|
||||
}
|
||||
queue = survivors
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace a family's adapter by BUILD-BESIDE: the old adapter keeps serving
|
||||
* (stays registered, its watermark untouched) while the replacement folds
|
||||
* from its own watermark (null/0 for a fresh build) to parity with the head
|
||||
* of the fact log. The flip is ATOMIC — a single registry pointer swap with
|
||||
* no await between the parity check and the assignment — and the losing
|
||||
* adapter's `discard()` is called after the flip.
|
||||
*
|
||||
* SINGLE-FLIGHT: a second concurrent swap on the same family throws a
|
||||
* typed {@link SwapInFlightError}. The build yields at installment
|
||||
* boundaries like any fold (doors interleave), but it is never
|
||||
* preemption-aborted — a swap under steady foreground traffic still
|
||||
* completes.
|
||||
*
|
||||
* On a build failure the partially-built replacement is discarded
|
||||
* (best-effort, narrated if that also fails) and the error propagates; the
|
||||
* old adapter keeps serving untouched.
|
||||
*
|
||||
* @param family - The registered family to replace.
|
||||
* @param buildAdapter - Factory for the replacement adapter (same family).
|
||||
* @returns The new adapter's watermark at the flip and the facts delivered
|
||||
* during the build.
|
||||
*/
|
||||
async swap(family: string, buildAdapter: () => Promise<ProjectionAdapter>): Promise<SwapResult> {
|
||||
const state = this.mustGet(family)
|
||||
if (state.swapInFlight) throw new SwapInFlightError(family)
|
||||
state.swapInFlight = true
|
||||
try {
|
||||
const next = await buildAdapter()
|
||||
if (!next || next.family !== family) {
|
||||
throw new Error(
|
||||
`reprojection: swap('${family}') built an adapter for family ` +
|
||||
`'${next?.family}' — the replacement must serve the same family`
|
||||
)
|
||||
}
|
||||
const build: FoldState = { adapter: next, quarantine: [], skip: new Set(), nextWarnAt: 1 }
|
||||
let applied = 0
|
||||
let installmentStart = Date.now()
|
||||
let stalledDoneAt: number | null = null
|
||||
|
||||
try {
|
||||
for (;;) {
|
||||
const stepResult = await this.step(build, undefined)
|
||||
applied += stepResult.applied
|
||||
if (stepResult.applied > 0) stalledDoneAt = null
|
||||
if (stepResult.done) {
|
||||
// Parity: the build just saw an empty scan (caught up to the head
|
||||
// as of that call). The serving adapter can never be beyond the
|
||||
// head, so newWm >= oldWm holds — verified loudly, never assumed.
|
||||
const oldWm = state.adapter.watermark() ?? 0
|
||||
const newWm = next.watermark() ?? 0
|
||||
if (newWm >= oldWm) break
|
||||
if (stalledDoneAt === newWm) {
|
||||
throw new Error(
|
||||
`reprojection: swap('${family}') build is caught up to the head at ` +
|
||||
`generation ${newWm} but the serving adapter claims watermark ${oldWm} — ` +
|
||||
`the serving stamp is beyond the fact log; refusing to flip`
|
||||
)
|
||||
}
|
||||
// The head moved past our scan (a concurrent fold advanced the
|
||||
// serving adapter) — keep folding to the new head.
|
||||
stalledDoneAt = newWm
|
||||
}
|
||||
if (Date.now() - installmentStart >= this.installmentMs) {
|
||||
await yieldToDoors()
|
||||
installmentStart = Date.now()
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
await next.discard().catch((cleanupErr) => {
|
||||
prodLog.warn(
|
||||
`reprojection: swap('${family}') build failed AND the failed build's discard() ` +
|
||||
`also failed — its artifact may be orphaned`,
|
||||
cleanupErr
|
||||
)
|
||||
})
|
||||
throw err
|
||||
}
|
||||
|
||||
// THE FLIP — atomic by construction: no await between the parity check
|
||||
// above and this pointer swap; readers see the old adapter until this
|
||||
// line and the new one from it.
|
||||
const losing = state.adapter
|
||||
state.adapter = next
|
||||
state.quarantine = build.quarantine
|
||||
state.skip = build.skip
|
||||
state.nextWarnAt = build.nextWarnAt
|
||||
|
||||
try {
|
||||
await losing.discard()
|
||||
} catch (discardErr) {
|
||||
// The flip already happened and the new adapter serves; the only loss
|
||||
// is the loser's orphaned artifact — said out loud, never rethrown as
|
||||
// a false swap failure.
|
||||
prodLog.warn(
|
||||
`reprojection: swap('${family}') completed but the losing adapter's discard() ` +
|
||||
`failed — its artifact may be orphaned`,
|
||||
discardErr
|
||||
)
|
||||
}
|
||||
return { watermark: next.watermark(), applied }
|
||||
} finally {
|
||||
state.swapInFlight = false
|
||||
}
|
||||
}
|
||||
|
||||
/** One fold step: scan a batch above the watermark, filter quarantined generations, apply. */
|
||||
private async step(state: FoldState, upTo: number | undefined): Promise<{ done: boolean; applied: number }> {
|
||||
const from = state.adapter.watermark() ?? 0
|
||||
if (upTo !== undefined && from >= upTo) return { done: true, applied: 0 }
|
||||
let facts = await this.source.scan(from, this.batchSize)
|
||||
if (facts.length === 0) return { done: true, applied: 0 }
|
||||
if (upTo !== undefined) {
|
||||
facts = facts.filter((f) => f.generation <= upTo)
|
||||
if (facts.length === 0) return { done: true, applied: 0 }
|
||||
}
|
||||
const batchUpTo = facts[facts.length - 1].generation
|
||||
const toApply = state.skip.size > 0 ? facts.filter((f) => !state.skip.has(f.generation)) : facts
|
||||
try {
|
||||
await state.adapter.applyBatch(toApply, batchUpTo)
|
||||
} catch (err) {
|
||||
if (err instanceof ProjectionApplyError) {
|
||||
this.recordQuarantine(state, err)
|
||||
return { done: false, applied: 0 }
|
||||
}
|
||||
throw err // unknown failure ≠ poison record — abort the advance loudly
|
||||
}
|
||||
// Anti-spin guard: a successful applyBatch that never advances the stamp
|
||||
// would re-serve the same window forever. Refuse loudly instead.
|
||||
const after = state.adapter.watermark() ?? 0
|
||||
if (after <= from) {
|
||||
throw new Error(
|
||||
`reprojection: family '${state.adapter.family}' applyBatch succeeded up to ` +
|
||||
`generation ${batchUpTo} but the watermark did not advance past ${from} — ` +
|
||||
`the adapter is not stamping; refusing to spin`
|
||||
)
|
||||
}
|
||||
return { done: false, applied: toApply.length }
|
||||
}
|
||||
|
||||
/** Ledger a typed apply failure, skip its generation, narrate per-doubling. */
|
||||
private recordQuarantine(state: FoldState, err: ProjectionApplyError): void {
|
||||
if (!Number.isFinite(err.generation)) {
|
||||
throw new Error(
|
||||
`reprojection: family '${state.adapter.family}' threw ProjectionApplyError with a ` +
|
||||
`non-finite generation (${err.generation}) — cannot quarantine; aborting the advance`
|
||||
)
|
||||
}
|
||||
if (state.skip.has(err.generation)) {
|
||||
throw new Error(
|
||||
`reprojection: family '${state.adapter.family}' threw ProjectionApplyError for ` +
|
||||
`generation ${err.generation}, which is ALREADY quarantined and was not in the ` +
|
||||
`batch — the adapter is misreporting; aborting the advance`
|
||||
)
|
||||
}
|
||||
state.skip.add(err.generation)
|
||||
state.quarantine.push({ generation: err.generation, error: err, at: Date.now() })
|
||||
const n = state.quarantine.length
|
||||
if (n === state.nextWarnAt) {
|
||||
state.nextWarnAt *= 2
|
||||
prodLog.warn(
|
||||
`reprojection: family '${state.adapter.family}' quarantined generation ` +
|
||||
`${err.generation} (${n} quarantined total) — the fact is skipped for this family ` +
|
||||
`and ledgered; reads it would have affected should be refused by the owner`,
|
||||
err.cause
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** A window completed: 'caught-up' with a clean ledger, 'quarantined' otherwise. */
|
||||
private completed(state: FoldState, applied: number): AdvanceResult {
|
||||
return {
|
||||
status: state.quarantine.length > 0 ? 'quarantined' : 'caught-up',
|
||||
watermark: state.adapter.watermark(),
|
||||
applied
|
||||
}
|
||||
}
|
||||
|
||||
/** The registered family state, or a loud refusal. */
|
||||
private mustGet(family: string): FamilyState {
|
||||
const state = this.registry.get(family)
|
||||
if (!state) throw new Error(`reprojection: family '${family}' is not registered`)
|
||||
return state
|
||||
}
|
||||
}
|
||||
Reference in a new issue