GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(stats): prevent full retention sync timeouts · jtrag/opencode@43e89ea

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages/stats/core/src
    • domain
      • inference.test.ts
      • inference.ts
    • r2-sql.test.ts
    • r2-sql.ts
    • stat-sync.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎packages/stats/core/src/domain/inference.test.ts‎

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 numberDiff line numberDiff line change
@@ -205,8 +205,8 @@ describe("inference stat normalization", () => {
205205
dataset: "zen",
206206
})
207207

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"]])
210210
expect(queries[0]?.query).toContain("AND product = 'go'")
211211
expect(queries[0]?.query).toContain("AND lower(model) NOT IN ('alpha-gpt-next')")
212212
expect(queries[0]?.query).toContain("CASE\n WHEN lower(model) IN ('omen-alpha') THEN 'unknown'\n")
@@ -222,16 +222,42 @@ describe("inference stat normalization", () => {
222222
)
223223
expect(queries[0]?.query).not.toContain(" OVER (")
224224
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'")
226227
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'")
228231
expect(queries[0]?.query).toContain("LEFT JOIN returned ON primary_models.user_key = returned.user_key")
229232
expect(queries[0]?.query).toContain("primary_models.cohort_date = returned.cohort_date")
230233
expect(queries[0]?.query).toContain("'Go' AS tier")
231234
expect(queries[0]?.query).toContain("COUNT(*) AS eligible_users")
232235
expect(queries[0]?.query).toContain("LIMIT 10000")
233236
})
234237

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+
235261
test("maps retention query results", () => {
236262
expect(
237263
toRetentionAggregate({
Collapse file

‎packages/stats/core/src/domain/inference.ts‎

Copy file name to clipboardExpand all lines: packages/stats/core/src/domain/inference.ts
+6-7Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -56,13 +56,12 @@ export function buildRetentionQueries(periodStart: Date, periodEnd: Date, input?
5656
dataset: Resource.StatsSyncConfig.dataset,
5757
}
5858
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+
}))
6665
}
6766

6867
function buildRetentionQuery(
Collapse file

‎packages/stats/core/src/r2-sql.test.ts‎

Copy file name to clipboard
+18Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
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

‎packages/stats/core/src/r2-sql.ts‎

Copy file name to clipboardExpand all lines: packages/stats/core/src/r2-sql.ts
+27-13Lines changed: 27 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { Context, Effect, Layer, Schema } from "effect"
22
import { Resource } from "sst/resource"
33

44
const R2_SQL_MAX_ROWS = 10_000
5+
const R2_SQL_TIMEOUT_MS = 15 * 60_000
56
const R2SqlValue = Schema.Union([Schema.String, Schema.Number, Schema.Boolean, Schema.Null])
67
const R2SqlResponse = Schema.Struct({
78
success: Schema.Boolean,
@@ -25,7 +26,9 @@ export class R2SqlQueryError extends Error {
2526
readonly status?: number
2627

2728
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+
})
2932
this.name = "R2SqlQueryError"
3033
this.requestId = input.requestId
3134
this.status = input.status
@@ -43,20 +46,31 @@ export class R2Sql extends Context.Service<R2Sql, R2Sql.Service>()("@opencode/st
4346
R2Sql,
4447
R2Sql.of({
4548
query: Effect.fn("R2Sql.query")(function* (query: string) {
49+
const startedAt = Date.now()
4650
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",
5761
},
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+
}),
6074
})
6175
const body = yield* Effect.tryPromise({
6276
try: () => response.text(),
Collapse file

‎packages/stats/core/src/stat-sync.ts‎

Copy file name to clipboardExpand all lines: packages/stats/core/src/stat-sync.ts
+44-6Lines changed: 44 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -47,9 +47,29 @@ export const syncStats: (options?: {
4747

4848
yield* logRuntimeCheck()
4949

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()))
5373
const modelRows = modelRowsFromAggregates(rows.filter((row) => row.dimension === "model").flatMap(toModelAggregate))
5474
const providerRows = providerRowsFromAggregates(
5575
rows.filter((row) => row.dimension === "provider").flatMap(toProviderAggregate),
@@ -68,12 +88,30 @@ export const syncStats: (options?: {
6888
startOfUtcDay(periodEnd),
6989
)
7090
: []
91+
yield* Effect.logInfo(`stats sync querying retention ${JSON.stringify({ queries: retentionQueries.length })}`)
7192
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)))),
75110
)
76111

112+
yield* Effect.logInfo(
113+
`stats sync writing aggregates ${JSON.stringify({ modelRows: modelRows.length, providerRows: providerRows.length, geoRows: geoRows.length, retentionRows: retentionRows.length })}`,
114+
)
77115
yield* Effect.all(
78116
[
79117
modelStats.upsert(modelRows),

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.