diff --git a/apps/api/tests/workers/project-data-message-ingest-metrics.test.ts b/apps/api/tests/workers/project-data-message-ingest-metrics.test.ts new file mode 100644 index 0000000000..17aa9ad57b --- /dev/null +++ b/apps/api/tests/workers/project-data-message-ingest-metrics.test.ts @@ -0,0 +1,321 @@ +import type { ProjectData } from '@simple-agent-manager/project-data/internal/do/index'; +import type { MessageIngestMetrics } from '@simple-agent-manager/project-data/internal/do/message-ingest-metrics'; +import { projectDataPorts } from '@simple-agent-manager/project-data/internal/do/ports'; +import type { RowUsage } from '@simple-agent-manager/project-data/internal/do/row-usage'; +import { env, runInDurableObject } from 'cloudflare:test'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +const source = { + workspaceId: 'metrics-workspace', + callbackGeneration: null, + outboxIncarnation: 'cbce9fe8-c5e5-464c-9900-4bec2bd30cb1', +}; +const config = { enabled: true, maxRowBytes: 65536, recentIds: 200 }; +function chunk(sequence: number, role = 'assistant') { + return { + messageId: `chunk-${sequence}`, + sequence, + role, + toolMetadata: null, + content: `part${sequence} `, + timestamp: new Date(1700000000000 + sequence).toISOString(), + }; +} +function reports(spy: ReturnType): Array<{ messageIngest: MessageIngestMetrics }> { + return spy.mock.calls.flatMap(([line]) => { + try { + const value = JSON.parse(String(line)); + return value.event === 'project_data.row_usage' ? [value] : []; + } catch { + return []; + } + }); +} +async function setup(enabled = true) { + vi.spyOn(projectDataPorts().operations, 'messageMergeConfig').mockResolvedValue({ + ...config, + enabled, + }); + const stub = env.PROJECT_DATA.get( + env.PROJECT_DATA.newUniqueId() + ) as DurableObjectStub; + await stub.ensureProjectId('metrics-project'); + const session = await stub.createSession(source.workspaceId, 'Metrics topic'); + return { stub, session }; +} +async function flush(stub: DurableObjectStub) { + await runInDurableObject(stub, (instance) => { + const usage = (instance as unknown as { rowUsage: RowUsage }).rowUsage; + const start = (usage as unknown as { windowStart: number }).windowStart; + usage.flush(start + usage.intervalMs); + }); +} +async function captureBatchError(stub: DurableObjectStub, session: string) { + const response = await stub.fetch( + new Request('https://test/__capture-expected-error', { + method: 'POST', + body: JSON.stringify({ + operation: 'persistMessageBatch', + args: [session, [chunk(1), chunk(2)], source], + }), + }) + ); + return response.json(); +} +afterEach(() => vi.restoreAllMocks()); + +describe('content-free message ingestion counters through real workerd', () => { + it('counts accepted roles, same-batch coalesces, cross-batch SQL appends and replay separately', async () => { + const { stub, session } = await setup(); + const log = vi.spyOn(console, 'log'); + await stub.persistMessageBatch(session, [chunk(1), chunk(2)], source); + await stub.persistMessageBatch(session, [chunk(3), chunk(4)], source); + await stub.persistMessageBatch(session, [chunk(1), chunk(2), chunk(3)], source); + await stub.persistMessageBatch( + session, + [chunk(5, 'thinking'), chunk(6, 'thinking'), chunk(7, 'tool')], + source + ); + await flush(stub); + const metrics = reports(log).at(-1)!.messageIngest; + expect(metrics).toMatchObject({ + batches: 4, + received: { assistant: 7, thinking: 2, tool: 1 }, + accepted: { assistant: 4, thinking: 2, tool: 1 }, + inserted: { assistant: 1, thinking: 2, tool: 1 }, + eligible: 4, + coalesced: 3, + appendStatements: 1, + duplicates: 3, + mergeReadyBatches: 4, + refused: {}, + breaks: { no_open: 1, role: 1 }, + }); + const rows = (await stub.getMessages(session, 50, null, null, undefined, false, 'asc')) + .messages; + expect(rows.map((row) => row.role)).toEqual(['assistant', 'thinking', 'thinking', 'tool']); + expect(rows[0]!.content).toBe('part1 part2 part3 part4 '); + log.mockClear(); + await stub.persistMessageBatch(session, [chunk(8, 'plan')], source); + await flush(stub); + expect(reports(log).at(-1)!.messageIngest).toMatchObject({ + batches: 1, + received: { assistant: 0, plan: 1 }, + coalesced: 0, + appendStatements: 0, + duplicates: 0, + }); + }); + + it.each([false, true])( + 'observes actual scoped and unscoped legacy socket admission; only scoped refuses (sessionScoped=%s)', + async (sessionScoped) => { + const { stub, session } = await setup(); + const response = await stub.fetch( + new Request(`https://test/ws${sessionScoped ? `?sessionId=${session}` : ''}`, { + headers: { Upgrade: 'websocket' }, + }) + ); + expect(response.status).toBe(101); + response.webSocket!.accept(); + const log = vi.spyOn(console, 'log'); + await stub.persistMessageBatch(session, [chunk(1), chunk(2)], source); + await stub.persistMessageBatch(session, [chunk(3)], source); + await flush(stub); + // A legacy session socket refuses merging for its session. A legacy project socket gets no + // transcript frames, so it is counted for diagnostics but never refuses. + expect(reports(log).at(-1)!.messageIngest).toMatchObject( + sessionScoped + ? { + batches: 2, + eligible: 3, + coalesced: 0, + inserted: { assistant: 3 }, + refused: { legacy_client: 2 }, + legacySessionSocketsMax: 1, + legacyProjectSocketsMax: 0, + } + : { + batches: 2, + eligible: 3, + coalesced: 2, + appendStatements: 1, + inserted: { assistant: 1 }, + refused: {}, + legacySessionSocketsMax: 0, + legacyProjectSocketsMax: 1, + } + ); + if (!sessionScoped) + expect(reports(log).at(-1)!.messageIngest.refused.legacy_client).toBeUndefined(); + expect((await stub.getMessages(session, 50)).messages).toHaveLength(sessionScoped ? 3 : 1); + response.webSocket!.close(); + } + ); + + it.each(['capable reader', 'unrelated legacy reader'])( + 'merges with a %s connected', + async (reader) => { + const { stub, session } = await setup(); + const watched = + reader === 'capable reader' + ? session + : await stub.createSession(source.workspaceId, 'Unrelated'); + const capability = reader === 'capable reader' ? '&messageAppend=message-append-v1' : ''; + const response = await stub.fetch( + new Request(`https://test/ws?sessionId=${watched}${capability}`, { + headers: { Upgrade: 'websocket' }, + }) + ); + expect(response.status).toBe(101); + response.webSocket!.accept(); + const log = vi.spyOn(console, 'log'); + await stub.persistMessageBatch(session, [chunk(1), chunk(2)], source); + await flush(stub); + expect(reports(log).at(-1)!.messageIngest).toMatchObject({ + coalesced: 1, + refused: {}, + legacySessionSocketsMax: 0, + legacyProjectSocketsMax: 0, + }); + response.webSocket!.close(); + } + ); + + it.each(['setting_disabled', 'missing_incarnation', 'invalid_sequence', 'receipt_cap'] as const)( + 'explains primary refusal %s', + async (reason) => { + const { stub, session } = await setup(reason !== 'setting_disabled'); + if (reason === 'receipt_cap') + vi.mocked(projectDataPorts().operations.messageMergeConfig!).mockResolvedValue({ + ...config, + maxRowBytes: 1024, + }); + const log = vi.spyOn(console, 'log'); + const input = + reason === 'receipt_cap' + ? Array.from({ length: 50 }, (_, index) => ({ + ...chunk(index + 1), + messageId: crypto.randomUUID(), + })) + : [chunk(2), chunk(reason === 'invalid_sequence' ? 1 : 3)]; + await stub.persistMessageBatch( + session, + input, + reason === 'missing_incarnation' ? { ...source, outboxIncarnation: undefined } : source + ); + await flush(stub); + expect(reports(log).at(-1)!.messageIngest).toMatchObject({ + batches: 1, + inserted: { assistant: input.length }, + accepted: { assistant: input.length }, + coalesced: 0, + refused: { [reason]: 1 }, + }); + } + ); + + it('does not publish outcomes when the actual persistence transaction rolls back', async () => { + const { stub, session } = await setup(); + const log = vi.spyOn(console, 'log'); + await runInDurableObject(stub, (instance) => { + const holder = instance as unknown as { sql: SqlStorage }; + const original = holder.sql; + holder.sql = new Proxy(original, { + get(target, key) { + if (key === 'exec') + return (query: string, ...bindings: unknown[]) => { + if (query.startsWith('INSERT INTO chat_messages ')) + throw new Error('controlled insert failure'); + return target.exec(query, ...bindings); + }; + return Reflect.get(target, key, target); + }, + }); + }); + expect(await captureBatchError(stub, session)).toMatchObject({ + threw: true, + message: 'controlled insert failure', + }); + await flush(stub); + expect(reports(log).at(-1)!.messageIngest).toMatchObject({ + batches: 0, + accepted: { assistant: 0 }, + coalesced: 0, + }); + expect((await stub.getMessages(session, 50)).messages).toHaveLength(0); + }); + it('retains committed counters and rows when later broadcasting fails', async () => { + const { stub, session } = await setup(); + const log = vi.spyOn(console, 'log'); + await runInDurableObject(stub, (instance) => { + const holder = instance as unknown as { + broadcastEvent: ( + type: string, + payload: Record, + sessionId?: string + ) => void; + }; + const original = holder.broadcastEvent.bind(holder); + holder.broadcastEvent = (type, payload, sessionId) => { + if (type === 'messages.batch') throw new Error('controlled post-commit broadcast failure'); + original(type, payload, sessionId); + }; + }); + expect(await captureBatchError(stub, session)).toMatchObject({ + threw: true, + message: 'controlled post-commit broadcast failure', + }); + await flush(stub); + expect(reports(log).at(-1)!.messageIngest).toMatchObject({ + batches: 1, + accepted: { assistant: 2 }, + inserted: { assistant: 1 }, + coalesced: 1, + }); + const rows = (await stub.getMessages(session, 50)).messages; + expect(rows).toHaveLength(1); + expect(rows[0]!.content).toBe('part1 part2 '); + }); + + it('explains source replacement and a delayed retired-source continuation', async () => { + const { stub, session } = await setup(); + const log = vi.spyOn(console, 'log'); + await stub.persistMessageBatch(session, [chunk(1), chunk(2)], source); + await stub.persistMessageBatch( + session, + [{ ...chunk(3), messageId: 'new-source', sequence: 1 }], + { ...source, outboxIncarnation: 'b5c61e7f-ae8d-4e2e-b77b-3c849ed6036b' } + ); + await stub.persistMessageBatch(session, [chunk(4)], source); + await flush(stub); + expect(reports(log).at(-1)!.messageIngest).toMatchObject({ + batches: 3, + refused: { retired_source: 1 }, + breaks: { source: 2 }, + }); + expect((await stub.getMessages(session, 50)).messages).toHaveLength(3); + }); + + it('identifies oversized and older-position initial rows without changing their inserts', async () => { + const { stub, session } = await setup(); + const log = vi.spyOn(console, 'log'); + await stub.persistMessageBatch( + session, + [{ ...chunk(1), content: 'x'.repeat(config.maxRowBytes) }], + source + ); + await stub.persistMessageBatch( + session, + [{ ...chunk(2), timestamp: new Date(1600000000000).toISOString() }], + source + ); + await flush(stub); + expect(reports(log).at(-1)!.messageIngest).toMatchObject({ + accepted: { assistant: 2 }, + inserted: { assistant: 2 }, + coalesced: 0, + breaks: { size_cap: 1, out_of_order: 1 }, + }); + }); +}); diff --git a/packages/project-data/README.md b/packages/project-data/README.md new file mode 100644 index 0000000000..2200eea89a --- /dev/null +++ b/packages/project-data/README.md @@ -0,0 +1,24 @@ +# ProjectData diagnostics + +The existing `project_data.row_usage` log reports approximate per-operation SQL reads/writes and alarm writes. `alarmWrites` is already included in `rowsWritten`. Counters live only in the Durable Object instance and can be lost on eviction; requested elapsed time is not logged coverage. + +`messageIngest` in the same log window explains batch persistence without logging message content, metadata, IDs or source identities: + +| Field | Meaning | +| ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `batches` | Batch persistence transactions that returned successfully, including duplicate-only batches | +| `received`, `accepted`, `inserted` | Transport chunks, newly accepted logical chunks, and physical inserts respectively, by fixed role (`user`, `assistant`, `thinking`, `tool`, `plan`, `system`, `other`) | +| `eligible` | Accepted assistant chunks with null stored tool metadata, regardless of whether the merge gate is enabled | +| `coalesced` | Logical chunks absorbed into an earlier canonical row, including merges within the same batch | +| `appendStatements` | Successful SQL updates to an existing canonical row; multiple chunks in one batch may share one update | +| `duplicates` | Chunks rejected as duplicates by the existing persistence logic | +| `mergeReadyBatches` | Batches passing setting, socket, source, sequence and receipt prerequisites (may contain no eligible chunks) | +| `refused` | Batches by their first applicable refusal: setting disabled, legacy client, missing incarnation, invalid sequence, retired source or receipt cap | +| `breaks` | Run boundary observations by fixed reason; `no_open` includes normal starts, not only failures | +| `legacyProjectSocketsMax`, `legacySessionSocketsMax` | Window maxima of open sockets without the append capability: on the batch's session (these refuse merging) and project-wide (diagnostic only; they get no transcript frames) | + +Primary refusal precedence is `setting_disabled`, `legacy_client`, `missing_incarnation`, `invalid_sequence`, `retired_source`, `receipt_cap`. Run-boundary reasons are `no_open`, `source`, `turn`, `intervening_writer`, `materialized`, `role`, `metadata`, `origin`, `sequence_gap`, `timestamp`, `out_of_order`, `size_cap`. Several independent boundaries can occur in one batch, so boundary counts do not partition batches. Admission of a legacy session socket seals that session's open run before persistence; `legacySessionSocketsMax` and `refused.legacy_client` identify that gate. `legacyProjectSocketsMax` shows stale session-list tabs without affecting merging. + +Diagnostics publish after the synchronous storage transaction returns, before asynchronous side effects. A rollback contributes no ingestion outcomes; a later broadcast/summary failure does not erase committed outcomes. Received counts include retry input; accepted/inserted/coalesced counts do not include duplicates. Batches that throw before commit contribute no ingestion counts, so SQL RPC calls and `batches` can differ. Existing SQL cursor attribution remains unchanged. Counters reset with the existing log window, have fixed cardinality, perform no SQL writes, and do not create timers or extra log lines. + +To distinguish a disabled merger from low eligible traffic, compare refusal reasons and socket maxima first, then accepted role mix, eligible share and coalesced chunks. A build version or enabled D1 setting alone does not prove a batch can merge. Compare production writes/call alongside accepted chunks/call and role mix; changes between unrelated time windows are not a controlled savings measurement. diff --git a/packages/project-data/src/do/index.ts b/packages/project-data/src/do/index.ts index e802e34c17..dac8c17e90 100644 --- a/packages/project-data/src/do/index.ts +++ b/packages/project-data/src/do/index.ts @@ -71,6 +71,7 @@ import * as logicalTranscript from './logical-transcript'; import * as mailbox from './mailbox'; import * as materialization from './materialization'; import * as messageContext from './message-context'; +import { emptyMessageIngestMetrics, refuseMerge } from './message-ingest-metrics'; import * as messagePersistence from './message-persistence'; import { DEFAULT_MESSAGE_MERGE_CONFIG, type MessageIngestSource } from './message-stream-ingest'; import * as messages from './messages'; @@ -125,7 +126,7 @@ import { admitBrowserSocket, broadcastToBrowserSockets, closeQuietly, - hasLegacySessionSocket, + countLegacySockets, } from './session-sockets'; import * as sessionState from './session-state'; import * as sessionSummarySync from './session-summary-sync'; @@ -908,16 +909,21 @@ export class ProjectData extends DurableObject { ? ((await projectDataPorts().operations.messageMergeConfig?.(this.env)) ?? DEFAULT_MESSAGE_MERGE_CONFIG) : DEFAULT_MESSAGE_MERGE_CONFIG; - // Only a socket watching this session can miss an append; project sockets never get - // transcript frames (session-sockets.ts). - const legacyClient = hasLegacySessionSocket(this.ctx, sessionId); + const metrics = emptyMessageIngestMetrics(); + const legacy = countLegacySockets(this.ctx, sessionId); + metrics.legacySessionSocketsMax = legacy.session; + // Informational only: project sockets get no transcript frames and never gate merging. + metrics.legacyProjectSocketsMax = legacy.project; + const legacyClient = legacy.session > 0; + if (!config.enabled) refuseMerge(metrics, 'setting_disabled'); + else if (legacyClient) refuseMerge(metrics, 'legacy_client'); return messagePersistence.persistMessageBatchWithSideEffects( this.sql, this.env, this.messagePersistenceHooks(), sessionId, batchMessages, - { source, config: { ...config, enabled: config.enabled && !legacyClient } } + { source, config: { ...config, enabled: config.enabled && !legacyClient }, metrics } ); }); } @@ -1014,6 +1020,7 @@ export class ProjectData extends DurableObject { private messagePersistenceHooks(): messagePersistence.MessagePersistenceHooks { return { + recordMessageIngest: (metrics) => this.rowUsage.recordMessageIngest(metrics), transactionSync: (fn) => this.meteredStorage.transactionSync(fn), recalculateAlarm: () => this.recalculateAlarm(), scheduleSummarySync: () => this.scheduleSummarySync(), diff --git a/packages/project-data/src/do/message-ingest-metrics.ts b/packages/project-data/src/do/message-ingest-metrics.ts new file mode 100644 index 0000000000..0465a0576c --- /dev/null +++ b/packages/project-data/src/do/message-ingest-metrics.ts @@ -0,0 +1,111 @@ +/** Content-free, fixed-cardinality diagnostics. Never persisted to SQLite. */ +export const INGEST_ROLES = [ + 'user', + 'assistant', + 'thinking', + 'tool', + 'plan', + 'system', + 'other', +] as const; +export type IngestRole = (typeof INGEST_ROLES)[number]; +export type MergeRefusal = + | 'setting_disabled' + | 'legacy_client' + | 'missing_incarnation' + | 'invalid_sequence' + | 'retired_source' + | 'receipt_cap'; +export type MergeBreak = + | 'no_open' + | 'source' + | 'turn' + | 'intervening_writer' + | 'materialized' + | 'role' + | 'metadata' + | 'origin' + | 'sequence_gap' + | 'timestamp' + | 'out_of_order' + | 'size_cap'; +type RoleCounts = Record; +const roles = (): RoleCounts => + Object.fromEntries(INGEST_ROLES.map((role) => [role, 0])) as RoleCounts; +function roleKey(role: string): IngestRole { + return INGEST_ROLES.includes(role as IngestRole) ? (role as IngestRole) : 'other'; +} +export interface MessageIngestMetrics { + batches: number; + received: RoleCounts; + accepted: RoleCounts; + inserted: RoleCounts; + eligible: number; + coalesced: number; + appendStatements: number; + duplicates: number; + mergeReadyBatches: number; + refused: Partial>; + breaks: Partial>; + legacyProjectSocketsMax: number; + legacySessionSocketsMax: number; +} +export function emptyMessageIngestMetrics(): MessageIngestMetrics { + return { + batches: 0, + received: roles(), + accepted: roles(), + inserted: roles(), + eligible: 0, + coalesced: 0, + appendStatements: 0, + duplicates: 0, + mergeReadyBatches: 0, + refused: {}, + breaks: {}, + legacyProjectSocketsMax: 0, + legacySessionSocketsMax: 0, + }; +} +export function countIngestRole(counts: RoleCounts, role: string): void { + counts[roleKey(role)]++; +} +/** A batch has one primary refusal; run boundaries are counted separately. */ +export function refuseMerge(metrics: MessageIngestMetrics | undefined, reason: MergeRefusal): void { + if (metrics && Object.keys(metrics.refused).length === 0) metrics.refused[reason] = 1; +} +export function breakMerge(metrics: MessageIngestMetrics | undefined, reason: MergeBreak): void { + if (metrics) metrics.breaks[reason] = (metrics.breaks[reason] ?? 0) + 1; +} +export function addMessageIngestMetrics( + total: MessageIngestMetrics, + batch: MessageIngestMetrics +): void { + for (const field of ['received', 'accepted', 'inserted'] as const) + for (const role of INGEST_ROLES) total[field][role] += batch[field][role]; + for (const field of [ + 'batches', + 'eligible', + 'coalesced', + 'appendStatements', + 'duplicates', + 'mergeReadyBatches', + ] as const) + total[field] += batch[field]; + for (const [key, value] of Object.entries(batch.refused)) { + const reason = key as MergeRefusal; + total.refused[reason] = (total.refused[reason] ?? 0) + value; + } + for (const [key, value] of Object.entries(batch.breaks)) { + const reason = key as MergeBreak; + total.breaks[reason] = (total.breaks[reason] ?? 0) + value; + } + total.legacyProjectSocketsMax = Math.max( + total.legacyProjectSocketsMax, + batch.legacyProjectSocketsMax + ); + total.legacySessionSocketsMax = Math.max( + total.legacySessionSocketsMax, + batch.legacySessionSocketsMax + ); +} diff --git a/packages/project-data/src/do/message-persistence.ts b/packages/project-data/src/do/message-persistence.ts index 40a5778237..b216843983 100644 --- a/packages/project-data/src/do/message-persistence.ts +++ b/packages/project-data/src/do/message-persistence.ts @@ -3,6 +3,7 @@ import { createModuleLogger } from '@simple-agent-manager/worker-core'; import * as activity from './activity'; import * as attention from './attention'; import * as idleCleanup from './idle-cleanup'; +import type { MessageIngestMetrics } from './message-ingest-metrics'; import type { MessageIngestSource, MessageMergeConfig } from './message-stream-ingest'; import * as messages from './messages'; import { observeReconciliationMessage } from './reconciliation-episode'; @@ -23,6 +24,7 @@ export type BatchMessageInput = { }; export type MessagePersistenceHooks = { + recordMessageIngest?: (metrics: MessageIngestMetrics) => void; transactionSync?: (fn: () => T) => T; recalculateAlarm: () => Promise; scheduleSummarySync: () => void; @@ -132,10 +134,16 @@ export async function persistMessageBatchWithSideEffects( hooks: MessagePersistenceHooks, sessionId: string, batchMessages: BatchMessageInput[], - merge?: { source?: MessageIngestSource; config: MessageMergeConfig } + merge?: { + source?: MessageIngestSource; + config: MessageMergeConfig; + metrics?: MessageIngestMetrics; + } ): Promise { const persist = () => messages.persistMessageBatch(sql, env, sessionId, batchMessages, merge); const result = hooks.transactionSync ? hooks.transactionSync(persist) : persist(); + // Publish only after the synchronous transaction commits; later effects may fail. + if (merge?.metrics) hooks.recordMessageIngest?.(merge.metrics); if (result.persisted === 0) { return { persisted: result.persisted, diff --git a/packages/project-data/src/do/message-stream-ingest.ts b/packages/project-data/src/do/message-stream-ingest.ts index b3f81b569b..6ed6b6a832 100644 --- a/packages/project-data/src/do/message-stream-ingest.ts +++ b/packages/project-data/src/do/message-stream-ingest.ts @@ -5,6 +5,13 @@ import { } from '@simple-agent-manager/shared'; import * as v from 'valibot'; +import { + breakMerge, + countIngestRole, + type MessageIngestMetrics, + refuseMerge, +} from './message-ingest-metrics'; + export const DEFAULT_MESSAGE_MERGE_CONFIG = { enabled: false, maxRowBytes: 64 * 1024, @@ -105,7 +112,8 @@ export class MessageStreamBatch { latestPosition: MessagePosition | null, materializedThrough: { createdAt: number; sequence: number } | null, messageIds: readonly string[], - messageCount: number + messageCount: number, + private readonly metrics?: MessageIngestMetrics ) { this.latestPosition = latestPosition; this.messageCount = messageCount; @@ -122,6 +130,7 @@ export class MessageStreamBatch { (index === 0 || sequence > (sequences[index - 1] ?? Number.MAX_SAFE_INTEGER)) ); const sameSource = sourceKey !== null && previous?.source === sourceKey; + if (previous?.open && !sameSource) breakMerge(metrics, 'source'); const retired = { ...(previous?.retired ?? {}) }; this.retiredSource = sourceKey !== null && Object.hasOwn(retired, sourceKey) ? sourceKey : null; if (sourceKey && !sameSource && !this.retiredSource && previous?.source) @@ -167,7 +176,25 @@ export class MessageStreamBatch { : 0 : 0; this.canMerge = config.enabled && this.canSequence && !this.retiredSource && receiptFits; + if (!config.enabled) refuseMerge(metrics, 'setting_disabled'); + else if (!sourceKey) refuseMerge(metrics, 'missing_incarnation'); + else if (!validSequence) refuseMerge(metrics, 'invalid_sequence'); + else if (this.retiredSource) refuseMerge(metrics, 'retired_source'); + else if (!receiptFits) refuseMerge(metrics, 'receipt_cap'); + else if (metrics) metrics.mergeReadyBatches++; const open = this.state.open; + if (open && this.canMerge) { + if (open.id !== latestPosition?.id || open.messageCount !== messageCount) + breakMerge(metrics, 'intervening_writer'); + else if (open.turn !== turn) breakMerge(metrics, 'turn'); + else if ( + materializedThrough && + (open.createdAt < materializedThrough.createdAt || + (open.createdAt === materializedThrough.createdAt && + open.sequence <= materializedThrough.sequence)) + ) + breakMerge(metrics, 'materialized'); + } if ( !this.canMerge || open?.id !== latestPosition?.id || @@ -206,6 +233,8 @@ export class MessageStreamBatch { /** Role/metadata/origin/gaps/cap/turn boundaries end a run, even on duplicate user echoes. */ boundary(role: string, toolMetadata: string | null): void { + if (this.state.open && (role !== 'assistant' || toolMetadata !== null)) + breakMerge(this.metrics, role !== 'assistant' ? 'role' : 'metadata'); if (role !== 'assistant' || toolMetadata !== null) this.state.open = null; } @@ -220,6 +249,7 @@ export class MessageStreamBatch { const contentBytes = new TextEncoder().encode(JSON.stringify(message.content)).byteLength - 2; const open = this.state.open; const eligible = this.canMerge && message.role === 'assistant' && message.toolMetadata === null; + if (eligible) this.recordContinuationBreak(message, sequence, contentBytes); if ( eligible && open && @@ -228,22 +258,8 @@ export class MessageStreamBatch { message.createdAt >= open.lastCreatedAt && open.bytes + contentBytes <= this.config.maxRowBytes ) { - const existing = this.inserts.get(open.id); - if (existing) existing.content += message.content; - else { - const update = this.updates.get(open.id); - if (update) { - update.content += message.content; - update.revision += message.content.length; - } else - this.updates.set(open.id, { - id: open.id, - sessionId: this.sessionId, - content: message.content, - offset: open.length, - revision: open.length + message.content.length, - }); - } + if (this.metrics) this.metrics.coalesced++; + this.stageContentAppend(open.id, message.content, open.length); open.length += message.content.length; open.bytes += contentBytes; open.lastSequence = sequence; @@ -258,6 +274,7 @@ export class MessageStreamBatch { ).byteLength; const newest = !this.latestPosition || compareMessagePositions(message, this.latestPosition) >= 0; + if (eligible) this.recordOpeningBreak(message, bytes); if (newest) this.latestPosition = message; this.state.open = eligible && newest && bytes <= this.config.maxRowBytes @@ -277,12 +294,53 @@ export class MessageStreamBatch { return message.id; } + private stageContentAppend(id: string, content: string, offset: number): void { + const existing = this.inserts.get(id); + if (existing) existing.content += content; + else { + const update = this.updates.get(id); + if (update) { + update.content += content; + update.revision += content.length; + } else + this.updates.set(id, { + id, + sessionId: this.sessionId, + content, + offset, + revision: offset + content.length, + }); + } + } + + private recordContinuationBreak( + message: StoredBatchMessage, + sequence: number | undefined, + contentBytes: number + ): void { + const open = this.state.open; + if (!open) breakMerge(this.metrics, 'no_open'); + else if (open.origin !== message.origin) breakMerge(this.metrics, 'origin'); + else if (sequence !== open.lastSequence + 1) breakMerge(this.metrics, 'sequence_gap'); + else if (message.createdAt < open.lastCreatedAt) breakMerge(this.metrics, 'timestamp'); + else if (open.bytes + contentBytes > this.config.maxRowBytes) + breakMerge(this.metrics, 'size_cap'); + } + + private recordOpeningBreak(message: StoredBatchMessage, bytes: number): void { + const newest = + !this.latestPosition || compareMessagePositions(message, this.latestPosition) >= 0; + if (!newest) breakMerge(this.metrics, 'out_of_order'); + else if (bytes > this.config.maxRowBytes) breakMerge(this.metrics, 'size_cap'); + } + flush(sql: SqlStorage): { broadcastMessages: StoredBatchMessage[]; appends: ChatMessageAppend[]; state: string; } { - for (const message of this.inserts.values()) + for (const message of this.inserts.values()) { + if (this.metrics) countIngestRole(this.metrics.inserted, message.role); sql.exec( `INSERT INTO chat_messages (id, session_id, role, content, tool_metadata, created_at, sequence, origin) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, @@ -295,6 +353,7 @@ export class MessageStreamBatch { message.sequence, message.origin ); + } for (const append of this.updates.values()) { const changed = sql .exec( @@ -305,6 +364,7 @@ export class MessageStreamBatch { ) .toArray(); if (changed.length !== 1) throw new Error('Canonical message append lost its stored base'); + if (this.metrics) this.metrics.appendStatements++; } // Refresh duplicates too: a failed local outbox DELETE can resend one old ID // alongside arbitrarily many newer batches. Keeping only NEW IDs loses it. diff --git a/packages/project-data/src/do/messages.ts b/packages/project-data/src/do/messages.ts index d10b387f12..b0df7b0c35 100644 --- a/packages/project-data/src/do/messages.ts +++ b/packages/project-data/src/do/messages.ts @@ -10,6 +10,7 @@ import { type ProjectDataArchiveSourceIntentState, } from '../archive/contract'; import { messageBoundsClause } from './message-cursor'; +import { countIngestRole, type MessageIngestMetrics,refuseMerge } from './message-ingest-metrics'; import { type MessageIngestSource, type MessageMergeConfig, @@ -153,7 +154,11 @@ export function persistMessageBatch( sequence?: number; origin?: string | null; }>, - context?: { source?: MessageIngestSource; config: MessageMergeConfig } + context?: { + source?: MessageIngestSource; + config: MessageMergeConfig; + metrics?: MessageIngestMetrics; + } ): { persisted: number; duplicates: number; @@ -194,6 +199,13 @@ export function persistMessageBatch( throw new Error(`Session ${sessionId} is stopped and cannot accept messages`); } + const metrics = context?.metrics; + if (metrics) { + metrics.batches++; + for (const message of messages) countIngestRole(metrics.received, message.role); + } + if (!context?.config.enabled) refuseMerge(metrics, 'setting_disabled'); + else if (!context.source?.outboxIncarnation) refuseMerge(metrics, 'missing_incarnation'); const previousStream = readMessageIngestState(session.stream_ingest_state); if (context?.source && (context.config.enabled || previousStream)) assertSessionIdentityGuard(sql, sessionId, 'persist message batch', { @@ -236,7 +248,8 @@ export function persistMessageBatch( } : null, messages.map((message) => message.messageId), - parseMessageCount(session, 'messages.batch_stream_count') + parseMessageCount(session, 'messages.batch_stream_count'), + metrics ) : null; @@ -366,6 +379,11 @@ export function persistMessageBatch( sequence, origin ); + if (metrics) { + countIngestRole(metrics.accepted, msg.role); + if (msg.role === 'assistant' && storedToolMetadata === null) metrics.eligible++; + if (!stream) countIngestRole(metrics.inserted, msg.role); + } persisted++; persistedMessages.push({ id: canonicalId, @@ -382,6 +400,7 @@ export function persistMessageBatch( let firstUserContent: string | null = null; const hadTopic = !!session.topic; const staged = stream?.flush(sql); + if (metrics) metrics.duplicates = duplicates; if (persisted > 0) { if (staged) diff --git a/packages/project-data/src/do/row-usage.ts b/packages/project-data/src/do/row-usage.ts index fab918b722..ba9660ac75 100644 --- a/packages/project-data/src/do/row-usage.ts +++ b/packages/project-data/src/do/row-usage.ts @@ -2,6 +2,12 @@ import { AsyncLocalStorage } from 'node:async_hooks'; import { createModuleLogger } from '@simple-agent-manager/worker-core'; +import { + addMessageIngestMetrics, + emptyMessageIngestMetrics, + type MessageIngestMetrics, +} from './message-ingest-metrics'; + const log = createModuleLogger('project_data'); import { DEFAULT_ROW_USAGE_INTERVAL_MS, ROW_USAGE_LABEL_LIMIT } from './row-usage-config'; export { DEFAULT_ROW_USAGE_INTERVAL_MS, ROW_USAGE_LABEL_LIMIT } from './row-usage-config'; @@ -27,6 +33,11 @@ export class RowUsage { } | null = null; private windowStart = Date.now(); intervalMs = DEFAULT_ROW_USAGE_INTERVAL_MS; + private messageIngest = emptyMessageIngestMetrics(); + + recordMessageIngest(batch: MessageIngestMetrics): void { + addMessageIngestMetrics(this.messageIngest, batch); + } constructor( private readonly projectId: () => string | null, @@ -165,11 +176,13 @@ export class RowUsage { labels: Object.fromEntries(selected.map((entry, rank) => [`rank${rank}`, entry])), droppedLabelCount: dropped.length, totalLabelCount: labels.length, + messageIngest: this.messageIngest, }); } catch { // Accounting must never change RPC return values or replace an application's error. } this.totals.clear(); + this.messageIngest = emptyMessageIngestMetrics(); this.windowStart = now; try { this.afterFlush(); diff --git a/packages/project-data/src/do/session-sockets.ts b/packages/project-data/src/do/session-sockets.ts index eb91c9dc25..2996acc267 100644 --- a/packages/project-data/src/do/session-sockets.ts +++ b/packages/project-data/src/do/session-sockets.ts @@ -65,18 +65,30 @@ export function admitBrowserSocket(ctx: DurableObjectState, sql: SqlStorage, url } /** - * Whether an open socket subscribed to this session cannot apply `message.append`. A socket the - * server already closed (for example after a resync) stays listed while its close handshake is - * pending; it receives nothing more, so it must not keep merging off. + * Open sockets without the `message.append` capability, for one session's ingest. `session` + * counts those subscribed to the session: they gate merging for it. `project` counts unscoped + * ones: they never receive transcript frames, so they are reported for diagnostics only. A socket + * the server already closed (for example after a resync) stays listed while its close handshake is + * pending; it receives nothing more, so it is not counted. */ -export function hasLegacySessionSocket(ctx: DurableObjectState, sessionId: string): boolean { - return ctx - .getWebSockets(sessionTag(sessionId)) - .some( - (ws) => - ws.readyState === WebSocket.OPEN && - !tagsOf(ctx, ws)?.includes(CHAT_MESSAGE_APPEND_CAPABILITY) - ); +export function countLegacySockets( + ctx: DurableObjectState, + sessionId: string +): { session: number; project: number } { + const own = sessionTag(sessionId); + let session = 0; + let project = 0; + for (const ws of ctx.getWebSockets()) { + if (ws.readyState !== WebSocket.OPEN) continue; + const tags = tagsOf(ctx, ws); + // A socket whose tags cannot be read cannot be attributed to a session (it is almost + // certainly gone), so it is not counted for either scope. + if (!tags || tags.includes(CHAT_MESSAGE_APPEND_CAPABILITY)) continue; + const tag = tags.find((t) => t.startsWith(SESSION_TAG_PREFIX)); + if (!tag) project++; + else if (tag === own) session++; + } + return { session, project }; } function send(ws: WebSocket, message: string): void { diff --git a/packages/project-data/tests/unit/session-sockets.test.ts b/packages/project-data/tests/unit/session-sockets.test.ts index 48061a60fb..81e34233af 100644 --- a/packages/project-data/tests/unit/session-sockets.test.ts +++ b/packages/project-data/tests/unit/session-sockets.test.ts @@ -12,7 +12,7 @@ import { describe, expect, it, vi } from 'vitest'; import { broadcastToBrowserSockets, closeQuietly, - hasLegacySessionSocket, + countLegacySockets, } from '../../src/do/session-sockets'; const SESSION = '11111111-2222-3333-4444-555555555555'; @@ -99,11 +99,20 @@ describe('broadcastToBrowserSockets failure isolation', () => { }); }); -describe('hasLegacySessionSocket', () => { - it('counts only open sockets without the capability', () => { +describe('countLegacySockets', () => { + it('counts open sockets without the capability, by scope', () => { const closing = socket(session); closing.readyState = WebSocket.CLOSING; - expect(hasLegacySessionSocket(context([closing, socket(capable)]), SESSION)).toBe(false); - expect(hasLegacySessionSocket(context([closing, socket(session)]), SESSION)).toBe(true); + const other = socket(['session:99999999-2222-3333-4444-555555555555']); + expect(countLegacySockets(context([closing, other, socket(capable)]), SESSION)).toEqual({ + session: 0, + project: 0, + }); + expect( + countLegacySockets( + context([closing, socket(session), socket([]), socket([CHAT_MESSAGE_APPEND_CAPABILITY])]), + SESSION + ) + ).toEqual({ session: 1, project: 1 }); }); }); diff --git a/tasks/archive/2026-11-16-message-merge-diagnostics.md b/tasks/archive/2026-11-16-message-merge-diagnostics.md new file mode 100644 index 0000000000..d8410b7ca8 --- /dev/null +++ b/tasks/archive/2026-11-16-message-merge-diagnostics.md @@ -0,0 +1,169 @@ +# Explain production message-merging write rates + +The first 30 minutes of production ON coverage showed 27.38 writes/call versus24.65 OFF. Current row_usage telemetry cannot distinguish merger precondition failures from a low assistant-text share. A stale project WebSocket can disable merging for all sessions. + +Authorized by parent task01M7CVZNSP0EHV9BJ72HCFQJSC eventc25c632b-edbd-4c95-8d3d-8b59bad3c098 as a counter-only followup to PR2760. + +Research: ProjectData.index persistMessageBatch combines admin setting with relevant socket capabilities; MessageStreamBatch evaluates source/sequence/receipt/open-row boundaries; messages.persistMessageBatch applies transaction writes; RowUsage aggregates in memory and flushes existing log windows. ACP thinking/tool rows are excluded from assistant merging. Existing reporter fixture has no thinking. + +- [x] Add bounded content-free counters to existing row_usage windows: received/accepted/inserted by fixed role, eligible accepted chunks, coalesced chunks, append SQL statements, refused batches and run breaks by fixed enums. +- [x] Sample legacy session/project socket counts as window maxima. Preserve all storage, wire and configuration behavior, add no SQL writes or schema. +- [x] Record committed synchronous persistence outcomes even if later side effects fail; no outcomes from rollback. +- [x] Real-workerd tests drive persistence, retries, refusal gates, legacy sockets, role mix, same-batch and cross-batch merges, flush/reset and no extra SQL writes; negative-control discrimination. +- [ ] Relevant build/lint/typecheck/tests and required quality checks; local domain/completion review, CodeRabbit best effort. +- [ ] Coordinate per-installation staging lease, deploy, real Claude thinking/tool-heavy ON/OFF comparison and legacy socket gate; record counts/hash only and clean all owned resources/auth/settings. +- [ ] PR green, merge, first successful production deploy containing commit; read-only counters report and H1/H2 conclusion if supported. + +Acceptance: fixed-cardinality logs explain effective gates and physical outcomes without content/IDs or new storage writes. ON/OFF transcript/storage behavior stays identical to approved PR2760. Representative live run reports role mix, eligibility, append/insert counts and writes/call. Explain stale-client mitigation and thinking/tool followups without changing them in this PR. + +## Continuation handoff — 2026-11-16 01:02 UTC + +Owner task `01M7E19YHSJ73896Q84ASSGFDN`, parent `01M7CVZNSP0EHV9BJ72HCFQJSC`, project `01KHRJGANBBWGDY1NZ0KVF0D4J`. PR2773 is the counter-only followup; original storage PR2760 already merged as `7bea824b926009e5fbec5a1aed456a8f8663124c` and first successful whole production deploy43744172794 completed18:17:48UTC Nov15. Do not redo its closed staging work. This task is NOT complete. Use `/do`, call SAM get_instructions first, read current task/output branch, report session credential_limits scope=session. Work in primary checkout on `sam/store-streamed-agent-replies-ssgfdn`, no outside worktrees. Never inspect/stage the unrelated credential-bearing `.codex/config.toml` modification. No production mutations/auth/provisioning. No message content, tokens or raw logs in reports. + +Parent's verified peer event `9bf8e991-26c0-423e-89ab-4aa8c4354451` requests this handoff, then only PR2773 CI/staging/merge and the01:40 production read on this credential. Do NOT start the separately authorized socket-scope PR on this credential. Stop routine coordinator status messages; send only results, blockers and handoff pointers. Codex allowance was94% at00:57 (parent observed95% at00:58), reset2026-11-18T07:01:07Z. A Claude task may take over. + +### Counter PR gates and implementation + +Production implementation `df8bef973`; test-only duplication cleanup `d9dbfc6e35d211d80726f757e0c11f4ea9ceb49a`. A subsequent handoff-only commit may be current: ALWAYS query PR current full SHA/checks. Fixed diagnostic schema in `packages/project-data/src/do/message-ingest-metrics.ts`; index samples effective configuration/socket gates, messages/stream ingest count transaction outcomes, persistence hook publishes AFTER transactionSync returns BEFORE awaited side effects, RowUsage aggregates in memory and resets with EXISTING log window. No schema, SQL, settings, timer, extra log-line or wire behavior changes. README defines semantics. New workerd file `apps/api/tests/workers/project-data-message-ingest-metrics.test.ts`. + +Counters: received/accepted/inserted fixed roles(user/assistant/thinking/tool/plan/system/other), eligible accepted assistant with null stored metadata even if disabled, coalesced logical chunks, successful append UPDATE statements, duplicates, mergeReadyBatches, primary refusal(setting_disabled/legacy_client/missing_incarnation/invalid_sequence/retired_source/receipt_cap), bounded run breaks(including size_cap/out_of_order), relevant legacy project/session socket window maxima. Same-batch coalesces need not produce UPDATE. Rollback contributes no counters; postcommit broadcast failure retains committed counts. Never turn identities/content/arbitrary metadata into labels. + +Phase1 research,2 checkout,3 implementation COMPLETE. Phase4 full `pnpm lint && pnpm typecheck && pnpm test && pnpm build` PASS; API15542tests passed/4skipped,1031files passed/3skipped. Base real-workerd43PASS, focused metrics13PASS; after d9 test-only dedup13PASS again(session46643). Billed reporter fixture unchanged6615OFF/1596ON, no additional SQLwrites. Negative control nooped publication only in first positive test: intended assertion RED(exit1), exact original restored. AST/file-size/DOmigration/runtime-boundaries/observability-noise PASS; latter live telemetry404skipped. Gitleaks pinned8.30.1 checksumverified, committed-content snapshot43reviewed/0new PASS; snapshot deleted. Local qualityscript failures were root-owned temp/generated dependency traversal/loadedCPU; quiet timeout rerun65PASS; current d9 CI Code Quality Checks SUCCESS reconciles clean environment. Do not weaken gates or alter protected runtime files. + +Phase5 COMPLETE: local counter_review Cloudflare/test findings(initial-row size/order reasons and commit-then-broadcastfailure test) ADDRESSED/rereviewPASS; doc-sync/constitutionPASS; completion implementation readinessPASS, overall live/release still pending. Incremental d9 test-only review PASS, no scenarios/assertions weakened. No pending reviewers. Mandatory completion validation again before eventual archive. + +Phase6 PENDING, merge-blocking: new counter PR has NO live staging evidence, NO owned resources/auth/settings/lease. Phase7 PR2773 OPEN/ready, full CI pending. At00:59 d9: no failures; Code Quality, lint, build/typecheck, other packages, Secret Scan, PR Evidence, mock/worker smoke SUCCESS; API3shards/DO7shards/CLI pending. Sonar result not yet available on d9. Old641 Sonar10.4% duplicationFAILED entirely in test setup; d9 parameterized equivalent socket cases/shared error-transport helper, no production change. ALL checks including Sonar and aggregate Durable Object Workers must pass current fullhead. + +CodeRabbit BEST-EFFORT COMPLETE: label00:39:48; trusted request run43781697388SUCCESS/comment6904142750 at00:40:43; bot rate-limit6904144077 at00:40:48; no submitted reviews/findings. Updated auto summary6904125671 at00:53:40 says auto reviews disabled/skipped. No manual retrigger for handoff/test cleanup; later actual review remains binding. PR evidence contains receipt links. + +### Durable waits and exact reconciliation + +Session `c2dad030-146f-4876-956a-88e2d35b98b9`. Current CI subscription527e128f-2ab3-49fd-9bc7-9da12dc7cde3 tracks d9 ONLY, expires04:54:28UTC/minwake10m; cancel/replace if handoff commit advances head. PR review subscription559eb28b-5fad-450a-999d-cebc8af0c15b active until04:40. Accepted CI fallback742cdc5a-3319-4d8d-bde4-f1e294c22b20 due01:15/expires01:45. Its prompt says reconcile actual current head, so remains usable after documentation commit. Inspect state:any on resume; read/ACK event IDs. Query GitHub immediately before/after subscription. Save new SHA/subscription in PR/task/localstate. After fallback if still pending report exact check URLs/delivery status; no blind renewal. Old641subscriptionc636 and01:00fallbackd2da CANCELLED. Staging queue checkpoint3950a0fc-dd9a-4c4e-b86a-24b790e92cb3 due01:31:14.143/expires02:01:14.143. Production01:40 schedule below independent. + +### Staging queue, plan and cleanup + +Explicit parent order: L5a → reads-fix PR2765/task01M7GB4125DFTECRYYCAHXAWTS → security PR2755/task01M7FPX2RR5JSJ1CYG6QPXY9VG → us. Coordination channel `feature.selfhost-spike`; follow subscriptione5bd33d4-f979-4820-9a31-cca864ab92c0 active until08:40, watermark215 when created. Check latest channel cleanup/release receipts and both environment leases before action. Last audit00:33: staging2 held by L5a task01M7FCZD2APNNX1T08Z6ZJGMC7 branchsam/task-l5-landing-slice-zjgmc7 deployment7812255949 expiry01:31:14.143; primary held by01M7C1SRMAWR3PYFWKF03XJ273 branchsam/implement-phase-3-run-3xj273 deployment7812411212 expiry02:38:46.609. Expiry does NOT override queued peers. Primary reportedly has unmerged PR2721 DOv23 migration mismatch; not independently verified, don't fallback there without confirming. No chat polling/lease negotiation. + +Read `.agent-instructions/reference/rules/13-staging-verification-full.md`. Acquire/deploy only via `gh workflow run deploy-staging.yml --ref sam/store-streamed-agent-replies-ssgfdn -f environment=staging2 -f sam_task_id=01M7E19YHSJ73896Q84ASSGFDN -f lease_hold_minutes=`. No Cloudflare Worker settings PATCH. Staging settings via admin API/UI or deploy-staging. Workload identity audience `https://api.sammy2.party/api/auth/workload-identity-login`, targets staging2-agent-admin/user, cookie `.sammy2.party`. Bootstrap provides effective platform compute and Claude Code proxy key; no personal credential needed. Use Artifacts-backed project(no GitHubApp), Claude Code `providerMode:sam` (installation default has no agent key), explicitly thinking-enabled session. Effective Hetzner/pool exists, cap2nodes. Missing local Claude key is NOT blocker. Keep routine verification bounded, estimate incremental bill before unusually costly/repeated tests. + +Live plan: create one owned project/session/workspace using normal app/API; record all owned IDs without content. Run a real thinking-enabled Claude tool-heavy turn with long streamed assistant text ON and OFF (save original staging settings and restore). Watch incremental reply in browser, reload/hash exact content, capture bounded existing row_usage windows with new messageIngest fields. Compare raw-role counts/accepted eligibility/coalesces/actual UPDATE/physical inserts/writes percall, normalize traffic; thinking/tools intentionally remain unmerged. Reproduce legacy socket admission with actual `/sessions/ws` lacking message-append-v1 while setting ON. After #2774 (merged into this branch), a project socket is diagnostic only: legacyProjectSocketsMax>0 with no refusal and merging continuing; a session-scoped legacy socket produces refused.legacy_client>0 for its session. (Superseded the pre-#2774 expectation that a project socket refuses.) Sessionlegacy gate also real-workerd covered. Never claim noappend from lack of existing success logs. Use hashes/counts/sizes only. If eligible density or equivalence fails, report rather than approximating. No web code changed in counterPR; future UIchanges require375/1280visualaudit. + +Clean every owned workspace/node/project/auth/settings promptly, verify provider resource absence using current strict cleanup workflow, then release only own lease through same deployment workflow `-f lease_action=release`; confirm newest leasepayloadreleased. Preserve unrelated resources/leases. No staging helper/kit has yet been built for this counter PR. Original PR2760 staging kit/auth authority is CLOSED and must NOT be replayed. Build fresh bounded helper from current API reference if needed. + +### Production read at01:40 UTC — read-only only + +Human Raphaël enabled `chat.messageMergingEnabled` at `2026-11-15T23:07:03.647Z` (D1true, auditsetrevision5). Leave ON. No human reload timestamp supplied; don't invent one. Accepted pending schedule `8bd6717a-c446-41e6-8368-8e4a0f28fe51` due01:40/expires02:10. Helper Library `01M7GR3V4QB8FK4ZWXPBJRFCWH`(5741bytes), restore via download_library_file targetPath RELATIVE DIRECTORY `.tmp`. Local `.tmp/chunk-production-on-observe.mjs`. Invoke exec_with_secrets literal command argv `["node","/workspaces/simple-agent-manager/.tmp/chunk-production-on-observe.mjs","2026-11-15T23:07:03.647Z"]`, cwdabsolute, secretNames EXACTLY `["CF_PRODUCTION_DEBUGGING_TOKEN","CF_PRODUCTION_ACCOUNT_ID"]`, timeout180000; poll terminal. Outputs counts-only `.tmp/chunk-production-on-observation.json`, upload unique filename. Helper reads D1setting/audit, fleet, Worker versions, existing logusage and3knownfailureevents. It does NOT parse new counters; counterPR not deployed yet. If upgrading helper later, never paste rawlogs or content. + +Require >=2h ACTUAL union covered fully postactivation windows, exclude straddlers/gaps; requested duration is not coverage. rowsWritten ALREADY INCLUDES alarmWrites. OFFbaseline:3145calls/77524writes(including2747alarms),2.0018577778coveredhours,24.6499205087writes/call,38726.027823writes/coveredhour. Library `01M7GJWF4PY69V8HAPQZV0YGK2`. Historical26.4writes/call. IntermediateON00:07: 2windows23:23:08.802–23:53:09.098,0.500082222h,978calls/26775writes(including765alarms)/17544644rowsRead;27.3773006writes/call(+11.0645%vsOFF),53541.1954/hour. NO savings demonstrated; uncontrolled traffic, cannot attribute. Perwindow droppedLabels37/40 though persistlabelpresent. All3bounded knownfailurequeries0hits, not universalabsence. Fleet2nodes/13workspacesall7bea onlycapabilityinventory; Worker96be100%. ArtifactLibrary `01M7GTXHZN74YC89TCVPS8KYES`, idea note01M7GTY167VT1N7HRCPM07VTGN. Finalcounts post note to idea `01M7CX61WVX72T7CFQNRTX0DVM` and send parent results. Ifcoverageinsufficient report exact gap, no timerloop. Existing sessions_read returns grouped rows; cannot prove rawrole density. Future deployed counters are needed for H1(refusal)vsH2(loweligibletraffic). + +### Release and next PR findings + +Before merge recheck all CI/review/staging gates and current-main production deploy waiting on CI; do not supersede its queued deployment blindly. Merge2773 only after staging. Receipt = FIRSTsuccessful whole DeployProduction whose head contains countercommit. Trusted-main-tip mismatch is supersession: reconcile latestmainCI/deploy, dispatch currenttipdeploy if needed only after exactCIgreen. Basic productionhealth/version smokeonly; no fullauthenticatedtests. Then read new counters honestly whenavailable. Overall task stays active until requiredresults/handoff. + +Next socket-scope PR is authorized by parent evente6e46d8f but MUST be separate AFTER2773merge, and MUST NOT start on near-exhaustedcredential. Audit findings: repo productconsumers `/sessions/ws` are useProjectWebSocket(unscoped) and useChatWebSocket(session-scoped); pre2760/current projecthook only consumes lifecycle/attention/comments/access and ignores transcripts. APIroute `apps/api/src/routes/chat.ts:105` forwards rawrequest via project-data client about3338. Actual `packages/project-data/src/do/index.ts:4043` broadcastEvent currently sends session transcriptframes to taggedsession AND allunscopedproject sockets. Public `apps/www/src/content/docs/docs/reference/api.md:19` and routecomment promise that, so change docs with narrowed contract; no claim externalclientsaudited. Removeproject/unscoped sockets from transcriptcapabilitygate AND filter their message.new/messages.batch/message.append sends. Retain relevantlegacysessiongate. Critical race: a legacysessionsocket may connect AFTER per-batchgate during awaitedsideeffects, so ALSO filter message.append per-socketcapability AT SEND. Realpath tests: projectlegacy no longerdisablesmerge; sessionscopelegacy onlydisablesownsession; legacychat NEVER gets unsupportedappend, includingcontrolledlateconnectrace. Don't merely callprivatehandlerdirectly. Ifweb/acp-clientchanges runmandatory375/1280visualaudit. Thinking future needs openrowrole/checksamekind; toolupdates requirepresence-awaresametoolCallIdmetadata semantics, neverJSONconcat. Recommendations only until realdensity supports them. + +### Sonar complexity followup — 2026-11-16 01:11UTC + +After the handoff, Sonar reported Quality Gate PASS with0.0% duplication, but also CRITICAL typescript:S3776 on stage cognitivecomplexity26>15. Extracted only the newly added diagnostic reason chains into recordContinuationBreak and recordOpeningBreak, preserving eligibility, calltiming, precedence and all merge/SQL conditions. Incremental specialist review PASS. ESLint/Prettier/project-data build PASS; direct real-workerd four affected suites48/48PASS(75.22s), including13counter cases and existingmerge/upgrade/rowusagecoverage. Two earlier wrapper runs were deliberately terminated143 without results and are not claimed as PASS. Current code changes require fresh exacthead CI/Sonar before merge. No new scope/behavior or stagingresources. + +### Final Sonar refactor followup — 2026-11-16 01:19UTC + +The first helper extraction reduced stage complexity to17 but did not clear S3776, and its boolean diagnostic parameter triggered S2301. Extracted existing append accumulation into stageContentAppend(id,content,offset), and opening diagnostics now derive their predicate from the message before latestPosition mutates. Specialist review PASS: insert/update choice, content, offsets, revisions and reason precedence preserved. ESLint/project-data build PASS; final four-suite real-workerd rerun48/48PASS. Fresh exacthead CI/Sonar must still pass before merge. + +## FINAL TRANSFER — 2026-11-16 01:49UTC (supersedes earlier ownership and waits) + +Coordinator decision event e720a35f-6d5b-4978-958b-bd33fb91404e transfers remaining PR2773 staging, merge, production deploy and first counter read to Claude task 01M7GY0BKP1WESE5Y82PZNN42S (PR2774), which holds staging2. This Codex task MUST NOT take a lease, deploy or merge, and starts no new work. It remains reachable for questions. Counter source candidate 2a86d7f55a9f5d587d73b5ad2297f82ebbaa2852 has ALL CI PASS/SKIP, including aggregate Test/Workers and Sonar zero issues. The final transfer commit changes only the task document; deploy the tested exact source head if requested by coordinator, then reconcile CI on the current documentation head before merge. PR2774 must verify independently; do not silently treat its modified socket behavior as counter-only proof. + +Production observation remains 1.750881667 actual covered hours, 4054 calls /112301 writes INCLUDING3190 alarms, 27.7013 writes/call versus24.6499 OFF. No demonstrated saving. Coordinator event517a43ef requested cancellation of top-up; 01:50 schedule0f3302f3 CANCELLEDv2. No >=2h completion claimed. No production changes. Next useful observation is after counters AND gate fix are deployed. + +Exact staging counter read, without raw log disclosure: + +1. Helper Library01M7H0F82Y6T0XASP58Z1T46ZZ, filename message-ingest-staging-counts.mjs,4530bytes. Restore with download_library_file(fileId=01M7H0F82Y6T0XASP58Z1T46ZZ,targetPath=".tmp") — targetPath is a relative DIRECTORY. The helper is syntax-checked only; live execution belongs to the lease holder. It queries sam2-api-staging2 in the staging Cloudflare account, fixed numeric fields only. It never prints message content, source/session/message IDs or arbitrary metadata. +2. Record isolated test project ID and phase start/end UTC timestamps in the holder's local state. Use separate OFF/ON/legacy phases, one owned session per phase or non-overlapping complete log windows. A project usage window includes every session in that project; it is not a per-session counter. Let the initial window settle before measuring. +3. Under exec_with_secrets use EXACT staging secretNames ["CF_TOKEN","CF_ACCOUNT_ID"], cwd "/workspaces/simple-agent-manager", timeoutMs180000 and literal argv: + + ["node","/workspaces/simple-agent-manager/.tmp/message-ingest-staging-counts.mjs","","",""] + + Replace angle placeholders with actual IDs/timestamps, not shell expansions. Poll exec_with_secrets_status until terminal. The helper writes .tmp/message-ingest-staging-counts.json and prints only numeric counter JSON. Upload a distinct phase-named copy. No production secrets for staging. Do not use wrangler tail or publish raw telemetry. + +4. Flush interval is runtime admin setting operations.projectDataRowUsageIntervalMs, default15min, min60000. In leased staging only, save original value and temporarily select60000 through the admin settings API/UI if bounded live testing needs it. GET https://api.sammy2.party/api/admin/settings returns {revision,settings,history}; PATCH same URL with authenticated admin browser credentials and JSON {expectedRevision:,changes:[{name:"operations.projectDataRowUsageIntervalMs",value:60000}]}. The same PATCH shape changes chat.messageMergingEnabled between false/true. Fetch a fresh revision each mutation; restore original values afterward through API/UI. NO Cloudflare Worker settings PATCH. +5. RowUsage emits at an operation boundary after interval elapsed, not on a timer. Existing DOs refresh interval after a flush, so do not assume setting change instantly affects a previously active object. Prefer a fresh test project after setting changes and trigger an ordinary session-list read after each interval to cause flush. Exclude a boundary-straddling window. Missing logs or missing messageIngest is a coverage gap, never zero merges. The helper excludes straddlers and reports union coveredMs. AlarmWrites is a subset of rowsWritten, never add it twice. + +Expected emitted event and numeric schema: + + event: "project_data.row_usage" + projectId: owned test project ID (existing top-level attribution) + windowStart, windowEnd: epoch milliseconds + labels: {rank0:{label:"persistMessageBatch",calls,rowsRead,rowsWritten,alarmWrites}, ...} + droppedLabelCount, totalLabelCount: integers + messageIngest: { + batches: integer, + received: {user,assistant,thinking,tool,plan,system,other}, + accepted: {user,assistant,thinking,tool,plan,system,other}, + inserted: {user,assistant,thinking,tool,plan,system,other}, + eligible: integer, + coalesced: integer, + appendStatements: integer, + duplicates: integer, + mergeReadyBatches: integer, + refused: {setting_disabled?,legacy_client?,missing_incarnation?,invalid_sequence?,retired_source?,receipt_cap?}, + breaks: {no_open?,source?,turn?,intervening_writer?,materialized?,role?,metadata?,origin?,sequence_gap?,timestamp?,out_of_order?,size_cap?}, + legacyProjectSocketsMax: integer, + legacySessionSocketsMax: integer + } + +Every role key exists; sparse refused/break keys absent means0. Unknown roles count as other. Received includes retries; accepted excludes duplicates; inserted is physical canonical inserts. Eligible counts accepted assistant/null-metadata chunks even OFF. Coalesced is logical chunk merges, including within a batch; appendStatements counts actual UPDATE statements only, so these differ. Refused is one primary reason per batch (setting_disabled takes precedence over legacy_client). Socket counts are MAXIMA sampled per batch, not window sums. Counters publish only after synchronous persistence commits; rollback contributes none; postcommit broadcast failure retains counts. Instance eviction loses unflushed diagnostics. Existing label cap can drop persist label even while messageIngest exists; require persistLabelPresent=true for writes/call comparisons. + +Live expected checks on exact counter source candidate: + +- OFF: accepted assistant eligibility still visible; refused.setting_disabled >0; coalesced=0 and appendStatements=0. +- ON with merge-capable reporter/incarnation, sequential assistant chunks and no legacy relevant socket: mergeReadyBatches>0, coalesced>0; cross-batch continuation normally yields appendStatements>0. inserted.assistant below accepted.assistant establishes fewer physical assistant rows. Other run boundaries/metadata may legitimately prevent a particular chunk from merging; inspect reason counts instead of assuming. +- Thinking/tool-heavy real Claude turn: received/accepted/inserted role mix makes density visible. Thinking/tool rows remain unmerged in this PR. Typed cards and transcript content must remain intact; watch incremental app reply, reload and compare content hash. Never paste text into evidence. +- ON with actual unscoped legacy socket (after #2774): legacyProjectSocketsMax>=1, no refusal, merging continues. ON with a session-scoped legacy socket: legacySessionSocketsMax>=1, refused.legacy_client>0, coalesced=0 for that session's batches. After closing socket, subsequent clean phases should merge eligible assistant runs. Mixed normal traffic in the same window makes simple zero assertions invalid; isolate phases. +- A legacy session socket only affects that session; unrelated session socket not counted as relevant. PR2774 changes unscoped semantics, so its expected result differs: unscoped must not block merging or receive transcript frames. Do not mix these two expected behaviors. + +Exact legacy/capable browser WebSocket reproduction (authenticated staging2 Playwright page/context, cookie .sammy2.party): + + await page.evaluate(async ({projectId,sessionId,scoped,capable}) => { + const u = new URL("wss://api.sammy2.party/api/projects/" + projectId + "/sessions/ws"); + if (scoped) u.searchParams.set("sessionId",sessionId); + if (capable) u.searchParams.set("messageAppend","message-append-v1"); + const ws = new WebSocket(u.href); + window.__mergeProbe = ws; + window.__mergeProbeTypes = {}; + ws.onmessage = event => { + try { + const type = JSON.parse(event.data).type; + if (typeof type === "string") window.__mergeProbeTypes[type] = (window.__mergeProbeTypes[type] || 0) + 1; + } catch {} + }; + await new Promise((resolve,reject) => { + ws.onopen=resolve; + ws.onerror=() => reject(new Error("Probe websocket failed")); + }); + return {readyState:ws.readyState}; + }, {projectId:"",sessionId:"",scoped:false,capable:false}); + +Use scoped:false,capable:false for the old project client; scoped:true,capable:false for an old session client; scoped:true,capable:true for a compatible session reader. Query parameter absence is what makes it legacy: do NOT send messageAppend on the legacy probe. Normal browser cookies authenticate the upgrade; never put tokens in the URL. Keep the socket open DURING real agent ingestion. Record only readyState and event-type counts, never frames/content. Close and delete probe state in finally: + + await page.evaluate(() => { + window.__mergeProbe?.close(1000); + delete window.__mergeProbe; + delete window.__mergeProbeTypes; + }); + +The real workerd regression file apps/api/tests/workers/project-data-message-ingest-metrics.test.ts drives the same actual socket admission via stub.fetch Upgrade. It is a reference for expected counter outcomes, not a substitute for leased staging proof. + +Cleanup and release remain holder-owned: restore staging settings, close probes/browser auth, delete EVERY owned workspace/node/project, verify provider absence, then release lease through deploy-staging and confirm released payload. No old PR2760 auth/helper authority may be reused. This Codex task has no resources/auth/settings/lease to clean. + +Library01M7GXXV4YN93Z9J13S3TARGFA is replaced with the complete original handoff plus this addendum. PR body and task document carry the same transfer instructions. The counter helper is separately durable in Library01M7H0F82Y6T0XASP58Z1T46ZZ. Coordinator/Claude task owns all remaining release actions; previous Codex queue timer will be cancelled so it cannot accidentally resume deployment. + +## Staging2 result (2026-11-16, carried by task 01M7GY0BKP1WESE5Y82PZNN42S) + +Head `38b5668b2` (main with #2774 merged), deploy run 43823832576. One Instant Claude Code session, tool-heavy turns, row-usage interval 60 s, 10 complete windows (numeric results: library 01M7HR29FT8PMZBTHZGD53DE94). + +- ON + legacy project socket: 31 batches, received assistant 106 / tool 13 / user 1; inserted assistant 1 / tool 13; coalesced 105, append statements 21; no refusal; legacyProjectSocketsMax 1; 8.84 writes/call, 36 reads/call. +- ON + legacy session socket: 28 batches; inserted assistant 110 / tool 11; refused legacy_client 28; legacySessionSocketsMax 1; 19.75 writes/call, 84 reads/call. +- OFF: 21 batches; inserted assistant 115 / tool 11; refused setting_disabled 21; 24.71 writes/call, 212 reads/call. +- No thinking chunks were emitted by this staging session, so thinking density was not measured. +- Cleanup: settings reset to default, session stopped, project deleted, signed out.