/** * SQLite-backed persistence store for routing state. * * Implements StorePort from domain types, plus token-bucket rate limiting. * Uses WAL journal mode for concurrent reads and BEGIN IMMEDIATE for * atomic token-bucket operations (prevents TOCTOU on rate_limits table). * * Maps to T013 in the routing pipeline spec. */ import type { ModelProfile, PriceCatalog, RoutingDatasetRecord, RoutingOutcomeRecord, RoutingReasoningTelemetry, RoutingTelemetry, RoutingUsageActuals, SessionPin } from '../../domain/types/entities.js'; import type { ListDatasetOptions, ListOutcomeOptions, ListTelemetryOptions, StorePort } from '../../domain/types/store-port.js'; import { type WriteQueueOptions, type WriteQueueStats } from './write-queue.js'; export interface TokenBucketResult { readonly allowed: boolean; readonly remaining: number; readonly retryAfterSeconds: number | null; } export interface SqliteStoreOptions { /** Path to SQLite database file, or ':memory:' for tests. */ readonly dbPath: string; /** Fleet catalog (loaded from YAML config, not persisted in SQLite). */ readonly models: readonly ModelProfile[]; /** * SP-235 / #142: bounded write-queue tuning (flush interval, size trigger, * capacity). Defaults per docs/sqlite-write-queue-design.md §3.2–3.3. */ readonly writeQueue?: WriteQueueOptions; } export interface CreateStoreResult { readonly store: StorePort; readonly degraded: boolean; } /** * Create a persistence store with corrupt-DB recovery. * * Strategy: * 1. Attempt to open the SQLite DB and run migrations. * 2. On failure (corrupt/locked): rename the file, try fresh creation. * 3. If recreation also fails: fall back to MemoryStore. * * Never throws — the host agent must not crash due to persistence issues. */ export declare function createResilientStore(options: SqliteStoreOptions): CreateStoreResult; export declare class SqliteStore implements StorePort { private readonly db; private readonly models; private readonly consumeTokenTx; /** * SP-235 / #142: hot-path writes (pins, telemetry, dataset, outcomes) * enqueue here and are applied in one transaction per flush. Rate limiting * (consumeToken) stays synchronous — see design doc §2 W6. */ private readonly writeQueue; constructor(options: SqliteStoreOptions); getSessionPin(sessionId: string): Promise; putSessionPin(pin: SessionPin): Promise; deleteSessionPin(sessionId: string): Promise; getModelProfiles(): Promise; getPriceCatalog(): Promise; putPriceCatalog(catalog: PriceCatalog): Promise; appendTelemetry(entry: RoutingTelemetry): void; listTelemetry(options?: ListTelemetryOptions): Promise; private evictTelemetryRows; appendDatasetRecord(entry: RoutingDatasetRecord): void; listDatasetRecords(options?: ListDatasetOptions): Promise; private evictDatasetRows; appendOutcomeRecord(entry: RoutingOutcomeRecord): void; listOutcomeRecords(options?: ListOutcomeOptions): Promise; private evictOutcomeRows; /** * Initialize a token bucket. Idempotent — existing buckets are unchanged. */ initBucket(key: string, maxTokens: number, refillRate: number): void; /** * Atomically attempt to consume tokens from a bucket. * * Uses BEGIN IMMEDIATE to acquire a reserved lock before reading, * preventing TOCTOU races between concurrent consumers. * * SP-234 / #142 audit (W6): intentionally EXCLUDED from the write queue — * this is an atomic read-modify-write on the rate-limit path; batching or * deferring it would break token-bucket correctness. Stays synchronous. */ consumeToken(key: string, cost?: number): TokenBucketResult; /** Run PRAGMA integrity_check. Returns true if the database is healthy. */ checkHealth(): boolean; /** * SP-235 / #142: write-queue stats (enqueued / dropped / flushed / * flushCount) for observability and the SP-236 benchmark. */ get writeQueueStats(): WriteQueueStats; /** Close the database connection, flushing queued writes first (SP-235). */ close(): void; /** * SP-235 / #142: write-queue sink. Applies the drained batch in ONE * SQLite transaction (amortizing WAL commit cost across the batch) and * runs eviction ONCE per flush per touched append-only table, instead of * once per INSERT (design doc §3.2). */ private applyWriteBatch; private insertPinRow; private deletePinRow; private insertTelemetryRow; /** * SP-241 / #164: post-turn usage actuals for the newest row of a request. * Applied synchronously (off the write queue) after a flush so the queued * append for this request is visible first (read-your-writes). A missing * request_id is a no-op — actuals capture must never fail the route. */ updateTelemetryUsageActuals(requestId: string, actuals: RoutingUsageActuals): void; /** * SP-246 / #166: post-delegation adaptive reasoning fields for the newest * row of a request. Applied synchronously (off the write queue) after a * flush so the queued append for this request is visible first * (read-your-writes). A missing request_id is a no-op — reasoning telemetry * must never fail the route. */ updateTelemetryReasoning(requestId: string, fields: RoutingReasoningTelemetry): void; private insertDatasetRow; private insertOutcomeRow; private initialize; private runMigrations; private buildConsumeTokenTx; } export declare class SqliteStoreError extends Error { readonly name = "SqliteStoreError"; constructor(message: string, options?: ErrorOptions); } //# sourceMappingURL=sqlite-store.d.ts.map