Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Repair aggregate duplicates and ensure measurement indexes at startup (#1305)

Dee3b3c552d2ffe
diff --git a/backend/README.md b/backend/README.md
index 9787393b7..7fc69c2ff 100644
--- a/backend/README.md
+++ b/backend/README.md
@@ -222,6 +222,10 @@ legacy account-cohort retention percentage or an industry benchmark.
Ship the backend and its worker together, verify the unique and TTL indexes using synthetic reports,
then ship the CLI and settings surfaces with a visible release note explaining the default and switch.
+The worker installs measurement keys explicitly even when the general Prisma schema push declines
+an unrelated change. It transactionally combines duplicate day/metric totals from a deployment race
+before creating their unique index; this bounded repair touches only aggregate counters and preserves
+their sum. A missing key or failed repair stops worker startup rather than claiming readiness.
The daily decision workflow and release note are in [the measurement guide](../docs/product-measurement.md).
Mixed-version coverage remains explicit until clients update. The existing `usage:report` command
below reads the bounded **historical** tables; its current-day counts cease when new history writes stop.
diff --git a/backend/src/lib/productUsage.test.ts b/backend/src/lib/productUsage.test.ts
index 678ff5ee1..6ab154c46 100644
--- a/backend/src/lib/productUsage.test.ts
+++ b/backend/src/lib/productUsage.test.ts
@@ -5,7 +5,7 @@ const db = vi.hoisted(() => ({
productUsagePreference: { findUnique: vi.fn(), upsert: vi.fn() },
analyticsMachineState: { findFirst: vi.fn() },
productUsageReceipt: { create: vi.fn(), findUnique: vi.fn() },
- productUsageTotal: { upsert: vi.fn(), update: vi.fn() },
+ productUsageTotal: { upsert: vi.fn(), update: vi.fn(), groupBy: vi.fn(), findMany: vi.fn(), deleteMany: vi.fn() },
userDailyPresence: { deleteMany: vi.fn() }, userDailyClientPresence: { deleteMany: vi.fn() },
userDailyRemoteUsage: { deleteMany: vi.fn() }, userDailyDevicePresence: { deleteMany: vi.fn() },
machineDailyPresence: { deleteMany: vi.fn() }, agentDailyPresence: { deleteMany: vi.fn() },
@@ -111,11 +111,39 @@ it('the legacy delete path erases all six linked activity collections', async ()
expect(db[name].deleteMany).toHaveBeenCalledWith({ where: { userId: 'account' } })
})
-it('installs database expiry for receipts, totals and every linked daily history', async () => {
+it('installs required unique keys independently of schema push, then expiry for all histories', async () => {
await ensureProductUsageExpiry()
- expect(db.$runCommandRaw).toHaveBeenCalledTimes(10)
- expect(db.$runCommandRaw.mock.calls[0][0]).toMatchObject({ createIndexes: 'product_usage_receipts', indexes: [{ expireAfterSeconds: 0 }] })
- expect(db.$runCommandRaw.mock.calls[2][0]).toMatchObject({ createIndexes: 'user_daily_presence', indexes: [{ expireAfterSeconds: 35 * 86400 }] })
+ expect(db.$runCommandRaw).toHaveBeenCalledTimes(12)
+ expect(db.$runCommandRaw.mock.calls[0][0]).toMatchObject({ createIndexes: 'product_usage_preferences', indexes: [{ key: { userId: 1 }, unique: true }] })
+ expect(db.$runCommandRaw.mock.calls[1][0]).toMatchObject({ createIndexes: 'product_usage_totals', indexes: [{ key: { dayUtc: 1, metric: 1 }, unique: true }] })
+ expect(db.$runCommandRaw.mock.calls[2][0]).toMatchObject({ createIndexes: 'product_usage_receipts', indexes: [{ expireAfterSeconds: 0 }] })
+ expect(db.$runCommandRaw.mock.calls[4][0]).toMatchObject({ createIndexes: 'user_daily_presence', indexes: [{ expireAfterSeconds: 35 * 86400 }] })
+ expect(db.productUsageTotal.groupBy).not.toHaveBeenCalled()
+})
+
+it('merges duplicate counters transactionally before installing their unique key', async () => {
+ db.$runCommandRaw.mockResolvedValueOnce({}).mockRejectedValueOnce({ meta: { message: 'E11000 duplicate key' } })
+ db.productUsageTotal.groupBy.mockResolvedValue([{ dayUtc: now, metric: 'relay_turns_started' }])
+ db.productUsageTotal.findMany.mockResolvedValue([{ id: 'keep', value: 2 }, { id: 'duplicate', value: 5 }])
+ await ensureProductUsageExpiry()
+ expect(db.$transaction).toHaveBeenCalledOnce()
+ expect(db.productUsageTotal.update).toHaveBeenCalledWith({ where: { id: 'keep' }, data: { value: { increment: 5 } } })
+ expect(db.productUsageTotal.deleteMany).toHaveBeenCalledWith({ where: { id: { in: ['duplicate'] } } })
+})
+
+it('retries a conflicting repair but fails startup for unrelated database failures', async () => {
+ db.$runCommandRaw.mockResolvedValueOnce({}).mockRejectedValueOnce({ meta: { code: 11000 } })
+ db.$transaction.mockRejectedValueOnce({ code: 'P2034' })
+ await expect(ensureProductUsageExpiry()).resolves.toBeUndefined()
+ db.$runCommandRaw.mockRejectedValueOnce(new Error('permission denied'))
+ await expect(ensureProductUsageExpiry()).rejects.toThrow('permission denied')
+})
+
+it('bounds duplicate repair work and refuses to claim readiness without a unique key', async () => {
+ db.$runCommandRaw.mockResolvedValueOnce({}).mockRejectedValue({ meta: { code: 11000 } })
+ db.productUsageTotal.groupBy.mockResolvedValue([])
+ await expect(ensureProductUsageExpiry()).rejects.toThrow('aggregate key is not ready')
+ expect(db.$transaction).toHaveBeenCalledTimes(10)
})
it('setup ingestion never reads an account and expires after yesterday', async () => {
diff --git a/backend/src/lib/productUsage.ts b/backend/src/lib/productUsage.ts
index d0b67828c..e1cdda8f5 100644
--- a/backend/src/lib/productUsage.ts
+++ b/backend/src/lib/productUsage.ts
@@ -108,8 +108,52 @@ export async function deleteLegacyProductUsage(userId: string): Promise<void> {
])
}
-/** Run only in the singleton worker. Expiry is enforced by Mongo, including during application downtime. */
+async function ensureProductUsageTotalKey(): Promise<void> {
+ // The API can receive relay counts before the singleton's general schema push. That push may
+ // also decline unrelated changes. Install this correctness boundary explicitly; do not rely on it.
+ for (let attempt = 0; attempt < 10; attempt++) {
+ try {
+ await prisma.$runCommandRaw({ createIndexes: 'product_usage_totals', indexes: [{
+ key: { dayUtc: 1, metric: 1 }, name: 'product_usage_totals_dayUtc_metric_key', unique: true,
+ }] })
+ return
+ } catch (error) {
+ const failure = error as { meta?: { code?: string | number; message?: string } }
+ if (String(failure.meta?.code) !== '11000' && !failure.meta?.message?.includes('E11000')) throw error
+ }
+ // Repair only duplicate aggregate keys, never account data. A transaction preserves increments
+ // from concurrent writers: a changed/deleted row conflicts and retries instead of losing counts.
+ // Bound each pass; a large backlog fails worker startup and resumes safely on its next start.
+ try {
+ await prisma.$transaction(async tx => {
+ const [group] = await tx.productUsageTotal.groupBy({
+ by: ['dayUtc', 'metric'], having: { id: { _count: { gt: 1 } } },
+ orderBy: [{ dayUtc: 'asc' }, { metric: 'asc' }], take: 1,
+ })
+ if (!group) return
+ const rows = await tx.productUsageTotal.findMany({
+ where: { dayUtc: group.dayUtc, metric: group.metric },
+ select: { id: true, value: true }, orderBy: { id: 'asc' }, take: 128,
+ })
+ if (rows.length < 2) return
+ const [keeper, ...duplicates] = rows
+ await tx.productUsageTotal.update({ where: { id: keeper.id },
+ data: { value: { increment: duplicates.reduce((sum, row) => sum + row.value, 0) } } })
+ await tx.productUsageTotal.deleteMany({ where: { id: { in: duplicates.map(row => row.id) } } })
+ })
+ } catch (error) {
+ if ((error as { code?: string }).code !== 'P2034') throw error
+ }
+ }
+ throw new Error('Product usage aggregate key is not ready')
+}
+
+/** Run only in the singleton worker. Required keys and expiry must survive a declined schema push. */
export async function ensureProductUsageExpiry(): Promise<void> {
+ await prisma.$runCommandRaw({ createIndexes: 'product_usage_preferences', indexes: [{
+ key: { userId: 1 }, name: 'product_usage_preferences_userId_key', unique: true,
+ }] })
+ await ensureProductUsageTotalKey()
for (const [collection, field, seconds] of [
['product_usage_receipts', 'expiresAt', 0],
['product_usage_totals', 'dayUtc', 396 * DAY / 1000],