@tangle-network/agent-app 0.63.1 → 0.63.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chat-routes/index.js +1 -1
- package/dist/{chunk-MM3GOLHO.js → chunk-HG2WVONR.js} +2 -2
- package/dist/chunk-HG2WVONR.js.map +1 -0
- package/dist/public-consultation/index.js +1 -1
- package/dist/rollout/d1.d.ts +24 -3
- package/dist/rollout/d1.js +46 -24
- package/dist/rollout/d1.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-MM3GOLHO.js.map +0 -1
package/dist/rollout/d1.d.ts
CHANGED
|
@@ -30,7 +30,9 @@ export interface D1LikeForRollout {
|
|
|
30
30
|
};
|
|
31
31
|
};
|
|
32
32
|
}
|
|
33
|
-
|
|
33
|
+
/** Apply through the product migration runner after request_received_at exists. Safe to apply again. */
|
|
34
|
+
export declare const ROLLOUT_TURN_TIMING_REQUEST_WINDOW_INDEX_MIGRATION_SQL = "\nCREATE INDEX IF NOT EXISTS rollout_turn_timing_by_request_origin ON rollout_turn_timing (rollout, request_received_at, at);\nCREATE INDEX IF NOT EXISTS rollout_turn_timing_by_lane_request_origin ON rollout_turn_timing (rollout, lane, request_received_at, at);\n";
|
|
35
|
+
export declare const ROLLOUT_TURN_TIMING_SCHEMA_SQL = "\nCREATE TABLE IF NOT EXISTS rollout_turn_timing (\n turn_id TEXT PRIMARY KEY,\n rollout TEXT NOT NULL,\n workspace_id TEXT NOT NULL,\n lane TEXT NOT NULL,\n admission_ms INTEGER,\n request_received_at INTEGER,\n model TEXT,\n revision TEXT,\n arm TEXT,\n variant TEXT,\n first_visible_ms INTEGER,\n first_text_ms INTEGER,\n settled_ms INTEGER NOT NULL,\n failed INTEGER NOT NULL CHECK (failed IN (0, 1)),\n failure_code TEXT,\n at INTEGER NOT NULL\n);\nCREATE INDEX IF NOT EXISTS rollout_turn_timing_by_lane ON rollout_turn_timing (rollout, lane, at);\n\nCREATE INDEX IF NOT EXISTS rollout_turn_timing_by_request_origin ON rollout_turn_timing (rollout, request_received_at, at);\nCREATE INDEX IF NOT EXISTS rollout_turn_timing_by_lane_request_origin ON rollout_turn_timing (rollout, lane, request_received_at, at);\n\n";
|
|
34
36
|
/** Apply once through the product migration runner to existing tables; historical rows stay NULL. */
|
|
35
37
|
export declare const ROLLOUT_TURN_TIMING_FIRST_VISIBLE_MIGRATION_SQL = "ALTER TABLE rollout_turn_timing ADD COLUMN first_visible_ms INTEGER;";
|
|
36
38
|
/** Apply once through the product migration runner; old rows remain unknown. */
|
|
@@ -97,7 +99,8 @@ export declare function createD1TurnTimingStore(options: {
|
|
|
97
99
|
* Exact origin and stream identity must agree; old NULL origins cannot be guessed. Throws so durable owners retry. */
|
|
98
100
|
recordFacts(facts: NativeTurnTimingFacts): Promise<void>;
|
|
99
101
|
/** Request-origin ruler, separate from the rollout stage's relative latencies and missing-word failure rule.
|
|
100
|
-
*
|
|
102
|
+
* Known origins select the request window; missing observations stay in that denominator. Unknown origins
|
|
103
|
+
* are unassigned and reported separately by settlement window. Limits bound returned rows, not index reads. */
|
|
101
104
|
measureRequestOrigin(input: {
|
|
102
105
|
rollout: string;
|
|
103
106
|
lane?: string;
|
|
@@ -145,11 +148,29 @@ export declare function createD1TurnTimingStore(options: {
|
|
|
145
148
|
rollout: string;
|
|
146
149
|
lane: string | null;
|
|
147
150
|
revision: string | null;
|
|
148
|
-
clock: string;
|
|
149
151
|
limit: number;
|
|
150
152
|
filtered: boolean;
|
|
153
|
+
clock: string;
|
|
151
154
|
};
|
|
152
155
|
population: string;
|
|
156
|
+
unassignedOrigins: {
|
|
157
|
+
samples: number;
|
|
158
|
+
failed: number;
|
|
159
|
+
truncated: boolean;
|
|
160
|
+
selection: {
|
|
161
|
+
rollout: string;
|
|
162
|
+
lane: string | null;
|
|
163
|
+
revision: string | null;
|
|
164
|
+
limit: number;
|
|
165
|
+
filtered: boolean;
|
|
166
|
+
clock: string;
|
|
167
|
+
};
|
|
168
|
+
window: {
|
|
169
|
+
from: string;
|
|
170
|
+
to: string;
|
|
171
|
+
};
|
|
172
|
+
population: string;
|
|
173
|
+
};
|
|
153
174
|
source: string;
|
|
154
175
|
window: {
|
|
155
176
|
from: string;
|
package/dist/rollout/d1.js
CHANGED
|
@@ -9,6 +9,10 @@ import {
|
|
|
9
9
|
import "../chunk-MH74DY2I.js";
|
|
10
10
|
|
|
11
11
|
// src/rollout/d1.ts
|
|
12
|
+
var ROLLOUT_TURN_TIMING_REQUEST_WINDOW_INDEX_MIGRATION_SQL = `
|
|
13
|
+
CREATE INDEX IF NOT EXISTS rollout_turn_timing_by_request_origin ON rollout_turn_timing (rollout, request_received_at, at);
|
|
14
|
+
CREATE INDEX IF NOT EXISTS rollout_turn_timing_by_lane_request_origin ON rollout_turn_timing (rollout, lane, request_received_at, at);
|
|
15
|
+
`;
|
|
12
16
|
var ROLLOUT_TURN_TIMING_SCHEMA_SQL = `
|
|
13
17
|
CREATE TABLE IF NOT EXISTS rollout_turn_timing (
|
|
14
18
|
turn_id TEXT PRIMARY KEY,
|
|
@@ -29,6 +33,7 @@ CREATE TABLE IF NOT EXISTS rollout_turn_timing (
|
|
|
29
33
|
at INTEGER NOT NULL
|
|
30
34
|
);
|
|
31
35
|
CREATE INDEX IF NOT EXISTS rollout_turn_timing_by_lane ON rollout_turn_timing (rollout, lane, at);
|
|
36
|
+
${ROLLOUT_TURN_TIMING_REQUEST_WINDOW_INDEX_MIGRATION_SQL}
|
|
32
37
|
`;
|
|
33
38
|
var ROLLOUT_TURN_TIMING_FIRST_VISIBLE_MIGRATION_SQL = `ALTER TABLE rollout_turn_timing ADD COLUMN first_visible_ms INTEGER;`;
|
|
34
39
|
var ROLLOUT_TURN_TIMING_RULER_MIGRATION_SQL = `
|
|
@@ -170,25 +175,27 @@ function createD1TurnTimingStore(options) {
|
|
|
170
175
|
).run();
|
|
171
176
|
},
|
|
172
177
|
/** Request-origin ruler, separate from the rollout stage's relative latencies and missing-word failure rule.
|
|
173
|
-
*
|
|
178
|
+
* Known origins select the request window; missing observations stay in that denominator. Unknown origins
|
|
179
|
+
* are unassigned and reported separately by settlement window. Limits bound returned rows, not index reads. */
|
|
174
180
|
async measureRequestOrigin(input) {
|
|
175
181
|
const until = input.until ?? now();
|
|
182
|
+
const filters = ["rollout = ?"];
|
|
183
|
+
const bindings = [input.rollout];
|
|
184
|
+
if (input.lane !== void 0) {
|
|
185
|
+
filters.push("lane = ?");
|
|
186
|
+
bindings.push(input.lane);
|
|
187
|
+
}
|
|
188
|
+
if (input.revision === null) filters.push("(revision IS NULL OR revision = '')");
|
|
189
|
+
else if (input.revision !== void 0) {
|
|
190
|
+
filters.push("revision = ?");
|
|
191
|
+
bindings.push(input.revision);
|
|
192
|
+
}
|
|
193
|
+
const selected = filters.join(" AND ");
|
|
176
194
|
const { results = [] } = await options.db.prepare(
|
|
177
195
|
`SELECT turn_id, request_received_at, admission_ms, first_visible_ms, first_text_ms, model, lane, revision, failed FROM rollout_turn_timing
|
|
178
|
-
WHERE
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
).bind(
|
|
182
|
-
input.rollout,
|
|
183
|
-
input.lane ?? null,
|
|
184
|
-
input.lane ?? null,
|
|
185
|
-
input.since,
|
|
186
|
-
until,
|
|
187
|
-
input.revision === void 0 ? 0 : 1,
|
|
188
|
-
input.revision ?? null,
|
|
189
|
-
input.revision ?? null,
|
|
190
|
-
MEASURE_ROW_LIMIT + 1
|
|
191
|
-
).all();
|
|
196
|
+
WHERE ${selected} AND request_received_at >= ? AND request_received_at < ?
|
|
197
|
+
ORDER BY request_received_at DESC LIMIT ?`
|
|
198
|
+
).bind(...bindings, input.since, until, MEASURE_ROW_LIMIT + 1).all();
|
|
192
199
|
const rows = results.slice(0, MEASURE_ROW_LIMIT);
|
|
193
200
|
const storedCoverage = timingCoverage(rows);
|
|
194
201
|
const missingTiming = () => rows.filter((row) => row.admission_ms == null || row.first_visible_ms == null || row.first_text_ms == null);
|
|
@@ -229,6 +236,19 @@ function createD1TurnTimingStore(options) {
|
|
|
229
236
|
const visible = rows.flatMap((row) => row.admission_ms == null || row.first_visible_ms == null ? [] : [row.admission_ms + row.first_visible_ms]).sort((a, b) => a - b);
|
|
230
237
|
const failed = rows.filter((row) => row.failed === 1).length;
|
|
231
238
|
const coverage = timingCoverage(rows);
|
|
239
|
+
const { results: unassigned = [] } = await options.db.prepare(
|
|
240
|
+
`SELECT failed FROM rollout_turn_timing WHERE ${selected} AND request_received_at IS NULL AND at >= ? AND at < ?
|
|
241
|
+
ORDER BY at DESC LIMIT ?`
|
|
242
|
+
).bind(...bindings, input.since, until, MEASURE_ROW_LIMIT + 1).all();
|
|
243
|
+
const unassignedRows = unassigned.slice(0, MEASURE_ROW_LIMIT);
|
|
244
|
+
const selection = {
|
|
245
|
+
rollout: input.rollout,
|
|
246
|
+
lane: input.lane ?? null,
|
|
247
|
+
revision: input.revision === void 0 ? "all" : input.revision,
|
|
248
|
+
limit: MEASURE_ROW_LIMIT,
|
|
249
|
+
filtered: input.lane !== void 0 || input.revision !== void 0
|
|
250
|
+
};
|
|
251
|
+
const window = { from: new Date(input.since).toISOString(), to: new Date(until).toISOString() };
|
|
232
252
|
return {
|
|
233
253
|
samples: rows.length,
|
|
234
254
|
failed,
|
|
@@ -240,17 +260,18 @@ function createD1TurnTimingStore(options) {
|
|
|
240
260
|
unknownCoverage: Object.fromEntries(Object.entries(coverage).map(([key, count]) => [key, rows.length - count])),
|
|
241
261
|
truncated: results.length > MEASURE_ROW_LIMIT,
|
|
242
262
|
observedFacts,
|
|
243
|
-
selection: {
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
263
|
+
selection: { ...selection, clock: "request-received-at" },
|
|
264
|
+
population: "Persisted terminal timing rows with known request origins in the request window; excludes pre-admission, missing-persistence and unassigned-origin attempts.",
|
|
265
|
+
unassignedOrigins: {
|
|
266
|
+
samples: unassignedRows.length,
|
|
267
|
+
failed: unassignedRows.filter((row) => row.failed === 1).length,
|
|
268
|
+
truncated: unassigned.length > MEASURE_ROW_LIMIT,
|
|
269
|
+
selection: { ...selection, clock: "settled-at" },
|
|
270
|
+
window,
|
|
271
|
+
population: "Persisted terminal timing rows with unknown request origins settled in this window; cannot be assigned to the request-window denominator."
|
|
250
272
|
},
|
|
251
|
-
population: "Persisted terminal timing rows in the selection; excludes pre-admission and missing-persistence attempts.",
|
|
252
273
|
source: `rollout_turn_timing lane=${input.lane ?? "all"}`,
|
|
253
|
-
window
|
|
274
|
+
window
|
|
254
275
|
};
|
|
255
276
|
},
|
|
256
277
|
/** Record settled chat outcomes without a product timing/serialization adapter. Read revision at settlement. */
|
|
@@ -299,6 +320,7 @@ function createD1TurnTimingStore(options) {
|
|
|
299
320
|
export {
|
|
300
321
|
ROLLOUT_TURN_TIMING_FIRST_VISIBLE_MIGRATION_SQL,
|
|
301
322
|
ROLLOUT_TURN_TIMING_REQUEST_ORIGIN_MIGRATION_SQL,
|
|
323
|
+
ROLLOUT_TURN_TIMING_REQUEST_WINDOW_INDEX_MIGRATION_SQL,
|
|
302
324
|
ROLLOUT_TURN_TIMING_RULER_MIGRATION_SQL,
|
|
303
325
|
ROLLOUT_TURN_TIMING_SCHEMA_SQL,
|
|
304
326
|
ROLLOUT_TURN_TIMING_VARIANT_MIGRATION_SQL,
|
package/dist/rollout/d1.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/rollout/d1.ts"],"sourcesContent":["/**\n * The measurement a rollout guard reads: one row per turn with its lane, its\n * first visible word and whether it failed, and the stage numbers computed\n * from those rows.\n *\n * Record from the chat route's lifecycle (`onTurnComplete` / `onTurnError`\n * carry `firstVisibleMs`, `firstTextMs` and `durationMs`), then serve `measureStage` behind an\n * operator endpoint that the deploy's `rollout.config.mjs` calls. A stage is\n * measured on the turns of the workspaces it admits, in the lane being rolled\n * out, since the time it went live.\n *\n * By default `record` fills what the product's row leaves out from what the chat route measured for the same\n * `turnId` (its `turnStreamId`): `admissionMs`, `firstVisibleMs`, `firstTextMs`, the served `model` and readable failure, on every\n * lane. It writes only the columns the table has (read once per isolate with `PRAGMA table_info`), so a table that\n * predates a migration keeps recording the columns it has instead of losing the row. `revision`, `arm` and\n * `variant` are the product's and are written when the row carries them. Pass `measuredFacts: false` to write\n * only the row's own values.\n */\nimport { measuredTurnFacts, nativeTimingObservationValues, readableTurnFailure, type NativeTurnTimingFacts } from '../turn-trace/turn-facts'\nimport type { ChatTurnLifecycle, ChatTurnLifecycleComplete, ChatTurnLifecycleError } from '../chat-routes/turn-route-contracts'\nimport { rolloutAdmits, type RolloutStage, type StageMeasurement } from './index'\n\n/** Minimal D1 surface (Cloudflare's `D1Database` satisfies it). */\nexport interface D1LikeForRollout {\n prepare(sql: string): {\n bind(...values: unknown[]): {\n run(): Promise<unknown>\n all<T = Record<string, unknown>>(): Promise<{ results?: T[] }>\n }\n }\n}\n\nexport const ROLLOUT_TURN_TIMING_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS rollout_turn_timing (\n turn_id TEXT PRIMARY KEY,\n rollout TEXT NOT NULL,\n workspace_id TEXT NOT NULL,\n lane TEXT NOT NULL,\n admission_ms INTEGER,\n request_received_at INTEGER,\n model TEXT,\n revision TEXT,\n arm TEXT,\n variant TEXT,\n first_visible_ms INTEGER,\n first_text_ms INTEGER,\n settled_ms INTEGER NOT NULL,\n failed INTEGER NOT NULL CHECK (failed IN (0, 1)),\n failure_code TEXT,\n at INTEGER NOT NULL\n);\nCREATE INDEX IF NOT EXISTS rollout_turn_timing_by_lane ON rollout_turn_timing (rollout, lane, at);\n`\n\n/** Apply once through the product migration runner to existing tables; historical rows stay NULL. */\nexport const ROLLOUT_TURN_TIMING_FIRST_VISIBLE_MIGRATION_SQL =\n `ALTER TABLE rollout_turn_timing ADD COLUMN first_visible_ms INTEGER;`\n\n/** Apply once through the product migration runner; old rows remain unknown. */\nexport const ROLLOUT_TURN_TIMING_RULER_MIGRATION_SQL = `\nALTER TABLE rollout_turn_timing ADD COLUMN admission_ms INTEGER;\nALTER TABLE rollout_turn_timing ADD COLUMN model TEXT;\nALTER TABLE rollout_turn_timing ADD COLUMN revision TEXT;\nALTER TABLE rollout_turn_timing ADD COLUMN arm TEXT;\n`\n\n/** Apply once through the product migration runner before any row carries `variant`; old rows stay NULL. */\nexport const ROLLOUT_TURN_TIMING_VARIANT_MIGRATION_SQL =\n `ALTER TABLE rollout_turn_timing ADD COLUMN variant TEXT;`\n\n/** Additive upgrade for a table created before durable native timing transfer. Historical origins remain NULL. */\nexport const ROLLOUT_TURN_TIMING_REQUEST_ORIGIN_MIGRATION_SQL =\n `ALTER TABLE rollout_turn_timing ADD COLUMN request_received_at INTEGER;`\n\nexport interface TurnTimingRow {\n /** Original route trace epoch, used to prevent facts from a different attempt merging into this row. */\n requestReceivedAt?: number\n /** Request receipt to lifecycle start, before the existing relative durations. */\n admissionMs?: number\n model?: string\n revision?: string\n /** The rollout cohort arm (`assignRolloutArm`, or a synthetic cohort's label). Guards filter on it. */\n arm?: string\n /** The turn's experiment assignments, apart from `arm` so an experiment never changes the cohort a guard reads,\n * e.g. `billing_in_gate=1;prompt_prefix=0`. Written only when set, so a table without the column keeps recording. */\n variant?: string\n turnId: string\n /** The plan this turn counts toward, e.g. `hospitality-routed-chat`. */\n rollout: string\n workspaceId: string\n /** The lane that served the turn, e.g. `routed` or `sandbox`. Only the rolled-out lane is measured. */\n lane: string\n /** From the lifecycle's `firstTextMs`; absent when no word streamed. */\n firstTextMs?: number\n /** From the lifecycle firstVisibleMs; absent when no reasoning, tool or answer streamed. */\n firstVisibleMs?: number\n settledMs: number\n failed: boolean\n /** Defaults to the route's terminal code and redacted explanation. Empty or object-coerced strings use that evidence too. */\n failureCode?: string\n /** Epoch ms; defaults to now. */\n at?: number\n}\n\n/** Rows read for one measurement; a stage needing more than this would be measured on its newest rows. */\nconst MEASURE_ROW_LIMIT = 20_000\n\nfunction percentile(sorted: readonly number[], p: number): number | null {\n if (!sorted.length) return null\n return sorted[Math.min(sorted.length - 1, Math.ceil((p / 100) * sorted.length) - 1)]!\n}\n\n/** Stage metrics from turn rows: first-words and settled percentiles in ms, and the failure rate. */\nexport function stageMetrics(rows: ReadonlyArray<Pick<TurnTimingRow, 'firstVisibleMs' | 'firstTextMs' | 'settledMs' | 'failed'>>) {\n const firstVisible = rows.flatMap(row => row.firstVisibleMs == null ? [] : [row.firstVisibleMs]).sort((a, b) => a - b)\n const firstWords = rows.flatMap(row => row.firstTextMs === undefined || row.firstTextMs === null ? [] : [row.firstTextMs]).sort((a, b) => a - b)\n const settled = rows.filter(row => !row.failed).map(row => row.settledMs).sort((a, b) => a - b)\n return {\n first_visible_p50_ms: percentile(firstVisible, 50),\n first_visible_p90_ms: percentile(firstVisible, 90),\n first_words_p50_ms: percentile(firstWords, 50),\n first_words_p90_ms: percentile(firstWords, 90),\n settled_p50_ms: percentile(settled, 50),\n settled_p90_ms: percentile(settled, 90),\n // A turn that streamed no word failed the user whatever its envelope said.\n failure_rate: rows.length ? rows.filter(row => row.failed || row.firstTextMs === undefined || row.firstTextMs === null).length / rows.length : null,\n }\n}\n\ninterface TimingObservationRow {\n admission_ms: number | null; first_visible_ms: number | null; first_text_ms: number | null\n model: string | null; lane: string | null; revision: string | null\n}\n\nfunction timingCoverage(rows: readonly TimingObservationRow[]) {\n const known = (value: string | null) => Boolean(value?.trim()) && value !== 'unknown'\n return {\n admission: rows.filter(row => row.admission_ms != null).length,\n firstVisible: rows.filter(row => row.first_visible_ms != null).length,\n firstText: rows.filter(row => row.first_text_ms != null).length,\n requestOriginFirstVisible: rows.filter(row => row.admission_ms != null && row.first_visible_ms != null).length,\n model: rows.filter(row => known(row.model)).length,\n lane: rows.filter(row => known(row.lane)).length,\n revision: rows.filter(row => known(row.revision)).length,\n }\n}\n\n/** Columns `record` writes, in order; `variant` and the ruler columns arrived by migration. */\nconst RECORD_COLUMNS = ['turn_id', 'rollout', 'workspace_id', 'lane', 'first_visible_ms', 'first_text_ms', 'settled_ms', 'failed',\n 'failure_code', 'at', 'admission_ms', 'request_received_at', 'model', 'revision', 'arm', 'variant'] as const\ntype RecordColumn = typeof RECORD_COLUMNS[number]\n\n/** The table's columns per database binding, read once per isolate; `null` when they could not be read. */\nconst tableColumns = new WeakMap<object, Promise<ReadonlySet<string> | null>>()\n\nfunction readColumns(db: D1LikeForRollout, refresh: boolean): Promise<ReadonlySet<string> | null> {\n const cached = tableColumns.get(db)\n if (cached && !refresh) return cached\n const read = Promise.resolve().then(() => db.prepare('PRAGMA table_info(rollout_turn_timing)').bind().all<{ name: string }>())\n .then(({ results = [] }) => results.length ? new Set(results.map(column => column.name)) : null, () => null)\n tableColumns.set(db, read)\n return read\n}\n\nfunction roundOrNull(value: number | undefined): number | null {\n return value === undefined ? null : Math.round(value)\n}\n\nexport function createD1TurnTimingStore(options: {\n db: D1LikeForRollout\n now?: () => number\n /** Fill omitted timing and model from the chat route's measurement of the same turn. Default true. */\n measuredFacts?: boolean\n /** Read missing observations from the existing native admission owner. Bound and index the selected identity batches. */\n readObservedFacts?(turns: readonly { turnStreamId: string; requestReceivedAt: number }[]): Promise<readonly NativeTurnTimingFacts[]>\n}) {\n const now = options.now ?? Date.now\n const store = {\n /** Record one settled turn. Idempotent on `turnId`. Default never throws; durable owners opt into retryable writes with throwOnError. */\n async record(row: TurnTimingRow, write?: { throwOnError?: boolean }): Promise<void> {\n try {\n // Read before any await: the facts belong to the request that is settling this turn.\n const measured = options.measuredFacts === false ? undefined : measuredTurnFacts(row.turnId)\n const productFailure = row.failureCode?.trim()\n const values: Record<RecordColumn, unknown> = {\n turn_id: row.turnId, rollout: row.rollout, workspace_id: row.workspaceId, lane: row.lane,\n first_visible_ms: roundOrNull(row.firstVisibleMs ?? measured?.firstVisibleMs),\n first_text_ms: roundOrNull(row.firstTextMs ?? measured?.firstTextMs),\n settled_ms: Math.round(row.settledMs), failed: row.failed ? 1 : 0,\n failure_code: productFailure && productFailure !== '[object Object]'\n ? row.failureCode : measured?.failureCode ?? row.failureCode ?? null,\n at: row.at ?? now(), admission_ms: roundOrNull(row.admissionMs ?? measured?.admissionMs),\n request_received_at: row.requestReceivedAt ?? measured?.requestReceivedAt ?? null,\n model: row.model ?? measured?.model ?? null, revision: row.revision ?? null, arm: row.arm ?? null,\n variant: row.variant ?? null,\n }\n let columns = await readColumns(options.db, false)\n // A value the product passed whose column is unknown: the table may have migrated since the read.\n const explicit: Partial<Record<RecordColumn, unknown>> = { first_visible_ms: row.firstVisibleMs,\n admission_ms: row.admissionMs, request_received_at: row.requestReceivedAt, model: row.model, revision: row.revision, arm: row.arm, variant: row.variant }\n if (columns && Object.entries(explicit).some(([column, value]) => value !== undefined && !columns!.has(column))) {\n columns = await readColumns(options.db, true)\n }\n // Columns unknown (no table yet, or a binding without PRAGMA): every column, `variant` only when set.\n const written = RECORD_COLUMNS.filter(column => columns ? columns.has(column) : column !== 'variant' || row.variant !== undefined)\n await options.db.prepare(\n `INSERT OR IGNORE INTO rollout_turn_timing (${written.join(', ')}) VALUES (${written.map(() => '?').join(', ')})`,\n ).bind(...written.map(column => values[column])).run()\n } catch (error) {\n console.error(JSON.stringify({ event: 'rollout_turn_timing_record_failed', turnId: row.turnId,\n error: error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200) }))\n if (write?.throwOnError) throw error\n }\n },\n\n /** Merge later genuine observations into an already-terminal row. Never inserts or changes its verdict.\n * Exact origin and stream identity must agree; old NULL origins cannot be guessed. Throws so durable owners retry. */\n async recordFacts(facts: NativeTurnTimingFacts): Promise<void> {\n const values = nativeTimingObservationValues(facts)\n await options.db.prepare(`UPDATE rollout_turn_timing SET\n admission_ms = COALESCE(admission_ms, ?), first_visible_ms = COALESCE(first_visible_ms, ?),\n first_text_ms = COALESCE(first_text_ms, ?) WHERE turn_id = ? AND request_received_at = ?\n AND (admission_ms IS NULL OR ? IS NULL OR admission_ms = ?)`)\n .bind(roundOrNull(values.admissionMs), roundOrNull(values.firstVisibleMs), roundOrNull(values.firstTextMs),\n facts.turnStreamId, facts.requestReceivedAt, roundOrNull(values.admissionMs), roundOrNull(values.admissionMs)).run()\n },\n\n /** Request-origin ruler, separate from the rollout stage's relative latencies and missing-word failure rule.\n * Unknown facts stay in the denominator. Newest rows are bounded explicitly and truncation is reported. */\n async measureRequestOrigin(input: { rollout: string; lane?: string; since: number; until?: number; revision?: string | null }) {\n const until = input.until ?? now()\n const { results = [] } = await options.db.prepare(\n `SELECT turn_id, request_received_at, admission_ms, first_visible_ms, first_text_ms, model, lane, revision, failed FROM rollout_turn_timing\n WHERE rollout = ? AND (? IS NULL OR lane = ?) AND at >= ? AND at < ?\n AND (? = 0 OR (? IS NULL AND (revision IS NULL OR revision = '')) OR revision = ?)\n ORDER BY at DESC LIMIT ?`,\n ).bind(input.rollout, input.lane ?? null, input.lane ?? null, input.since, until,\n input.revision === undefined ? 0 : 1, input.revision ?? null, input.revision ?? null, MEASURE_ROW_LIMIT + 1).all<{\n turn_id: string; request_received_at: number | null\n admission_ms: number | null; first_visible_ms: number | null; first_text_ms: number | null\n model: string | null; lane: string | null; revision: string | null; failed: number\n }>()\n const rows = results.slice(0, MEASURE_ROW_LIMIT)\n const storedCoverage = timingCoverage(rows)\n const missingTiming = () => rows.filter(row => row.admission_ms == null || row.first_visible_ms == null || row.first_text_ms == null)\n const missing = missingTiming().filter(row => row.request_received_at != null)\n const observedFacts = { requested: missing.length, matched: 0, observationReadFailed: false,\n configured: Boolean(options.readObservedFacts), unknown: missingTiming().length }\n if (missing.length && options.readObservedFacts) {\n try {\n const observed = await options.readObservedFacts(missing.map(row => ({ turnStreamId: row.turn_id, requestReceivedAt: row.request_received_at! })))\n const byIdentity = new Map(missing.map(row => [row.turn_id, row]))\n const matched = new Set<string>()\n for (const facts of observed) {\n const row = byIdentity.get(facts.turnStreamId)\n if (!row || row.request_received_at !== facts.requestReceivedAt) continue\n let values: ReturnType<typeof nativeTimingObservationValues>\n try { values = nativeTimingObservationValues(facts) } catch { continue }\n if (row.admission_ms != null && values.admissionMs != null && row.admission_ms !== Math.round(values.admissionMs)) continue\n row.admission_ms ??= roundOrNull(values.admissionMs)\n row.first_visible_ms ??= roundOrNull(values.firstVisibleMs)\n row.first_text_ms ??= roundOrNull(values.firstTextMs)\n matched.add(row.turn_id)\n }\n observedFacts.matched = matched.size\n observedFacts.unknown = missingTiming().length\n } catch {\n observedFacts.observationReadFailed = true\n }\n }\n const visible = rows.flatMap(row => row.admission_ms == null || row.first_visible_ms == null\n ? [] : [row.admission_ms + row.first_visible_ms]).sort((a, b) => a - b)\n const failed = rows.filter(row => row.failed === 1).length\n const coverage = timingCoverage(rows)\n return {\n samples: rows.length, failed, failureRate: rows.length ? failed / rows.length : null,\n requestOriginFirstVisibleP50Ms: percentile(visible, 50),\n coverage,\n storedCoverage,\n recoveredCoverage: Object.fromEntries(Object.entries(coverage).map(([key, count]) => [key, count - storedCoverage[key as keyof typeof storedCoverage]])),\n unknownCoverage: Object.fromEntries(Object.entries(coverage).map(([key, count]) => [key, rows.length - count])),\n truncated: results.length > MEASURE_ROW_LIMIT,\n observedFacts,\n selection: { rollout: input.rollout, lane: input.lane ?? null, revision: input.revision === undefined ? 'all' : input.revision,\n clock: 'settled-at', limit: MEASURE_ROW_LIMIT, filtered: input.lane !== undefined || input.revision !== undefined },\n population: 'Persisted terminal timing rows in the selection; excludes pre-admission and missing-persistence attempts.',\n source: `rollout_turn_timing lane=${input.lane ?? 'all'}`,\n window: { from: new Date(input.since).toISOString(), to: new Date(until).toISOString() },\n }\n },\n\n /** Record settled chat outcomes without a product timing/serialization adapter. Read revision at settlement. */\n lifecycle<TContext>(input: {\n rollout: string\n identify(info: ChatTurnLifecycleComplete<TContext> | ChatTurnLifecycleError<TContext>):\n Pick<TurnTimingRow, 'workspaceId' | 'lane' | 'arm' | 'variant' | 'model' | 'failureCode'>\n revision?: () => string | undefined\n }): ChatTurnLifecycle<TContext> {\n const record = (info: ChatTurnLifecycleComplete<TContext> | ChatTurnLifecycleError<TContext>, failed: boolean) => {\n const identified = input.identify(info)\n return store.record({ ...identified, rollout: input.rollout, turnId: info.turnStreamId,\n admissionMs: info.admissionMs, firstVisibleMs: info.firstVisibleMs, firstTextMs: info.firstTextMs,\n model: identified.model ?? ('model' in info ? info.model : undefined),\n failureCode: identified.failureCode ?? (failed ? measuredTurnFacts(info.turnStreamId)?.failureCode\n ?? readableTurnFailure('error' in info ? info.error : undefined) : undefined),\n revision: input.revision ? input.revision() : (typeof process === 'undefined' ? undefined : process.env.DEPLOY_SHA?.trim()),\n settledMs: info.durationMs, failed })\n }\n return { onTurnComplete: info => info.gated ? undefined : record(info, false),\n onTurnError: info => record(info, true) }\n },\n\n /** The stage's numbers: its admitted workspaces' turns in `lane` since `since` (epoch ms). A row carries no\n * workspace creation time, so a workspace admitted only by a `new-since:` entry is not counted. */\n async measureStage(input: { rollout: string; stage: RolloutStage; lane: string; since: number }): Promise<StageMeasurement> {\n const { results = [] } = await options.db.prepare(\n `SELECT workspace_id, first_visible_ms, first_text_ms, settled_ms, failed FROM rollout_turn_timing\n WHERE rollout = ? AND lane = ? AND at >= ? ORDER BY at DESC LIMIT ?`,\n ).bind(input.rollout, input.lane, input.since, MEASURE_ROW_LIMIT).all<{\n workspace_id: string; first_visible_ms: number | null; first_text_ms: number | null; settled_ms: number; failed: number\n }>()\n const rows = results\n .filter(row => rolloutAdmits(input.stage.value, { id: row.workspace_id }))\n .map(row => ({ firstVisibleMs: row.first_visible_ms ?? undefined, firstTextMs: row.first_text_ms ?? undefined, settledMs: row.settled_ms, failed: row.failed === 1 }))\n return {\n stage: input.stage.name,\n lane: input.lane,\n samples: rows.length,\n metrics: stageMetrics(rows),\n source: `rollout_turn_timing lane=${input.lane}`,\n window: { from: new Date(input.since).toISOString(), to: new Date(now()).toISOString() },\n }\n },\n }\n return store\n}\n"],"mappings":";;;;;;;;;;;AAgCO,IAAM,iCAAiC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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GAAG;AAAA,QACxC;AAAA;AAAA,MAEF,EAAE,KAAK,MAAM,SAAS,MAAM,MAAM,MAAM,OAAO,iBAAiB,EAAE,IAE/D;AACH,YAAM,OAAO,QACV,OAAO,SAAO,cAAc,MAAM,MAAM,OAAO,EAAE,IAAI,IAAI,aAAa,CAAC,CAAC,EACxE,IAAI,UAAQ,EAAE,gBAAgB,IAAI,oBAAoB,QAAW,aAAa,IAAI,iBAAiB,QAAW,WAAW,IAAI,YAAY,QAAQ,IAAI,WAAW,EAAE,EAAE;AACvK,aAAO;AAAA,QACL,OAAO,MAAM,MAAM;AAAA,QACnB,MAAM,MAAM;AAAA,QACZ,SAAS,KAAK;AAAA,QACd,SAAS,aAAa,IAAI;AAAA,QAC1B,QAAQ,4BAA4B,MAAM,IAAI;AAAA,QAC9C,QAAQ,EAAE,MAAM,IAAI,KAAK,MAAM,KAAK,EAAE,YAAY,GAAG,IAAI,IAAI,KAAK,IAAI,CAAC,EAAE,YAAY,EAAE;AAAA,MACzF;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/rollout/d1.ts"],"sourcesContent":["/**\n * The measurement a rollout guard reads: one row per turn with its lane, its\n * first visible word and whether it failed, and the stage numbers computed\n * from those rows.\n *\n * Record from the chat route's lifecycle (`onTurnComplete` / `onTurnError`\n * carry `firstVisibleMs`, `firstTextMs` and `durationMs`), then serve `measureStage` behind an\n * operator endpoint that the deploy's `rollout.config.mjs` calls. A stage is\n * measured on the turns of the workspaces it admits, in the lane being rolled\n * out, since the time it went live.\n *\n * By default `record` fills what the product's row leaves out from what the chat route measured for the same\n * `turnId` (its `turnStreamId`): `admissionMs`, `firstVisibleMs`, `firstTextMs`, the served `model` and readable failure, on every\n * lane. It writes only the columns the table has (read once per isolate with `PRAGMA table_info`), so a table that\n * predates a migration keeps recording the columns it has instead of losing the row. `revision`, `arm` and\n * `variant` are the product's and are written when the row carries them. Pass `measuredFacts: false` to write\n * only the row's own values.\n */\nimport { measuredTurnFacts, nativeTimingObservationValues, readableTurnFailure, type NativeTurnTimingFacts } from '../turn-trace/turn-facts'\nimport type { ChatTurnLifecycle, ChatTurnLifecycleComplete, ChatTurnLifecycleError } from '../chat-routes/turn-route-contracts'\nimport { rolloutAdmits, type RolloutStage, type StageMeasurement } from './index'\n\n/** Minimal D1 surface (Cloudflare's `D1Database` satisfies it). */\nexport interface D1LikeForRollout {\n prepare(sql: string): {\n bind(...values: unknown[]): {\n run(): Promise<unknown>\n all<T = Record<string, unknown>>(): Promise<{ results?: T[] }>\n }\n }\n}\n\n/** Apply through the product migration runner after request_received_at exists. Safe to apply again. */\nexport const ROLLOUT_TURN_TIMING_REQUEST_WINDOW_INDEX_MIGRATION_SQL = `\nCREATE INDEX IF NOT EXISTS rollout_turn_timing_by_request_origin ON rollout_turn_timing (rollout, request_received_at, at);\nCREATE INDEX IF NOT EXISTS rollout_turn_timing_by_lane_request_origin ON rollout_turn_timing (rollout, lane, request_received_at, at);\n`\n\nexport const ROLLOUT_TURN_TIMING_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS rollout_turn_timing (\n turn_id TEXT PRIMARY KEY,\n rollout TEXT NOT NULL,\n workspace_id TEXT NOT NULL,\n lane TEXT NOT NULL,\n admission_ms INTEGER,\n request_received_at INTEGER,\n model TEXT,\n revision TEXT,\n arm TEXT,\n variant TEXT,\n first_visible_ms INTEGER,\n first_text_ms INTEGER,\n settled_ms INTEGER NOT NULL,\n failed INTEGER NOT NULL CHECK (failed IN (0, 1)),\n failure_code TEXT,\n at INTEGER NOT NULL\n);\nCREATE INDEX IF NOT EXISTS rollout_turn_timing_by_lane ON rollout_turn_timing (rollout, lane, at);\n${ROLLOUT_TURN_TIMING_REQUEST_WINDOW_INDEX_MIGRATION_SQL}\n`\n\n/** Apply once through the product migration runner to existing tables; historical rows stay NULL. */\nexport const ROLLOUT_TURN_TIMING_FIRST_VISIBLE_MIGRATION_SQL =\n `ALTER TABLE rollout_turn_timing ADD COLUMN first_visible_ms INTEGER;`\n\n/** Apply once through the product migration runner; old rows remain unknown. */\nexport const ROLLOUT_TURN_TIMING_RULER_MIGRATION_SQL = `\nALTER TABLE rollout_turn_timing ADD COLUMN admission_ms INTEGER;\nALTER TABLE rollout_turn_timing ADD COLUMN model TEXT;\nALTER TABLE rollout_turn_timing ADD COLUMN revision TEXT;\nALTER TABLE rollout_turn_timing ADD COLUMN arm TEXT;\n`\n\n/** Apply once through the product migration runner before any row carries `variant`; old rows stay NULL. */\nexport const ROLLOUT_TURN_TIMING_VARIANT_MIGRATION_SQL =\n `ALTER TABLE rollout_turn_timing ADD COLUMN variant TEXT;`\n\n/** Additive upgrade for a table created before durable native timing transfer. Historical origins remain NULL. */\nexport const ROLLOUT_TURN_TIMING_REQUEST_ORIGIN_MIGRATION_SQL =\n `ALTER TABLE rollout_turn_timing ADD COLUMN request_received_at INTEGER;`\n\nexport interface TurnTimingRow {\n /** Original route trace epoch, used to prevent facts from a different attempt merging into this row. */\n requestReceivedAt?: number\n /** Request receipt to lifecycle start, before the existing relative durations. */\n admissionMs?: number\n model?: string\n revision?: string\n /** The rollout cohort arm (`assignRolloutArm`, or a synthetic cohort's label). Guards filter on it. */\n arm?: string\n /** The turn's experiment assignments, apart from `arm` so an experiment never changes the cohort a guard reads,\n * e.g. `billing_in_gate=1;prompt_prefix=0`. Written only when set, so a table without the column keeps recording. */\n variant?: string\n turnId: string\n /** The plan this turn counts toward, e.g. `hospitality-routed-chat`. */\n rollout: string\n workspaceId: string\n /** The lane that served the turn, e.g. `routed` or `sandbox`. Only the rolled-out lane is measured. */\n lane: string\n /** From the lifecycle's `firstTextMs`; absent when no word streamed. */\n firstTextMs?: number\n /** From the lifecycle firstVisibleMs; absent when no reasoning, tool or answer streamed. */\n firstVisibleMs?: number\n settledMs: number\n failed: boolean\n /** Defaults to the route's terminal code and redacted explanation. Empty or object-coerced strings use that evidence too. */\n failureCode?: string\n /** Epoch ms; defaults to now. */\n at?: number\n}\n\n/** Rows read for one measurement; a stage needing more than this would be measured on its newest rows. */\nconst MEASURE_ROW_LIMIT = 20_000\n\nfunction percentile(sorted: readonly number[], p: number): number | null {\n if (!sorted.length) return null\n return sorted[Math.min(sorted.length - 1, Math.ceil((p / 100) * sorted.length) - 1)]!\n}\n\n/** Stage metrics from turn rows: first-words and settled percentiles in ms, and the failure rate. */\nexport function stageMetrics(rows: ReadonlyArray<Pick<TurnTimingRow, 'firstVisibleMs' | 'firstTextMs' | 'settledMs' | 'failed'>>) {\n const firstVisible = rows.flatMap(row => row.firstVisibleMs == null ? [] : [row.firstVisibleMs]).sort((a, b) => a - b)\n const firstWords = rows.flatMap(row => row.firstTextMs === undefined || row.firstTextMs === null ? [] : [row.firstTextMs]).sort((a, b) => a - b)\n const settled = rows.filter(row => !row.failed).map(row => row.settledMs).sort((a, b) => a - b)\n return {\n first_visible_p50_ms: percentile(firstVisible, 50),\n first_visible_p90_ms: percentile(firstVisible, 90),\n first_words_p50_ms: percentile(firstWords, 50),\n first_words_p90_ms: percentile(firstWords, 90),\n settled_p50_ms: percentile(settled, 50),\n settled_p90_ms: percentile(settled, 90),\n // A turn that streamed no word failed the user whatever its envelope said.\n failure_rate: rows.length ? rows.filter(row => row.failed || row.firstTextMs === undefined || row.firstTextMs === null).length / rows.length : null,\n }\n}\n\ninterface TimingObservationRow {\n admission_ms: number | null; first_visible_ms: number | null; first_text_ms: number | null\n model: string | null; lane: string | null; revision: string | null\n}\n\nfunction timingCoverage(rows: readonly TimingObservationRow[]) {\n const known = (value: string | null) => Boolean(value?.trim()) && value !== 'unknown'\n return {\n admission: rows.filter(row => row.admission_ms != null).length,\n firstVisible: rows.filter(row => row.first_visible_ms != null).length,\n firstText: rows.filter(row => row.first_text_ms != null).length,\n requestOriginFirstVisible: rows.filter(row => row.admission_ms != null && row.first_visible_ms != null).length,\n model: rows.filter(row => known(row.model)).length,\n lane: rows.filter(row => known(row.lane)).length,\n revision: rows.filter(row => known(row.revision)).length,\n }\n}\n\n/** Columns `record` writes, in order; `variant` and the ruler columns arrived by migration. */\nconst RECORD_COLUMNS = ['turn_id', 'rollout', 'workspace_id', 'lane', 'first_visible_ms', 'first_text_ms', 'settled_ms', 'failed',\n 'failure_code', 'at', 'admission_ms', 'request_received_at', 'model', 'revision', 'arm', 'variant'] as const\ntype RecordColumn = typeof RECORD_COLUMNS[number]\n\n/** The table's columns per database binding, read once per isolate; `null` when they could not be read. */\nconst tableColumns = new WeakMap<object, Promise<ReadonlySet<string> | null>>()\n\nfunction readColumns(db: D1LikeForRollout, refresh: boolean): Promise<ReadonlySet<string> | null> {\n const cached = tableColumns.get(db)\n if (cached && !refresh) return cached\n const read = Promise.resolve().then(() => db.prepare('PRAGMA table_info(rollout_turn_timing)').bind().all<{ name: string }>())\n .then(({ results = [] }) => results.length ? new Set(results.map(column => column.name)) : null, () => null)\n tableColumns.set(db, read)\n return read\n}\n\nfunction roundOrNull(value: number | undefined): number | null {\n return value === undefined ? null : Math.round(value)\n}\n\nexport function createD1TurnTimingStore(options: {\n db: D1LikeForRollout\n now?: () => number\n /** Fill omitted timing and model from the chat route's measurement of the same turn. Default true. */\n measuredFacts?: boolean\n /** Read missing observations from the existing native admission owner. Bound and index the selected identity batches. */\n readObservedFacts?(turns: readonly { turnStreamId: string; requestReceivedAt: number }[]): Promise<readonly NativeTurnTimingFacts[]>\n}) {\n const now = options.now ?? Date.now\n const store = {\n /** Record one settled turn. Idempotent on `turnId`. Default never throws; durable owners opt into retryable writes with throwOnError. */\n async record(row: TurnTimingRow, write?: { throwOnError?: boolean }): Promise<void> {\n try {\n // Read before any await: the facts belong to the request that is settling this turn.\n const measured = options.measuredFacts === false ? undefined : measuredTurnFacts(row.turnId)\n const productFailure = row.failureCode?.trim()\n const values: Record<RecordColumn, unknown> = {\n turn_id: row.turnId, rollout: row.rollout, workspace_id: row.workspaceId, lane: row.lane,\n first_visible_ms: roundOrNull(row.firstVisibleMs ?? measured?.firstVisibleMs),\n first_text_ms: roundOrNull(row.firstTextMs ?? measured?.firstTextMs),\n settled_ms: Math.round(row.settledMs), failed: row.failed ? 1 : 0,\n failure_code: productFailure && productFailure !== '[object Object]'\n ? row.failureCode : measured?.failureCode ?? row.failureCode ?? null,\n at: row.at ?? now(), admission_ms: roundOrNull(row.admissionMs ?? measured?.admissionMs),\n request_received_at: row.requestReceivedAt ?? measured?.requestReceivedAt ?? null,\n model: row.model ?? measured?.model ?? null, revision: row.revision ?? null, arm: row.arm ?? null,\n variant: row.variant ?? null,\n }\n let columns = await readColumns(options.db, false)\n // A value the product passed whose column is unknown: the table may have migrated since the read.\n const explicit: Partial<Record<RecordColumn, unknown>> = { first_visible_ms: row.firstVisibleMs,\n admission_ms: row.admissionMs, request_received_at: row.requestReceivedAt, model: row.model, revision: row.revision, arm: row.arm, variant: row.variant }\n if (columns && Object.entries(explicit).some(([column, value]) => value !== undefined && !columns!.has(column))) {\n columns = await readColumns(options.db, true)\n }\n // Columns unknown (no table yet, or a binding without PRAGMA): every column, `variant` only when set.\n const written = RECORD_COLUMNS.filter(column => columns ? columns.has(column) : column !== 'variant' || row.variant !== undefined)\n await options.db.prepare(\n `INSERT OR IGNORE INTO rollout_turn_timing (${written.join(', ')}) VALUES (${written.map(() => '?').join(', ')})`,\n ).bind(...written.map(column => values[column])).run()\n } catch (error) {\n console.error(JSON.stringify({ event: 'rollout_turn_timing_record_failed', turnId: row.turnId,\n error: error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200) }))\n if (write?.throwOnError) throw error\n }\n },\n\n /** Merge later genuine observations into an already-terminal row. Never inserts or changes its verdict.\n * Exact origin and stream identity must agree; old NULL origins cannot be guessed. Throws so durable owners retry. */\n async recordFacts(facts: NativeTurnTimingFacts): Promise<void> {\n const values = nativeTimingObservationValues(facts)\n await options.db.prepare(`UPDATE rollout_turn_timing SET\n admission_ms = COALESCE(admission_ms, ?), first_visible_ms = COALESCE(first_visible_ms, ?),\n first_text_ms = COALESCE(first_text_ms, ?) WHERE turn_id = ? AND request_received_at = ?\n AND (admission_ms IS NULL OR ? IS NULL OR admission_ms = ?)`)\n .bind(roundOrNull(values.admissionMs), roundOrNull(values.firstVisibleMs), roundOrNull(values.firstTextMs),\n facts.turnStreamId, facts.requestReceivedAt, roundOrNull(values.admissionMs), roundOrNull(values.admissionMs)).run()\n },\n\n /** Request-origin ruler, separate from the rollout stage's relative latencies and missing-word failure rule.\n * Known origins select the request window; missing observations stay in that denominator. Unknown origins\n * are unassigned and reported separately by settlement window. Limits bound returned rows, not index reads. */\n async measureRequestOrigin(input: { rollout: string; lane?: string; since: number; until?: number; revision?: string | null }) {\n const until = input.until ?? now()\n const filters: string[] = ['rollout = ?']\n const bindings: unknown[] = [input.rollout]\n if (input.lane !== undefined) { filters.push('lane = ?'); bindings.push(input.lane) }\n if (input.revision === null) filters.push(\"(revision IS NULL OR revision = '')\")\n else if (input.revision !== undefined) { filters.push('revision = ?'); bindings.push(input.revision) }\n const selected = filters.join(' AND ')\n const { results = [] } = await options.db.prepare(\n `SELECT turn_id, request_received_at, admission_ms, first_visible_ms, first_text_ms, model, lane, revision, failed FROM rollout_turn_timing\n WHERE ${selected} AND request_received_at >= ? AND request_received_at < ?\n ORDER BY request_received_at DESC LIMIT ?`,\n ).bind(...bindings, input.since, until, MEASURE_ROW_LIMIT + 1).all<{\n turn_id: string; request_received_at: number | null\n admission_ms: number | null; first_visible_ms: number | null; first_text_ms: number | null\n model: string | null; lane: string | null; revision: string | null; failed: number\n }>()\n const rows = results.slice(0, MEASURE_ROW_LIMIT)\n const storedCoverage = timingCoverage(rows)\n const missingTiming = () => rows.filter(row => row.admission_ms == null || row.first_visible_ms == null || row.first_text_ms == null)\n const missing = missingTiming().filter(row => row.request_received_at != null)\n const observedFacts = { requested: missing.length, matched: 0, observationReadFailed: false,\n configured: Boolean(options.readObservedFacts), unknown: missingTiming().length }\n if (missing.length && options.readObservedFacts) {\n try {\n const observed = await options.readObservedFacts(missing.map(row => ({ turnStreamId: row.turn_id, requestReceivedAt: row.request_received_at! })))\n const byIdentity = new Map(missing.map(row => [row.turn_id, row]))\n const matched = new Set<string>()\n for (const facts of observed) {\n const row = byIdentity.get(facts.turnStreamId)\n if (!row || row.request_received_at !== facts.requestReceivedAt) continue\n let values: ReturnType<typeof nativeTimingObservationValues>\n try { values = nativeTimingObservationValues(facts) } catch { continue }\n if (row.admission_ms != null && values.admissionMs != null && row.admission_ms !== Math.round(values.admissionMs)) continue\n row.admission_ms ??= roundOrNull(values.admissionMs)\n row.first_visible_ms ??= roundOrNull(values.firstVisibleMs)\n row.first_text_ms ??= roundOrNull(values.firstTextMs)\n matched.add(row.turn_id)\n }\n observedFacts.matched = matched.size\n observedFacts.unknown = missingTiming().length\n } catch {\n observedFacts.observationReadFailed = true\n }\n }\n const visible = rows.flatMap(row => row.admission_ms == null || row.first_visible_ms == null\n ? [] : [row.admission_ms + row.first_visible_ms]).sort((a, b) => a - b)\n const failed = rows.filter(row => row.failed === 1).length\n const coverage = timingCoverage(rows)\n const { results: unassigned = [] } = await options.db.prepare(\n `SELECT failed FROM rollout_turn_timing WHERE ${selected} AND request_received_at IS NULL AND at >= ? AND at < ?\n ORDER BY at DESC LIMIT ?`,\n ).bind(...bindings, input.since, until, MEASURE_ROW_LIMIT + 1).all<{ failed: number }>()\n const unassignedRows = unassigned.slice(0, MEASURE_ROW_LIMIT)\n const selection = { rollout: input.rollout, lane: input.lane ?? null, revision: input.revision === undefined ? 'all' : input.revision,\n limit: MEASURE_ROW_LIMIT, filtered: input.lane !== undefined || input.revision !== undefined }\n const window = { from: new Date(input.since).toISOString(), to: new Date(until).toISOString() }\n return {\n samples: rows.length, failed, failureRate: rows.length ? failed / rows.length : null,\n requestOriginFirstVisibleP50Ms: percentile(visible, 50),\n coverage,\n storedCoverage,\n recoveredCoverage: Object.fromEntries(Object.entries(coverage).map(([key, count]) => [key, count - storedCoverage[key as keyof typeof storedCoverage]])),\n unknownCoverage: Object.fromEntries(Object.entries(coverage).map(([key, count]) => [key, rows.length - count])),\n truncated: results.length > MEASURE_ROW_LIMIT,\n observedFacts,\n selection: { ...selection, clock: 'request-received-at' },\n population: 'Persisted terminal timing rows with known request origins in the request window; excludes pre-admission, missing-persistence and unassigned-origin attempts.',\n unassignedOrigins: { samples: unassignedRows.length, failed: unassignedRows.filter(row => row.failed === 1).length,\n truncated: unassigned.length > MEASURE_ROW_LIMIT, selection: { ...selection, clock: 'settled-at' }, window,\n population: 'Persisted terminal timing rows with unknown request origins settled in this window; cannot be assigned to the request-window denominator.' },\n source: `rollout_turn_timing lane=${input.lane ?? 'all'}`,\n window,\n }\n },\n\n /** Record settled chat outcomes without a product timing/serialization adapter. Read revision at settlement. */\n lifecycle<TContext>(input: {\n rollout: string\n identify(info: ChatTurnLifecycleComplete<TContext> | ChatTurnLifecycleError<TContext>):\n Pick<TurnTimingRow, 'workspaceId' | 'lane' | 'arm' | 'variant' | 'model' | 'failureCode'>\n revision?: () => string | undefined\n }): ChatTurnLifecycle<TContext> {\n const record = (info: ChatTurnLifecycleComplete<TContext> | ChatTurnLifecycleError<TContext>, failed: boolean) => {\n const identified = input.identify(info)\n return store.record({ ...identified, rollout: input.rollout, turnId: info.turnStreamId,\n admissionMs: info.admissionMs, firstVisibleMs: info.firstVisibleMs, firstTextMs: info.firstTextMs,\n model: identified.model ?? ('model' in info ? info.model : undefined),\n failureCode: identified.failureCode ?? (failed ? measuredTurnFacts(info.turnStreamId)?.failureCode\n ?? readableTurnFailure('error' in info ? info.error : undefined) : undefined),\n revision: input.revision ? input.revision() : (typeof process === 'undefined' ? undefined : process.env.DEPLOY_SHA?.trim()),\n settledMs: info.durationMs, failed })\n }\n return { onTurnComplete: info => info.gated ? undefined : record(info, false),\n onTurnError: info => record(info, true) }\n },\n\n /** The stage's numbers: its admitted workspaces' turns in `lane` since `since` (epoch ms). A row carries no\n * workspace creation time, so a workspace admitted only by a `new-since:` entry is not counted. */\n async measureStage(input: { rollout: string; stage: RolloutStage; lane: string; since: number }): Promise<StageMeasurement> {\n const { results = [] } = await options.db.prepare(\n `SELECT workspace_id, first_visible_ms, first_text_ms, settled_ms, failed FROM rollout_turn_timing\n WHERE rollout = ? AND lane = ? AND at >= ? ORDER BY at DESC LIMIT ?`,\n ).bind(input.rollout, input.lane, input.since, MEASURE_ROW_LIMIT).all<{\n workspace_id: string; first_visible_ms: number | null; first_text_ms: number | null; settled_ms: number; failed: number\n }>()\n const rows = results\n .filter(row => rolloutAdmits(input.stage.value, { id: row.workspace_id }))\n .map(row => ({ firstVisibleMs: row.first_visible_ms ?? undefined, firstTextMs: row.first_text_ms ?? undefined, settledMs: row.settled_ms, failed: row.failed === 1 }))\n return {\n stage: input.stage.name,\n lane: input.lane,\n samples: rows.length,\n metrics: stageMetrics(rows),\n source: `rollout_turn_timing lane=${input.lane}`,\n window: { from: new Date(input.since).toISOString(), to: new Date(now()).toISOString() },\n }\n },\n }\n return store\n}\n"],"mappings":";;;;;;;;;;;AAiCO,IAAM,yDAAyD;AAAA;AAAA;AAAA;AAK/D,IAAM,iCAAiC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAoB5C,sDAAsD;AAAA;AAIjD,IAAM,kDACX;AAGK,IAAM,0CAA0C;AAAA;AAAA;AAAA;AAAA;AAAA;AAQhD,IAAM,4CACX;AAGK,IAAM,mDACX;AAiCF,IAAM,oBAAoB;AAE1B,SAAS,WAAW,QAA2B,GAA0B;AACvE,MAAI,CAAC,OAAO,OAAQ,QAAO;AAC3B,SAAO,OAAO,KAAK,IAAI,OAAO,SAAS,GAAG,KAAK,KAAM,IAAI,MAAO,OAAO,MAAM,IAAI,CAAC,CAAC;AACrF;AAGO,SAAS,aAAa,MAAqG;AAChI,QAAM,eAAe,KAAK,QAAQ,SAAO,IAAI,kBAAkB,OAAO,CAAC,IAAI,CAAC,IAAI,cAAc,CAAC,EAAE,KAAK,CAAC,GAAG,MAAM,IAAI,CA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