Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions pm-stack/aggregator/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -699,6 +699,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
Expand Down
4 changes: 4 additions & 0 deletions pm-stack/aggregator/src/remote-stores.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ export function createTursoActionsRemote(getClient: GetClient = getTursoStoreCli
"supersedes_action_id",
"duplicate_of_action_id",
])}`,
{ operation: "actions", candidates: chunk.length },
);
}
},
Expand Down Expand Up @@ -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(
Expand All @@ -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 },
);
}
},
Expand Down Expand Up @@ -468,6 +471,7 @@ export function createTursoCommentsRemote(getClient: GetClient = getTursoStoreCl
"github_error",
"github_failed_at",
])}`,
{ operation: "comments", candidates: chunk.length },
);
}
},
Expand Down
3 changes: 2 additions & 1 deletion pm-stack/aggregator/src/sql-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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). */
Expand All @@ -23,5 +24,5 @@ export function sqlInt(v: number): string {

export interface SqlClient {
ref: string;
query<T = Record<string, unknown>>(sql: string): Promise<T[]>;
query<T = Record<string, unknown>>(sql: string, writeContext?: TursoWriteContext): Promise<T[]>;
}
29 changes: 24 additions & 5 deletions pm-stack/aggregator/src/turso-stores.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
Expand Down Expand Up @@ -96,13 +97,18 @@ export function decodeStoreRow(row: Record<string, unknown>): Record<string, unk
);
}

export function createTursoStoreClient(url: string, token: string, fetchFn: typeof fetch = fetch): SqlClient {
export function createTursoStoreClient(
url: string,
token: string,
fetchFn: typeof fetch = fetch,
writeMetrics?: TursoWriteMetrics,
): SqlClient {
const endpoint = new URL(url.replace(/^libsql:/, "https:"));
if (endpoint.protocol !== "https:" || endpoint.username || endpoint.password)
throw new Error("invalid Turso store URL");
return {
ref: "turso:fleet-platform",
async query<T = Record<string, unknown>>(input: string): Promise<T[]> {
async query<T = Record<string, unknown>>(input: string, writeContext?: TursoWriteContext): Promise<T[]> {
const stmt = storeStatement(input);
const res = await fetchFn(`${endpoint.href.replace(/\/$/, "")}/v2/pipeline`, {
method: "POST",
Expand All @@ -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) => {
Expand All @@ -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<SqlClient | null> {
export function createTursoStoreGetter(
resolveSecret = resolveBwsSecret,
writeMetrics?: TursoWriteMetrics,
): () => Promise<SqlClient | null> {
let cached: Promise<SqlClient | null> | 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(
Expand Down
86 changes: 86 additions & 0 deletions pm-stack/aggregator/src/turso-write-metrics.ts
Original file line number Diff line number Diff line change
@@ -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<typeof counter>,
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<WriteLabel, ReturnType<typeof bucket>>;

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);
}
}
Loading