GeezerVison is showing github.com — fix(stats): prevent full retention sync timeouts · jtrag/opencode@43e89ea
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: packages/stats/core/src/domain/inference.test.ts +30-4Lines changed: 30 additions & 4 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -205,8 +205,8 @@ describe("inference stat normalization", () => { | 205 | 205 | dataset: "zen", | 206 | 206 | }) | 207 | 207 |
| 208 | | - expect(queries).toHaveLength(1) | 209 | | - expect(queries[0]?.cohortDates).toEqual(["2026-08-10", "2026-08-17"]) | | 208 | + expect(queries).toHaveLength(2) | | 209 | + expect(queries.map((query) => query.cohortDates)).toEqual([["2026-08-10"], ["2026-08-17"]]) | 210 | 210 | expect(queries[0]?.query).toContain("AND product = 'go'") | 211 | 211 | expect(queries[0]?.query).toContain("AND lower(model) NOT IN ('alpha-gpt-next')") | 212 | 212 | expect(queries[0]?.query).toContain("CASE\n WHEN lower(model) IN ('omen-alpha') THEN 'unknown'\n") | @@ -222,16 +222,42 @@ describe("inference stat normalization", () => { | 222 | 222 | ) | 223 | 223 | expect(queries[0]?.query).not.toContain(" OVER (") | 224 | 224 | expect(queries[0]?.query).toContain("WHEN '2026-08-17' THEN '2026-08-10'") | 225 | | - expect(queries[0]?.query).toContain("WHEN '2026-08-24' THEN '2026-08-17'") | | 225 | + expect(queries[0]?.query).not.toContain("WHEN '2026-08-24' THEN '2026-08-17'") | | 226 | + expect(queries[1]?.query).toContain("WHEN '2026-08-24' THEN '2026-08-17'") | 226 | 227 | expect(queries[0]?.query).toContain("started_at >= '2026-08-10T00:00:00.000Z'") | 227 | | - expect(queries[0]?.query).toContain("started_at < '2026-08-31T00:00:00.000Z'") | | 228 | + expect(queries[0]?.query).toContain("started_at < '2026-08-24T00:00:00.000Z'") | | 229 | + expect(queries[1]?.query).toContain("started_at >= '2026-08-17T00:00:00.000Z'") | | 230 | + expect(queries[1]?.query).toContain("started_at < '2026-08-31T00:00:00.000Z'") | 228 | 231 | expect(queries[0]?.query).toContain("LEFT JOIN returned ON primary_models.user_key = returned.user_key") | 229 | 232 | expect(queries[0]?.query).toContain("primary_models.cohort_date = returned.cohort_date") | 230 | 233 | expect(queries[0]?.query).toContain("'Go' AS tier") | 231 | 234 | expect(queries[0]?.query).toContain("COUNT(*) AS eligible_users") | 232 | 235 | expect(queries[0]?.query).toContain("LIMIT 10000") | 233 | 236 | }) | 234 | 237 |
| | 238 | + test("splits a full retention window without dropping or duplicating cohorts", () => { | | 239 | + const source = { namespace: "inference", table: "generation", dataset: "zen" } | | 240 | + const queries = buildRetentionQueries(new Date("2026-07-16T19:00:00Z"), new Date("2026-09-10T00:00:00Z"), source) | | 241 | + | | 242 | + expect(queries.flatMap((query) => query.cohortDates)).toEqual([ | | 243 | + "2026-07-13", | | 244 | + "2026-07-20", | | 245 | + "2026-07-27", | | 246 | + "2026-08-03", | | 247 | + "2026-08-10", | | 248 | + "2026-08-17", | | 249 | + "2026-08-24", | | 250 | + ]) | | 251 | + queries.forEach((query) => { | | 252 | + const start = new Date(`${query.cohortDates[0]}T00:00:00Z`) | | 253 | + const end = new Date(start.getTime() + 14 * 86_400_000) | | 254 | + expect(query).toEqual(buildRetentionQueries(start, end, source)[0]) | | 255 | + }) | | 256 | + expect(buildRetentionQueries(new Date("2026-08-31T00:00:00Z"), new Date("2026-09-10T00:00:00Z"), source)).toEqual( | | 257 | + [], | | 258 | + ) | | 259 | + }) | | 260 | + | 235 | 261 | test("maps retention query results", () => { | 236 | 262 | expect( | 237 | 263 | toRetentionAggregate({ | |
Collapse file Copy file name to clipboardExpand all lines: packages/stats/core/src/domain/inference.ts +6-7Lines changed: 6 additions & 7 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -56,13 +56,12 @@ export function buildRetentionQueries(periodStart: Date, periodEnd: Date, input? | 56 | 56 | dataset: Resource.StatsSyncConfig.dataset, | 57 | 57 | } | 58 | 58 | const periods = retentionPeriods(periodStart, periodEnd) | 59 | | - if (periods.length === 0) return [] | 60 | | - return [ | 61 | | - { | 62 | | - cohortDates: periods.map((period) => period.start.toISOString().slice(0, 10)), | 63 | | - query: buildRetentionQuery(periods, source), | 64 | | - }, | 65 | | - ] | | 59 | + // Bound the user-level joins to one activity week and its return week. | | 60 | + // Combining the entire display window makes full syncs much more expensive. | | 61 | + return periods.map((period) => ({ | | 62 | + cohortDates: [period.start.toISOString().slice(0, 10)], | | 63 | + query: buildRetentionQuery([period], source), | | 64 | + })) | 66 | 65 | } | 67 | 66 |
| 68 | 67 | function buildRetentionQuery( | |
Collapse file Copy file name to clipboard +18Lines changed: 18 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +import { expect, test } from "bun:test" | | 2 | +import { R2SqlQueryError } from "./r2-sql" | | 3 | + | | 4 | +test("includes the transport failure in the message used by sync logging", () => { | | 5 | + const cause = new DOMException("The operation timed out.", "TimeoutError") | | 6 | + const error = new R2SqlQueryError({ message: "Failed to run R2 SQL stats query", cause }) | | 7 | + | | 8 | + expect(error.message).toBe("Failed to run R2 SQL stats query: TimeoutError: The operation timed out.") | | 9 | + expect(error.cause).toBe(cause) | | 10 | +}) | | 11 | + | | 12 | +test("preserves an R2 response error and request details", () => { | | 13 | + const error = new R2SqlQueryError({ message: "R2 SQL stats query failed", status: 400, requestId: "test-request" }) | | 14 | + | | 15 | + expect(error.message).toBe("R2 SQL stats query failed") | | 16 | + expect(error.status).toBe(400) | | 17 | + expect(error.requestId).toBe("test-request") | | 18 | +}) |
Collapse file Copy file name to clipboardExpand all lines: packages/stats/core/src/r2-sql.ts +27-13Lines changed: 27 additions & 13 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -2,6 +2,7 @@ import { Context, Effect, Layer, Schema } from "effect" | 2 | 2 | import { Resource } from "sst/resource" | 3 | 3 |
| 4 | 4 | const R2_SQL_MAX_ROWS = 10_000 | | 5 | +const R2_SQL_TIMEOUT_MS = 15 * 60_000 | 5 | 6 | const R2SqlValue = Schema.Union([Schema.String, Schema.Number, Schema.Boolean, Schema.Null]) | 6 | 7 | const R2SqlResponse = Schema.Struct({ | 7 | 8 | success: Schema.Boolean, | @@ -25,7 +26,9 @@ export class R2SqlQueryError extends Error { | 25 | 26 | readonly status?: number | 26 | 27 |
| 27 | 28 | constructor(input: { message: string; requestId?: string; status?: number; cause?: unknown }) { | 28 | | - super(input.message, { cause: input.cause }) | | 29 | + super(input.cause instanceof Error ? `${input.message}: ${input.cause.toString()}` : input.message, { | | 30 | + cause: input.cause, | | 31 | + }) | 29 | 32 | this.name = "R2SqlQueryError" | 30 | 33 | this.requestId = input.requestId | 31 | 34 | this.status = input.status | @@ -43,20 +46,31 @@ export class R2Sql extends Context.Service<R2Sql, R2Sql.Service>()("@opencode/st | 43 | 46 | R2Sql, | 44 | 47 | R2Sql.of({ | 45 | 48 | query: Effect.fn("R2Sql.query")(function* (query: string) { | | 49 | + const startedAt = Date.now() | 46 | 50 | const response = yield* Effect.tryPromise({ | 47 | | - try: () => | 48 | | - Bun.fetch( | 49 | | - `https://api.sql.cloudflarestorage.com/api/v1/accounts/${Resource.R2Sql.accountId}/r2-sql/query/${Resource.R2Sql.bucket}`, | 50 | | - { | 51 | | - method: "POST", | 52 | | - headers: { | 53 | | - Authorization: `Bearer ${Resource.R2SqlAuthToken.value}`, | 54 | | - "Content-Type": "application/json", | 55 | | - }, | 56 | | - body: JSON.stringify({ query }), | | 51 | + try: (signal) => { | | 52 | + const options = { | | 53 | + method: "POST", | | 54 | + // Analytical queries can exceed Bun's default five-minute idle timer. | | 55 | + // Bound the whole request and cancel it when the sync is interrupted. | | 56 | + timeout: false, | | 57 | + signal: AbortSignal.any([signal, AbortSignal.timeout(R2_SQL_TIMEOUT_MS)]), | | 58 | + headers: { | | 59 | + Authorization: `Bearer ${Resource.R2SqlAuthToken.value}`, | | 60 | + "Content-Type": "application/json", | 57 | 61 | }, | 58 | | - ), | 59 | | - catch: (cause) => new R2SqlQueryError({ message: "Failed to run R2 SQL stats query", cause }), | | 62 | + body: JSON.stringify({ query }), | | 63 | + } | | 64 | + return Bun.fetch( | | 65 | + `https://api.sql.cloudflarestorage.com/api/v1/accounts/${Resource.R2Sql.accountId}/r2-sql/query/${Resource.R2Sql.bucket}`, | | 66 | + options, | | 67 | + ) | | 68 | + }, | | 69 | + catch: (cause) => | | 70 | + new R2SqlQueryError({ | | 71 | + message: `Failed to run R2 SQL stats query after ${Date.now() - startedAt}ms`, | | 72 | + cause, | | 73 | + }), | 60 | 74 | }) | 61 | 75 | const body = yield* Effect.tryPromise({ | 62 | 76 | try: () => response.text(), | |
Collapse file Copy file name to clipboardExpand all lines: packages/stats/core/src/stat-sync.ts +44-6Lines changed: 44 additions & 6 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -47,9 +47,29 @@ export const syncStats: (options?: { | 47 | 47 |
| 48 | 48 | yield* logRuntimeCheck() | 49 | 49 |
| 50 | | - const rows = yield* Effect.forEach(buildStatsQueries(periodStart, periodEnd), r2Sql.query, { | 51 | | - concurrency: 4, | 52 | | - }).pipe(Effect.map((batches) => batches.flat())) | | 50 | + const queries = buildStatsQueries(periodStart, periodEnd) | | 51 | + yield* Effect.logInfo( | | 52 | + `stats sync started ${JSON.stringify({ full: options?.full ?? false, periodStart, periodEnd, queries: queries.length })}`, | | 53 | + ) | | 54 | + const rows = yield* Effect.forEach( | | 55 | + queries, | | 56 | + (query, index) => | | 57 | + r2Sql.query(query).pipe( | | 58 | + Effect.tap((rows) => | | 59 | + Effect.logInfo( | | 60 | + `stats query complete ${JSON.stringify({ index, total: queries.length, rows: rows.length })}`, | | 61 | + ), | | 62 | + ), | | 63 | + Effect.tapError((error) => | | 64 | + Effect.logError( | | 65 | + `stats query failed ${JSON.stringify({ index, total: queries.length, error: error.message })}`, | | 66 | + ), | | 67 | + ), | | 68 | + ), | | 69 | + { | | 70 | + concurrency: 4, | | 71 | + }, | | 72 | + ).pipe(Effect.map((batches) => batches.flat())) | 53 | 73 | const modelRows = modelRowsFromAggregates(rows.filter((row) => row.dimension === "model").flatMap(toModelAggregate)) | 54 | 74 | const providerRows = providerRowsFromAggregates( | 55 | 75 | rows.filter((row) => row.dimension === "provider").flatMap(toProviderAggregate), | @@ -68,12 +88,30 @@ export const syncStats: (options?: { | 68 | 88 | startOfUtcDay(periodEnd), | 69 | 89 | ) | 70 | 90 | : [] | | 91 | + yield* Effect.logInfo(`stats sync querying retention ${JSON.stringify({ queries: retentionQueries.length })}`) | 71 | 92 | const retentionRows = retentionRowsFromAggregates( | 72 | | - yield* Effect.forEach(retentionQueries, (item) => r2Sql.query(item.query), { concurrency: 4 }).pipe( | 73 | | - Effect.map((batches) => batches.flatMap((batch) => batch.flatMap(toRetentionAggregate))), | 74 | | - ), | | 93 | + yield* Effect.forEach( | | 94 | + retentionQueries, | | 95 | + (item) => | | 96 | + r2Sql.query(item.query).pipe( | | 97 | + Effect.tap((rows) => | | 98 | + Effect.logInfo( | | 99 | + `retention query complete ${JSON.stringify({ cohortDates: item.cohortDates, rows: rows.length })}`, | | 100 | + ), | | 101 | + ), | | 102 | + Effect.tapError((error) => | | 103 | + Effect.logError( | | 104 | + `retention query failed ${JSON.stringify({ cohortDates: item.cohortDates, error: error.message })}`, | | 105 | + ), | | 106 | + ), | | 107 | + ), | | 108 | + { concurrency: 4 }, | | 109 | + ).pipe(Effect.map((batches) => batches.flatMap((batch) => batch.flatMap(toRetentionAggregate)))), | 75 | 110 | ) | 76 | 111 |
| | 112 | + yield* Effect.logInfo( | | 113 | + `stats sync writing aggregates ${JSON.stringify({ modelRows: modelRows.length, providerRows: providerRows.length, geoRows: geoRows.length, retentionRows: retentionRows.length })}`, | | 114 | + ) | 77 | 115 | yield* Effect.all( | 78 | 116 | [ | 79 | 117 | modelStats.upsert(modelRows), | |
|