From d86437bf2e623e04317a4c69bef1d13b2baffe90 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 00:11:21 -0600 Subject: [PATCH] Observe conditional Turso store writes in opt-in probes --- pm-stack/aggregator/README.md | 8 + pm-stack/aggregator/src/remote-stores.ts | 4 + pm-stack/aggregator/src/sql-client.ts | 3 +- pm-stack/aggregator/src/turso-stores.ts | 29 ++- .../aggregator/src/turso-write-metrics.ts | 86 ++++++++ .../test/turso-write-metrics.test.ts | 207 ++++++++++++++++++ 6 files changed, 331 insertions(+), 6 deletions(-) create mode 100644 pm-stack/aggregator/src/turso-write-metrics.ts create mode 100644 pm-stack/aggregator/test/turso-write-metrics.test.ts diff --git a/pm-stack/aggregator/README.md b/pm-stack/aggregator/README.md index d8180a7c7c..8b95bf3f18 100644 --- a/pm-stack/aggregator/README.md +++ b/pm-stack/aggregator/README.md @@ -698,6 +698,14 @@ Rules the implementation holds to: active gap windows still advance as before. The daily export is full and ordered by primary key, not incremental by timestamp. +- **Optional internal measurement.** A controlled probe can inject a + `TursoWriteMetrics` instance into `createTursoStoreGetter` and read its + in-process cumulative snapshot. The running service does not create + a meter or publish metrics. Counters only reflect successful responses + for the four UPSERT families and distinguish missing counts from zero. + Skipped means input candidates minus reported affected rows, only when + both are valid. Reported provider writes are not an invoice estimate. + Deploy with `PM_AGG_STORE_BACKEND=turso` (rendered by `install.sh` and set in the NixOS unit); the store token is resolved from Bitwarden by name (`src/turso-stores.ts`). The Supabase project these stores first diff --git a/pm-stack/aggregator/src/remote-stores.ts b/pm-stack/aggregator/src/remote-stores.ts index a750587760..2643e0f0b4 100644 --- a/pm-stack/aggregator/src/remote-stores.ts +++ b/pm-stack/aggregator/src/remote-stores.ts @@ -178,6 +178,7 @@ export function createTursoActionsRemote(getClient: GetClient = getTursoStoreCli "supersedes_action_id", "duplicate_of_action_id", ])}`, + { operation: "actions", candidates: chunk.length }, ); } }, @@ -254,6 +255,7 @@ export function createTursoActivityRemote(getClient: GetClient = getTursoStoreCl ["checkpoint", "seen_ids", "source_status"], true, )}`, + { operation: "activity.ingestion", candidates: chunk.length }, ); } const gapRows = data.gaps.map( @@ -267,6 +269,7 @@ export function createTursoActivityRemote(getClient: GetClient = getTursoStoreCl `insert into public.agg_activity_gaps (id, source, gap_from, gap_to, status, detected_at, resolved_at, updated_at) values\n` + `${chunk.join(",\n")}\n` + `on conflict (id) ${updateChanged("agg_activity_gaps", ["status", "gap_to", "resolved_at"], true)}`, + { operation: "activity.gaps", candidates: chunk.length }, ); } }, @@ -468,6 +471,7 @@ export function createTursoCommentsRemote(getClient: GetClient = getTursoStoreCl "github_error", "github_failed_at", ])}`, + { operation: "comments", candidates: chunk.length }, ); } }, diff --git a/pm-stack/aggregator/src/sql-client.ts b/pm-stack/aggregator/src/sql-client.ts index 625c1a214b..93ec742099 100644 --- a/pm-stack/aggregator/src/sql-client.ts +++ b/pm-stack/aggregator/src/sql-client.ts @@ -3,6 +3,7 @@ // build statements. The only remote implementation is the Turso store // client (turso-stores.ts), whose storeStatement() turns every literal // produced here into a typed argument before it rewrites any syntax. +import type { TursoWriteContext } from "./turso-write-metrics.ts"; /** Escape a string as a SQL string literal (standard-conforming strings: * doubling the single quote is sufficient). */ @@ -23,5 +24,5 @@ export function sqlInt(v: number): string { export interface SqlClient { ref: string; - query>(sql: string): Promise; + query>(sql: string, writeContext?: TursoWriteContext): Promise; } diff --git a/pm-stack/aggregator/src/turso-stores.ts b/pm-stack/aggregator/src/turso-stores.ts index c292d623bd..4409eb2320 100644 --- a/pm-stack/aggregator/src/turso-stores.ts +++ b/pm-stack/aggregator/src/turso-stores.ts @@ -4,6 +4,7 @@ // BEFORE rewriting syntax, so user text/JSON can never be rewritten as SQL. import { resolveBwsSecret } from "./secrets.ts"; import type { SqlClient } from "./sql-client.ts"; +import type { TursoWriteContext, TursoWriteMetrics } from "./turso-write-metrics.ts"; import { DECISION_EVENTS_TURSO_URL, DECISION_EVENTS_TURSO_TOKEN_NAME } from "./decision-events-sync.ts"; export type StoreArg = { type: "text"; value: string }; @@ -96,13 +97,18 @@ export function decodeStoreRow(row: Record): Record>(input: string): Promise { + async query>(input: string, writeContext?: TursoWriteContext): Promise { const stmt = storeStatement(input); const res = await fetchFn(`${endpoint.href.replace(/\/$/, "")}/v2/pipeline`, { method: "POST", @@ -120,7 +126,7 @@ export function createTursoStoreClient(url: string, token: string, fetchFn: type // Do not echo server SQL/errors: they can contain subscription keys. throw new Error("Turso store query failed or returned a malformed result"); } - return result.rows.map((cells: any[]) => { + const rows = result.rows.map((cells: any[]) => { if (cells.length !== result.cols.length) throw new Error("malformed Turso store row"); const row = Object.fromEntries( cells.map((cell, i) => { @@ -137,17 +143,30 @@ export function createTursoStoreClient(url: string, token: string, fetchFn: type ); return decodeStoreRow(row) as T; }); + if (writeMetrics && writeContext && first.response.type === "execute") { + // Never expose SQL, bindings, rows or the rest of the response to the + // meter. Observing a decoded success cannot change the query's result. + try { + writeMetrics.observe(writeContext, result.affected_row_count, result.rows_read, result.rows_written); + } catch { + // A diagnostic failure is not a failed write and must not induce retries. + } + } + return rows; }, }; } -export function createTursoStoreGetter(resolveSecret = resolveBwsSecret): () => Promise { +export function createTursoStoreGetter( + resolveSecret = resolveBwsSecret, + writeMetrics?: TursoWriteMetrics, +): () => Promise { let cached: Promise | null = null; return () => { if (!cached) { const pending = (async () => { const token = await resolveSecret(DECISION_EVENTS_TURSO_TOKEN_NAME); - return token ? createTursoStoreClient(DECISION_EVENTS_TURSO_URL, token) : null; + return token ? createTursoStoreClient(DECISION_EVENTS_TURSO_URL, token, fetch, writeMetrics) : null; })(); cached = pending; void pending.then( diff --git a/pm-stack/aggregator/src/turso-write-metrics.ts b/pm-stack/aggregator/src/turso-write-metrics.ts new file mode 100644 index 0000000000..10e08fffe6 --- /dev/null +++ b/pm-stack/aggregator/src/turso-write-metrics.ts @@ -0,0 +1,86 @@ +// Local-only observations of the four conditional UPSERTs. This is not a +// billing meter: successful statements are a subset of all billed activity. +const labels = [ + "activity.ingestion", + "activity.gaps", + "actions", + "comments", +] as const; +type WriteLabel = (typeof labels)[number]; + +export interface TursoWriteContext { + operation: WriteLabel; + candidates: number; +} + +function counter() { + return { knownBatches: 0, missingBatches: 0, rows: 0 }; +} +function bucket() { + return { + candidates: 0, + affected: counter(), + skipped: 0, + read: counter(), + written: counter(), + }; +} +function boundedAdd(current: number, increment: number): number { + return Math.min(Number.MAX_SAFE_INTEGER, current + increment); +} +function rowCount( + value: unknown, + maximum = Number.MAX_SAFE_INTEGER, +): number | undefined { + return typeof value === "number" && + Number.isSafeInteger(value) && + value >= 0 && + value <= maximum + ? value + : undefined; +} +function addCounter( + target: ReturnType, + value: number | undefined, +): void { + if (value === undefined) + target.missingBatches = boundedAdd(target.missingBatches, 1); + else { + target.knownBatches = boundedAdd(target.knownBatches, 1); + target.rows = boundedAdd(target.rows, value); + } +} + +export class TursoWriteMetrics { + #buckets = { + "activity.ingestion": bucket(), + "activity.gaps": bucket(), + actions: bucket(), + comments: bucket(), + } satisfies Record>; + + observe( + context: TursoWriteContext, + affected: unknown, + read: unknown, + written: unknown, + ): void { + if (!labels.includes(context.operation)) return; + const candidates = rowCount(context.candidates); + if (candidates === undefined || candidates === 0) return; + const target = this.#buckets[context.operation]; + const affectedRows = rowCount(affected, candidates); + target.candidates = boundedAdd(target.candidates, candidates); + addCounter(target.affected, affectedRows); + addCounter(target.read, rowCount(read)); + addCounter(target.written, rowCount(written)); + if (affectedRows !== undefined) + target.skipped = boundedAdd(target.skipped, candidates - affectedRows); + } + + // Cumulative since this meter was created. Fixed-size, detached, and + // available only to internal callers who explicitly install a meter. + snapshot() { + return structuredClone(this.#buckets); + } +} diff --git a/pm-stack/aggregator/test/turso-write-metrics.test.ts b/pm-stack/aggregator/test/turso-write-metrics.test.ts new file mode 100644 index 0000000000..9fd35926b3 --- /dev/null +++ b/pm-stack/aggregator/test/turso-write-metrics.test.ts @@ -0,0 +1,207 @@ +import { expect, test } from "bun:test"; +import { + createTursoActionsRemote, + createTursoActivityRemote, + createTursoCommentsRemote, +} from "../src/remote-stores.ts"; +import { createTursoStoreClient } from "../src/turso-stores.ts"; +import { TursoWriteMetrics } from "../src/turso-write-metrics.ts"; + +const context = { operation: "actions", candidates: 3 } as const; +const input = "insert into public.agg_actions(id) values ('fixture-marker')"; +function success(metrics: Record = {}) { + return Response.json({ + results: [ + { + type: "ok", + response: { + type: "execute", + result: { + cols: [{ name: "value" }], + rows: [[{ type: "text", value: '"fixture-marker"' }]], + ...metrics, + }, + }, + }, + { type: "ok", response: { type: "close" } }, + ], + }); +} + +test("model: only present safe counts contribute and zero is a known count", async () => { + const metrics = new TursoWriteMetrics(); + const requests: unknown[] = []; + const responses = [ + () => success({ affected_row_count: 0, rows_read: 7, rows_written: 0 }), + () => success({ affected_row_count: 2, rows_written: 9 }), + () => success({ affected_row_count: 4, rows_read: "5", rows_written: -1 }), + () => + success({ affected_row_count: 1.5, rows_read: 1e20, rows_written: null }), + () => success(), + ]; + const fetchFn = (async (_url, init) => { + requests.push(JSON.parse(init!.body as string)); + return responses.shift()!(); + }) as typeof fetch; + const client = createTursoStoreClient( + "https://example.test", + "fixture-token", + fetchFn, + metrics, + ); + for (const _ of Array.from({ length: 5 })) { + expect(await client.query(input, context)).toEqual([ + { value: "fixture-marker" }, + ]); + } + expect(requests).toHaveLength(5); + expect( + requests.every( + (req) => JSON.stringify(req) === JSON.stringify(requests[0]), + ), + ).toBe(true); + expect(metrics.snapshot().actions).toEqual({ + candidates: 15, + affected: { knownBatches: 2, missingBatches: 3, rows: 2 }, + skipped: 4, + read: { knownBatches: 1, missingBatches: 4, rows: 7 }, + written: { knownBatches: 2, missingBatches: 3, rows: 9 }, + }); + const copy = metrics.snapshot(); + copy.actions.read.rows = 999; + expect(metrics.snapshot().actions.read.rows).toBe(7); + expect(JSON.stringify(metrics.snapshot())).not.toContain("fixture"); +}); + +test("transport oracle: instrumentation is inert for unlabelled, failed or disabled calls", async () => { + const baseline = new TursoWriteMetrics().snapshot(); + const metrics = new TursoWriteMetrics(); + const requests: unknown[] = []; + let response = () => success({ affected_row_count: 2, rows_written: 3 }); + const fetchFn = (async (_url, init) => { + requests.push(JSON.parse(init!.body as string)); + return response(); + }) as typeof fetch; + const a = createTursoStoreClient( + "https://example.test", + "fixture-token", + fetchFn, + ); + const b = createTursoStoreClient( + "https://example.test", + "fixture-token", + fetchFn, + metrics, + ); + expect(await a.query(input, context)).toEqual(await b.query(input)); + expect(metrics.snapshot()).toEqual(baseline); + response = () => new Response("", { status: 503 }); + await expect(b.query(input, context)).rejects.toThrow("HTTP 503"); + response = () => + Response.json({ + results: [{ type: "error", error: { message: "fixture-private-error" } }], + }); + await expect(b.query(input, context)).rejects.toThrow("malformed result"); + response = () => success({ rows: [[]] }); + await expect(b.query(input, context)).rejects.toThrow( + "malformed Turso store row", + ); + expect(metrics.snapshot()).toEqual(baseline); + expect(requests).toHaveLength(5); + expect( + requests.every( + (req) => JSON.stringify(req) === JSON.stringify(requests[0]), + ), + ).toBe(true); + + class FailedDiagnostic extends TursoWriteMetrics { + observe(): void { + throw new Error("diagnostic failed"); + } + } + response = () => success({ affected_row_count: 2 }); + const c = createTursoStoreClient( + "https://example.test", + "fixture-token", + fetchFn, + new FailedDiagnostic(), + ); + expect(await c.query(input, context)).toEqual([{ value: "fixture-marker" }]); + expect(requests).toHaveLength(6); +}); + +test("adapter oracle: only the four real UPSERTs label their exact chunk sizes", async () => { + const metrics = new TursoWriteMetrics(); + let calls = 0; + const client = createTursoStoreClient( + "https://example.test", + "fixture-token", + (async (_url, _init) => { + calls++; + return success({ cols: [], rows: [], affected_row_count: 0 }); + }) as typeof fetch, + metrics, + ); + const get = async () => client; + const t = "2026-11-23T00:00:00.000Z"; + const author = { kind: "drew", id: "fixture", label: "Fixture" } as const; + await createTursoActionsRemote(get).saveAll( + Array.from({ length: 201 }, (_, n) => ({ + id: String(n), + clientToken: `fixture-${n}`, + kind: "triage", + verb: "acknowledge", + objectRef: "repo#1", + payload: {}, + author, + createdAt: t, + state: "new", + })), + ); + await createTursoActivityRemote(get).save({ + version: 1, + checkpoints: {}, + seen: { github: ["fixture"], watchdog: [] }, + gaps: [ + { + id: "fixture", + source: "watchdog", + from: t, + to: t, + status: "open", + detectedAt: t, + }, + ], + }); + await createTursoCommentsRemote(get).saveAll([ + { + id: "fixture", + objectRef: "repo#1", + kind: "message", + author, + authorVerified: true, + body: "fixture", + createdAt: t, + }, + ]); + expect(calls).toBe(5); + const out = metrics.snapshot(); + expect(Object.keys(out)).toEqual([ + "activity.ingestion", + "activity.gaps", + "actions", + "comments", + ]); + expect( + Object.values(out).map((v) => [ + v.candidates, + v.affected.knownBatches, + v.skipped, + ]), + ).toEqual([ + [2, 1, 2], + [1, 1, 1], + [201, 2, 201], + [1, 1, 1], + ]); +});