Skip to content

Commit 637cdc7

Browse files
Persist session metrics JSON on Postgres and SQLite
1 parent a60f4c2 commit 637cdc7

13 files changed

Lines changed: 173 additions & 5 deletions

File tree

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
'@truefoundry/trueforge-core': patch
3+
'@truefoundry/trueforge': patch
4+
---
5+
6+
Persist zero-initialized metrics on agent sessions.

‎packages/trueforge-core/src/agent-session/index.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@ export {
2121
} from './schemas/turn';
2222
export type { TerminalTurnState, Turn, TurnInputItem, TurnMetrics, TurnState } from './schemas/turn';
2323

24-
export { SessionSchema } from './schemas/session';
25-
export type { Session, SessionAgent } from './schemas/session';
24+
export { SessionMetricsSchema, SessionSchema } from './schemas/session';
25+
export type { Session, SessionAgent, SessionMetrics } from './schemas/session';
2626

2727
export {
2828
EventType,

‎packages/trueforge-core/src/agent-session/models/SessionRecord.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { SessionAgent } from '../schemas/session';
1+
import type { SessionAgent, SessionMetrics } from '../schemas/session';
22

33
/**
44
* Session persistence record. Agent binding is a single discriminated `agent`
@@ -30,5 +30,6 @@ export interface SessionRecord<TCustom extends object = Record<string, never>> {
3030
* updateSession, and createTurn — never on reads.
3131
*/
3232
last_activity_timestamp_ms: number;
33+
metrics: SessionMetrics;
3334
custom: TCustom | null;
3435
}

‎packages/trueforge-core/src/agent-session/schemas/session.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,14 @@
55
import { z } from '@hono/zod-openapi';
66
import { AgentSpecSchema } from './agentSpec';
77

8+
export const SessionMetricsSchema = z
9+
.object({
10+
total_cost_in_usd: z.number().nonnegative(),
11+
total_duration_ms: z.number().int().nonnegative(),
12+
total_turns: z.number().int().nonnegative(),
13+
})
14+
.strict();
15+
816
export const SessionAgentReferenceSchema = z
917
.object({
1018
type: z.literal('reference').describe('Bind the session to a named registry agent.'),
@@ -46,4 +54,5 @@ export const SessionSchema = z
4654
export type SessionAgentReference = z.infer<typeof SessionAgentReferenceSchema>;
4755
export type SessionAgentInline = z.infer<typeof SessionAgentInlineSchema>;
4856
export type SessionAgent = z.infer<typeof SessionAgentSchema>;
57+
export type SessionMetrics = z.infer<typeof SessionMetricsSchema>;
4958
export type Session = z.infer<typeof SessionSchema>;

‎packages/trueforge-core/src/agent-session/store/InMemorySessionStore.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,11 @@ export class InMemorySessionStore<
184184
created_at: now,
185185
updated_at: now,
186186
last_activity_timestamp_ms: Date.now(),
187+
metrics: {
188+
total_cost_in_usd: 0,
189+
total_duration_ms: 0,
190+
total_turns: 0,
191+
},
187192
custom: input.custom !== null ? deepCopy(input.custom) : null,
188193
};
189194
this.sessions.set(key, { record, turnIds: [] });

‎packages/trueforge-core/tests/agent-session/store/storeContractSuite.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,11 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
175175
});
176176
expect(mustGet(session).last_activity_timestamp_ms).toBeGreaterThanOrEqual(before);
177177
expect(mustGet(session).title).toBeNull();
178+
expect(mustGet(session).metrics).toEqual({
179+
total_cost_in_usd: 0,
180+
total_duration_ms: 0,
181+
total_turns: 0,
182+
});
178183
});
179184

180185
it('createSession persists created_by', async () => {
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { sql, type Kysely } from 'kysely';
2+
3+
export async function up(db: Kysely<unknown>): Promise<void> {
4+
await sql`SET LOCAL lock_timeout = '5s'`.execute(db);
5+
await db.schema
6+
.alterTable('session')
7+
.addColumn('metrics', 'jsonb', col =>
8+
col.notNull().defaultTo(sql`'{"total_cost_in_usd":0,"total_duration_ms":0,"total_turns":0}'::jsonb`),
9+
)
10+
.execute();
11+
// Serves GET /sessions/metrics (named agent + created_at window).
12+
// session_agent_id_idx cannot range on created_at; partial skips inline sessions.
13+
await sql`
14+
CREATE INDEX session_agent_created_at_idx
15+
ON session (tenant_id, agent_id, created_at)
16+
WHERE agent_id IS NOT NULL
17+
`.execute(db);
18+
}
19+
20+
export async function down(db: Kysely<unknown>): Promise<void> {
21+
await sql`SET LOCAL lock_timeout = '5s'`.execute(db);
22+
await sql`DROP INDEX IF EXISTS session_agent_created_at_idx`.execute(db);
23+
await db.schema.alterTable('session').dropColumn('metrics').execute();
24+
}

‎packages/trueforge/src/db/postgres/session-store/queries/sessions.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { AgentSpec } from '@truefoundry/trueforge-core/agent-session';
1+
import type { AgentSpec, SessionMetrics } from '@truefoundry/trueforge-core/agent-session';
22
import type { SessionRecord } from '@truefoundry/trueforge-core/agent-session/models/SessionRecord';
33
import type {
44
CreateSessionInput,
@@ -58,6 +58,7 @@ function mapRowToSessionRecord(row: {
5858
title: string | null;
5959
last_turn_id: string | null;
6060
custom: Record<string, unknown> | null;
61+
metrics: SessionMetrics;
6162
created_at: Date;
6263
updated_at: Date;
6364
last_activity_timestamp_ms: number;
@@ -75,6 +76,7 @@ function mapRowToSessionRecord(row: {
7576
title: row.title,
7677
last_turn_id: row.last_turn_id,
7778
custom: parseSessionCustom(row.custom),
79+
metrics: row.metrics,
7880
created_at: row.created_at,
7981
updated_at: row.updated_at,
8082
last_activity_timestamp_ms: row.last_activity_timestamp_ms,
@@ -97,6 +99,11 @@ export async function createSession(db: Kysely<Database>, input: CreateSessionIn
9799
agent_spec: columns.agent_spec !== null ? json(columns.agent_spec) : null,
98100
title: null,
99101
custom: input.custom !== null ? json(input.custom) : null,
102+
metrics: json({
103+
total_cost_in_usd: 0,
104+
total_duration_ms: 0,
105+
total_turns: 0,
106+
}),
100107
created_at: new Date(nowMs),
101108
updated_at: new Date(nowMs),
102109
last_activity_timestamp_ms: nowMs,

‎packages/trueforge/src/db/postgres/types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import type {
66
AgentSpec,
77
PersistedTurnEvent,
8+
SessionMetrics,
89
TurnInputItem,
910
TurnState,
1011
} from '@truefoundry/trueforge-core/agent-session';
@@ -79,6 +80,7 @@ export interface SessionTable {
7980
last_turn_id: string | null;
8081
/** top: caller-owned opaque extension; never mixed with store state */
8182
custom: JSONColumnType<Record<string, unknown>, Record<string, unknown>, Record<string, unknown>> | null;
83+
metrics: JSONColumnType<SessionMetrics, SessionMetrics, SessionMetrics>;
8284
/** top: list ordering (indexed below) */
8385
created_at: Date;
8486
updated_at: Date;

‎packages/trueforge/src/db/sqlite/client.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,7 @@ function applyPragmas(database: Database.Database): void {
124124
const JSON_RESULT_COLUMNS = new Set([
125125
'agent_spec',
126126
'custom',
127+
'metrics',
127128
'ancestor_ids',
128129
'input',
129130
'state',

0 commit comments

Comments
 (0)