Skip to content

Commit ab733be

Browse files
perf(automations): Store each run's cost so cost totals read only runs
Each usage write of a Conversation copies its cost to its run, and each run write copies it when it links the Conversation. The summary windows and the 90-day and hourly charts sum the stored column instead of joining every run to its Conversation. Co-Authored-By: BYK <[email protected]>
1 parent 274effd commit ab733be

10 files changed

Lines changed: 254 additions & 11 deletions

File tree

‎packages/junior/migrations/0116_automation_last_run.sql‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
ALTER TABLE "junior_automation_runs" ADD COLUMN "cost_usd" double precision;--> statement-breakpoint
12
ALTER TABLE "junior_automations" ADD COLUMN "last_run_at_ms" bigint;--> statement-breakpoint
23
ALTER TABLE "junior_automations" ADD COLUMN "last_run_status" text;--> statement-breakpoint
34
-- The list orders and filters by these columns, and each new run write
@@ -14,4 +15,30 @@ SET ("last_run_at_ms", "last_run_status") = (
1415
ORDER BY "completed_at_ms" DESC, "id" DESC
1516
LIMIT 1
1617
)
17-
WHERE "status" <> 'deleted';
18+
WHERE "status" <> 'deleted';--> statement-breakpoint
19+
-- Automation cost totals sum this column. Each usage write of a Conversation
20+
-- copies its cost to its run, and each run write copies it when it links the
21+
-- Conversation. This matches conversationUsageCostExpr.
22+
-- junior:bounded-backfill: settled runs only, which no app write changes; each row reads its own Conversation by primary key.
23+
UPDATE "junior_automation_runs"
24+
SET "cost_usd" = (
25+
SELECT CASE
26+
WHEN "usage_json"->'cost'->>'total' IS NOT NULL
27+
THEN ("usage_json"->'cost'->>'total')::double precision
28+
WHEN COALESCE(
29+
"usage_json"->'cost'->>'input',
30+
"usage_json"->'cost'->>'output',
31+
"usage_json"->'cost'->>'cacheRead',
32+
"usage_json"->'cost'->>'cacheWrite'
33+
) IS NOT NULL
34+
THEN COALESCE(("usage_json"->'cost'->>'input')::double precision, 0)
35+
+ COALESCE(("usage_json"->'cost'->>'output')::double precision, 0)
36+
+ COALESCE(("usage_json"->'cost'->>'cacheRead')::double precision, 0)
37+
+ COALESCE(("usage_json"->'cost'->>'cacheWrite')::double precision, 0)
38+
ELSE NULL
39+
END
40+
FROM "junior_conversations"
41+
WHERE "junior_conversations"."conversation_id" = "junior_automation_runs"."conversation_id"
42+
)
43+
WHERE "conversation_id" IS NOT NULL
44+
AND "status" IN ('blocked', 'completed', 'failed', 'skipped');

‎packages/junior/migrations/meta/0116_snapshot.json‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
2-
"id": "2eb10129-a170-426e-95c3-fb59c3d8911e",
2+
"id": "261e19e5-0c1a-4fe8-a617-41a8befec11c",
33
"prevId": "2975fcbf-7615-4d37-b9ee-aa182fc7fbb4",
44
"version": "7",
55
"dialect": "postgresql",
@@ -938,6 +938,12 @@
938938
"type": "text",
939939
"primaryKey": false,
940940
"notNull": false
941+
},
942+
"cost_usd": {
943+
"name": "cost_usd",
944+
"type": "double precision",
945+
"primaryKey": false,
946+
"notNull": false
941947
}
942948
},
943949
"indexes": {

‎packages/junior/migrations/meta/_journal.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -817,7 +817,7 @@
817817
{
818818
"idx": 116,
819819
"version": "7",
820-
"when": 1794919217164,
820+
"when": 1794924488990,
821821
"tag": "0116_automation_last_run",
822822
"breakpoints": true
823823
}

‎packages/junior/src/chat/automations/execution-stats.ts‎

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,10 @@ import {
1111
sql,
1212
type SQL,
1313
} from "drizzle-orm";
14-
import { conversationUsageCostExpr } from "@/api/conversations/aggregate";
1514
import { getDb } from "@/chat/db";
1615
import type { JuniorDatabase } from "@/db/db";
1716
import { logWarn } from "@/chat/logging";
17+
import { refreshAutomationRunCost } from "./run-cost";
1818
import { fallbackShortTitle } from "@/chat/services/short-title";
1919
import {
2020
automationTaskDescription,
@@ -204,6 +204,12 @@ export async function recordAutomationExecution(
204204
},
205205
setWhere: inArray(juniorAutomationRuns.status, ["pending", "running"]),
206206
});
207+
if (options.conversationId) {
208+
await refreshAutomationRunCost(
209+
getDb(),
210+
eq(juniorAutomationRuns.id, options.executionId),
211+
);
212+
}
207213
await refreshAutomationLastRun(getDb(), automationId);
208214
} catch (error) {
209215
logWarn("task.execution.stat_failed", {
@@ -227,9 +233,8 @@ export async function readAutomationExecutionSummaries(
227233
const thirtyDaysAgoMs = nowMs - 30 * 24 * 60 * 60 * 1000;
228234
const ninetyDaysAgoMs = nowMs - 90 * 24 * 60 * 60 * 1000;
229235
const db = getDb();
230-
const conversationCost = conversationUsageCostExpr(juniorConversations.usage);
231236
const costSince = (sinceMs: number) =>
232-
sql<number>`coalesce(sum(${conversationCost}) filter (where ${juniorAutomationRuns.completedAtMs} >= ${sinceMs}), 0)::double precision`;
237+
sql<number>`coalesce(sum(${juniorAutomationRuns.costUsd}) filter (where ${juniorAutomationRuns.completedAtMs} >= ${sinceMs}), 0)::double precision`;
233238
const summaryRows = db
234239
.select({
235240
costLast1Day: costSince(oneDayAgoMs),
@@ -241,11 +246,10 @@ export async function readAutomationExecutionSummaries(
241246
runsLast30Days: sql<number>`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${thirtyDaysAgoMs})::int`,
242247
runsLast90Days: sql<number>`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${ninetyDaysAgoMs})::int`,
243248
automationId: juniorAutomationRuns.automationId,
244-
totalCostUsd: sql<number>`coalesce(sum(${conversationCost}), 0)::double precision`,
249+
totalCostUsd: sql<number>`coalesce(sum(${juniorAutomationRuns.costUsd}), 0)::double precision`,
245250
totalRuns: sql<number>`count(*)::int`,
246251
})
247252
.from(juniorAutomationRuns)
248-
.leftJoin(juniorConversations, executionConversation())
249253
.where(
250254
and(
251255
isExecution(),
@@ -659,16 +663,16 @@ async function readExecutionStatusBuckets(args: {
659663
endMs: number;
660664
startMs: number;
661665
}) {
662-
const conversationCost = conversationUsageCostExpr(juniorConversations.usage);
663666
return await getDb()
664667
.select({
665668
count: count(),
666-
costUsd: sql<number | null>`SUM(${conversationCost})::double precision`,
669+
costUsd: sql<
670+
number | null
671+
>`SUM(${juniorAutomationRuns.costUsd})::double precision`,
667672
date: args.bucket,
668673
status: juniorAutomationRuns.status,
669674
})
670675
.from(juniorAutomationRuns)
671-
.leftJoin(juniorConversations, executionConversation())
672676
.where(
673677
and(
674678
isExecution(),
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { sql, type SQL } from "drizzle-orm";
2+
import { conversationUsageCostExpr } from "@/api/conversations/aggregate";
3+
import type { JuniorDatabase } from "@/db/db";
4+
import { juniorAutomationRuns } from "@/db/schema/automation-runs";
5+
import { juniorConversations } from "@/db/schema";
6+
7+
/**
8+
* Copy the cost of each matched run's Conversation to the run, so Automation
9+
* cost totals read only runs. Call it after each write that changes a
10+
* Conversation's usage or links a run to its Conversation.
11+
*/
12+
export async function refreshAutomationRunCost(
13+
db: JuniorDatabase,
14+
where: SQL,
15+
): Promise<void> {
16+
await db
17+
.update(juniorAutomationRuns)
18+
.set({
19+
costUsd: sql`(select ${conversationUsageCostExpr(juniorConversations.usage)} from ${juniorConversations} where ${juniorConversations.conversationId} = ${juniorAutomationRuns.conversationId})`,
20+
})
21+
.where(where);
22+
}

‎packages/junior/src/chat/conversations/metrics.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ import {
1212
} from "@/chat/usage";
1313
import type { ConversationRunMetrics } from "./store";
1414
import { nextDetailVersion } from "./sql/detail-version";
15+
import { refreshAutomationRunCost } from "@/chat/automations/run-cost";
16+
import { juniorAutomationRuns } from "@/db/schema/automation-runs";
1517

1618
function finite(value: number | undefined): number | undefined {
1719
return value !== undefined && Number.isFinite(value) && value >= 0
@@ -194,4 +196,8 @@ export async function replaceConversationMetrics(
194196
detailVersion: nextDetailVersion,
195197
})
196198
.where(eq(juniorConversations.conversationId, args.conversationId));
199+
await refreshAutomationRunCost(
200+
executor.db(),
201+
eq(juniorAutomationRuns.conversationId, args.conversationId),
202+
);
197203
}

‎packages/junior/src/chat/event-automations/runs.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
existingConversationId,
88
recordAutomationExecution,
99
} from "@/chat/automations/execution-stats";
10+
import { refreshAutomationRunCost } from "@/chat/automations/run-cost";
1011
import { automationVersionOf } from "@/chat/automations/versions";
1112
import type { EventAutomation } from "@/chat/event-automations/types";
1213
import type { JuniorDatabase } from "@/db/db";
@@ -36,6 +37,11 @@ export async function recordEventAutomationRunStarted(
3637
status: "running",
3738
})
3839
.onConflictDoNothing({ target: juniorAutomationRuns.id });
40+
// The dispatch can write usage before this row exists.
41+
await refreshAutomationRunCost(
42+
db,
43+
eq(juniorAutomationRuns.id, args.dispatchId),
44+
);
3945
}
4046

4147
/**

‎packages/junior/src/chat/scheduled-automations/runs.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import {
1616
existingConversationId,
1717
refreshAutomationLastRun,
1818
} from "@/chat/automations/execution-stats";
19+
import { refreshAutomationRunCost } from "@/chat/automations/run-cost";
1920
import { automationVersionOf } from "@/chat/automations/versions";
2021
import type { JuniorDatabase } from "@/db/db";
2122
import { juniorAutomationRuns } from "@/db/schema/automation-runs";
@@ -113,6 +114,9 @@ async function writeRun(
113114
.insert(juniorAutomationRuns)
114115
.values({ id: stored.id, ...columns })
115116
.onConflictDoUpdate({ target: juniorAutomationRuns.id, set: columns });
117+
if (stored.dispatchId) {
118+
await refreshAutomationRunCost(db, eq(juniorAutomationRuns.id, stored.id));
119+
}
116120
if (stored.completedAtMs !== undefined) {
117121
await refreshAutomationLastRun(db, stored.taskId);
118122
}

‎packages/junior/src/db/schema/automation-runs.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { sql } from "drizzle-orm";
22
import {
33
bigint,
44
check,
5+
doublePrecision,
56
foreignKey,
67
index,
78
integer,
@@ -53,6 +54,9 @@ export const juniorAutomationRuns = pgTable(
5354
completedAtMs: bigint("completed_at_ms", { mode: "number" }),
5455
errorMessage: text("error_message"),
5556
resultMessageTs: text("result_message_ts"),
57+
// Cost of the run's Conversation, copied from its usage on each usage
58+
// write, so Automation cost totals read only runs.
59+
costUsd: doublePrecision("cost_usd"),
5660
},
5761
(table) => [
5862
foreignKey({
Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
import { eq } from "drizzle-orm";
2+
import { Hono } from "hono";
3+
import { describe, expect, test } from "vitest";
4+
import { createJuniorApi } from "@/api";
5+
import { conversationUsageCostExpr } from "@/api/conversations/aggregate";
6+
import type { JuniorApiEnv } from "@/api/route";
7+
import {
8+
automationExecutionListSchema,
9+
automationSummarySchema,
10+
} from "@/api/schema/automation";
11+
import { recordAutomationExecution } from "@/chat/automations/execution-stats";
12+
import { migrateSchema } from "@/chat/conversations/sql/migrations";
13+
import { createSqlStore } from "@/chat/conversations/sql/store";
14+
import {
15+
resolveViewerUser,
16+
resolveViewerUserFromSql,
17+
} from "@/chat/plugins/viewer";
18+
import { saveScheduledAutomation } from "@/chat/scheduled-automations/tasks";
19+
import { juniorAutomationRuns } from "@/db/schema/automation-runs";
20+
import { juniorConversations } from "@/db/schema/conversations";
21+
import { createConfiguredJuniorSqlFixture } from "../../fixtures/sql";
22+
23+
function authenticatedApi(email: string) {
24+
const app = new Hono<JuniorApiEnv>();
25+
app.use("*", async (context, next) => {
26+
const viewer = await resolveViewerUser(email);
27+
if (!viewer) throw new Error(`missing viewer for ${email}`);
28+
context.set("viewer", viewer);
29+
await next();
30+
});
31+
app.route("/", createJuniorApi());
32+
return app;
33+
}
34+
35+
describe("Automation run cost", () => {
36+
test("follows usage that a run's Conversation gains after the run", async () => {
37+
const fixture = createConfiguredJuniorSqlFixture();
38+
const conversationStore = createSqlStore(fixture.sql);
39+
try {
40+
await migrateSchema(fixture.sql);
41+
const actor = {
42+
43+
platform: "slack" as const,
44+
slackUserId: "U123",
45+
teamId: "T123",
46+
};
47+
const destination = {
48+
channelId: "C123",
49+
platform: "slack" as const,
50+
teamId: "T123",
51+
};
52+
const runConversationId = "agent-dispatch:cost-run";
53+
await conversationStore.recordActivity({
54+
actor,
55+
conversationId: runConversationId,
56+
destination,
57+
title: "Automation run",
58+
visibility: "public",
59+
});
60+
const user = await resolveViewerUserFromSql(
61+
fixture.sql.db(),
62+
63+
);
64+
const identity = user!.identities.find(
65+
(candidate) => candidate.provider === "slack",
66+
)!;
67+
const nowMs = Date.now();
68+
const runAtMs = nowMs - 60 * 60 * 1000;
69+
await saveScheduledAutomation(fixture.sql.db(), {
70+
id: "sched_cost",
71+
conversationAccess: { audience: "channel", visibility: "public" },
72+
createdAtMs: nowMs - 2 * 60 * 60 * 1000,
73+
createdBy: { slackUserId: "U123" },
74+
creatorIdentityId: identity.id,
75+
credentialMode: "creator",
76+
destination,
77+
nextRunAtMs: nowMs + 60_000,
78+
outcomes: [],
79+
schedule: {
80+
description: "",
81+
kind: "recurring",
82+
recurrence: {
83+
frequency: "daily",
84+
interval: 1,
85+
startDate: new Date(nowMs).toISOString().slice(0, 10),
86+
time: { hour: 12, minute: 0 },
87+
},
88+
timezone: "UTC",
89+
},
90+
status: "active",
91+
task: { kind: "instruction", instruction: "Post the daily digest." },
92+
updatedAtMs: nowMs,
93+
});
94+
const recordTurn = async (runId: string, costUsd: number) =>
95+
await conversationStore.recordExecution({
96+
conversationId: runConversationId,
97+
createdAtMs: runAtMs,
98+
execution: { runId, status: "idle", updatedAtMs: Date.now() },
99+
lastActivityAtMs: Date.now(),
100+
metrics: {
101+
durationMs: 1_000,
102+
usage: { cost: { total: costUsd }, totalTokens: 100 },
103+
},
104+
updatedAtMs: Date.now(),
105+
});
106+
const api = authenticatedApi("[email protected]");
107+
const readCost = async () => {
108+
const summary = automationSummarySchema.parse(
109+
await (
110+
await api.request("http://localhost/api/automations/sched_cost")
111+
).json(),
112+
);
113+
const executions = automationExecutionListSchema.parse(
114+
await (
115+
await api.request(
116+
"http://localhost/api/automations/sched_cost/executions",
117+
)
118+
).json(),
119+
);
120+
const day = new Date(runAtMs).toISOString().slice(0, 10);
121+
return {
122+
day: executions.executionDays.find((entry) => entry.date === day)
123+
?.costUsd,
124+
total: summary.totalCostUsd,
125+
week: summary.costUsd[7],
126+
};
127+
};
128+
129+
// The run's Turn writes usage before the run records its outcome.
130+
await recordTurn("turn-1", 0.2);
131+
await recordAutomationExecution("sched_cost", {
132+
conversationId: runConversationId,
133+
executionId: "cost-run",
134+
nowMs: runAtMs,
135+
status: "completed",
136+
});
137+
expect(await readCost()).toEqual({ day: 0.2, total: 0.2, week: 0.2 });
138+
139+
// A follow-up Turn in the run's Conversation adds usage later.
140+
await recordTurn("turn-2", 0.05);
141+
expect(await readCost()).toEqual({ day: 0.25, total: 0.25, week: 0.25 });
142+
143+
// Each stored run cost equals the cost of its Conversation.
144+
const [parity] = await fixture.sql
145+
.db()
146+
.select({
147+
conversation: conversationUsageCostExpr(juniorConversations.usage),
148+
run: juniorAutomationRuns.costUsd,
149+
})
150+
.from(juniorAutomationRuns)
151+
.innerJoin(
152+
juniorConversations,
153+
eq(
154+
juniorConversations.conversationId,
155+
juniorAutomationRuns.conversationId,
156+
),
157+
)
158+
.where(eq(juniorAutomationRuns.id, "cost-run"));
159+
expect(parity!.run).toBe(parity!.conversation);
160+
} finally {
161+
await fixture.close();
162+
}
163+
});
164+
});

0 commit comments

Comments
 (0)