Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

⚡️ perf(hetero): stop re-reading the trace partial on every ingest batch (#19736)

Arvin Xu4fb3e25a0246
diff --git a/apps/server/src/modules/AgentTracing/S3SnapshotStore.test.ts b/apps/server/src/modules/AgentTracing/S3SnapshotStore.test.ts
index 9c09d3f0672..35b97eb5e6b 100644
--- a/apps/server/src/modules/AgentTracing/S3SnapshotStore.test.ts
+++ b/apps/server/src/modules/AgentTracing/S3SnapshotStore.test.ts
@@ -111,6 +111,39 @@ describe('S3SnapshotStore.savePartial', () => {
const roundtripped = JSON.parse((await decompressZstd(body)).toString('utf8'));
expect(roundtripped).toEqual(partial);
});
+
+ it('returns the stored token and fences the next write on it', async () => {
+ uploadBuffer.mockResolvedValueOnce({ ETag: '"abc"' });
+ const store = new S3SnapshotStore();
+
+ const result = await store.savePartial('op_partial_2', {} as Partial<ExecutionSnapshot>);
+ expect(result).toEqual({ token: '"abc"' });
+
+ await store.savePartial('op_partial_2', {} as Partial<ExecutionSnapshot>, {
+ expected: '"abc"',
+ });
+ expect(uploadBuffer.mock.calls[1][4]).toMatchObject({ ifMatch: '"abc"' });
+ });
+
+ it('reports a refused conditional write instead of throwing', async () => {
+ uploadBuffer.mockRejectedValueOnce(
+ Object.assign(new Error('precondition failed'), { $metadata: { httpStatusCode: 412 } }),
+ );
+ const store = new S3SnapshotStore();
+
+ await expect(
+ store.savePartial('op_partial_3', {} as Partial<ExecutionSnapshot>, { expected: '"old"' }),
+ ).resolves.toEqual({ conflict: true });
+ });
+
+ it('still throws when the write fails for another reason', async () => {
+ uploadBuffer.mockRejectedValueOnce(new Error('network down'));
+ const store = new S3SnapshotStore();
+
+ await expect(
+ store.savePartial('op_partial_4', {} as Partial<ExecutionSnapshot>, { expected: '"old"' }),
+ ).rejects.toThrow('network down');
+ });
});
describe('S3SnapshotStore.loadPartial', () => {
diff --git a/apps/server/src/modules/AgentTracing/S3SnapshotStore.ts b/apps/server/src/modules/AgentTracing/S3SnapshotStore.ts
index a0d0d013b42..f17209daed2 100644
--- a/apps/server/src/modules/AgentTracing/S3SnapshotStore.ts
+++ b/apps/server/src/modules/AgentTracing/S3SnapshotStore.ts
@@ -5,6 +5,8 @@ import {
type ExecutionSnapshot,
type ISnapshotStore,
parseOperationId,
+ type PartialSaveOptions,
+ type PartialSaveResult,
type SnapshotSummary,
} from '@lobechat/agent-tracing';
import debug from 'debug';
@@ -16,6 +18,12 @@ const decompressZstd = promisify(zstdDecompress);
const log = debug('lobe-server:agent-tracing:s3');
+/** A conditional write the store refused because the object changed underneath. */
+const isPreconditionFailed = (error: unknown): boolean => {
+ const status = (error as { $metadata?: { httpStatusCode?: number } })?.$metadata?.httpStatusCode;
+ return status === 412 || (error as { name?: string })?.name === 'PreconditionFailed';
+};
+
const TRACE_PREFIX = 'agent-traces';
const SNAPSHOT_SUFFIX = '.json.zst';
const LEGACY_SUFFIX = '.json';
@@ -132,16 +140,24 @@ export class S3SnapshotStore implements ISnapshotStore {
async savePartial(
operationId: string,
partial: Partial<ExecutionSnapshot>,
- options?: { signal?: AbortSignal },
- ): Promise<void> {
+ options?: PartialSaveOptions,
+ ): Promise<PartialSaveResult> {
const compressed = await this.encodeSnapshot(partial);
- await this.s3.uploadBuffer(
- this.partialKey(operationId),
- compressed,
- ZSTD_CONTENT_TYPE,
- undefined,
- { abortSignal: options?.signal },
- );
+ try {
+ const result = await this.s3.uploadBuffer(
+ this.partialKey(operationId),
+ compressed,
+ ZSTD_CONTENT_TYPE,
+ undefined,
+ { abortSignal: options?.signal, ifMatch: options?.expected },
+ );
+ return { token: result?.ETag };
+ } catch (error) {
+ // A refused conditional write is an answer, not a failure: the caller's
+ // cached copy is behind and it has to re-read before writing again.
+ if (options?.expected && isPreconditionFailed(error)) return { conflict: true };
+ throw error;
+ }
}
async removePartial(operationId: string): Promise<void> {
diff --git a/apps/server/src/modules/S3/index.ts b/apps/server/src/modules/S3/index.ts
index e49be379826..2827db091ce 100644
--- a/apps/server/src/modules/S3/index.ts
+++ b/apps/server/src/modules/S3/index.ts
@@ -337,8 +337,13 @@ export class S3 {
buffer: Buffer,
contentType?: string,
cacheControl?: string,
- /** `abortSignal` cancels an upload whose result the caller no longer wants written. */
- options?: { abortSignal?: AbortSignal },
+ /**
+ * `abortSignal` cancels an upload whose result the caller no longer wants
+ * written. `ifMatch` makes the write conditional on the stored object still
+ * having that ETag, so a caller holding a cached copy cannot overwrite a
+ * newer one; the store answers 412 instead.
+ */
+ options?: { abortSignal?: AbortSignal; ifMatch?: string },
) {
const command = new PutObjectCommand({
ACL: this.setAcl ? 'public-read' : undefined,
@@ -346,6 +351,7 @@ export class S3 {
Bucket: this.bucket,
CacheControl: cacheControl,
ContentType: contentType,
+ IfMatch: options?.ifMatch,
Key: path,
});
diff --git a/apps/server/src/services/heterogeneousAgent/HeteroTraceRecorder.ts b/apps/server/src/services/heterogeneousAgent/HeteroTraceRecorder.ts
index 4af924c8ce5..8e918314b34 100644
--- a/apps/server/src/services/heterogeneousAgent/HeteroTraceRecorder.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeteroTraceRecorder.ts
@@ -60,6 +60,39 @@ const str = (v: unknown): string | undefined => (typeof v === 'string' ? v : und
* and finalizing into the same `ExecutionSnapshot` S3 layout the built-in path
* uses. Context-engine fields are intentionally never set (hetero has no CE).
*/
+/**
+ * The partial each warm instance last wrote, with the token that write returned.
+ * Ingest batches arrive as separate requests, so this has to outlive the service
+ * instance to be worth anything — without it every batch re-reads the whole
+ * partial from the store before it can append to it (~350ms of the ~1s the
+ * device waits for its ack).
+ *
+ * Keeping a copy is only safe because the write that follows is fenced on the
+ * token: a batch routed to another instance writes a newer object, and this
+ * instance's next write is refused instead of rolling that one back.
+ */
+const partialCache = new Map<string, { partial: Partial<ExecutionSnapshot>; token: string }>();
+
+/** Bounded so a long-lived instance cannot accumulate finished operations. */
+const PARTIAL_CACHE_MAX = 32;
+
+const rememberPartial = (
+ operationId: string,
+ partial: Partial<ExecutionSnapshot>,
+ token?: string,
+) => {
+ // Without a token the next write could not be fenced, so there is nothing
+ // safe to remember.
+ if (!token) return partialCache.delete(operationId);
+
+ partialCache.delete(operationId);
+ partialCache.set(operationId, { partial, token });
+ if (partialCache.size > PARTIAL_CACHE_MAX) {
+ const oldest = partialCache.keys().next().value;
+ if (oldest !== undefined) partialCache.delete(oldest);
+ }
+};
+
export class HeteroTraceRecorder {
constructor(private readonly store: ISnapshotStore | null) {}
@@ -73,17 +106,35 @@ export class HeteroTraceRecorder {
if (!this.store || events.length === 0) return;
try {
- const partial = (await this.store.loadPartial(operationId)) ?? {};
- if (!partial.steps) partial.steps = [];
- if (!partial.startedAt) partial.startedAt = events[0].timestamp;
+ const cached = partialCache.get(operationId);
+ const fold = (partial: Partial<ExecutionSnapshot>) => {
+ if (!partial.steps) partial.steps = [];
+ if (!partial.startedAt) partial.startedAt = events[0].timestamp;
- const byIndex = new Map<number, StepSnapshot>();
- for (const s of partial.steps) byIndex.set(s.stepIndex, s);
+ const byIndex = new Map<number, StepSnapshot>();
+ for (const s of partial.steps) byIndex.set(s.stepIndex, s);
+ for (const event of events) this.applyEvent(partial, byIndex, event);
+ return partial;
+ };
- for (const event of events) this.applyEvent(partial, byIndex, event);
+ const partial = fold(cached?.partial ?? (await this.store.loadPartial(operationId)) ?? {});
+ const result = await this.store.savePartial(operationId, partial, {
+ expected: cached?.token,
+ });
+
+ if (result?.conflict) {
+ // Another instance wrote this partial while we held a copy. Drop ours,
+ // read theirs, and fold this batch's events into it instead.
+ partialCache.delete(operationId);
+ const fresh = fold((await this.store.loadPartial(operationId)) ?? {});
+ const retry = await this.store.savePartial(operationId, fresh);
+ rememberPartial(operationId, fresh, retry?.token);
+ return;
+ }
- await this.store.savePartial(operationId, partial);
+ rememberPartial(operationId, partial, result?.token);
} catch (e) {
+ partialCache.delete(operationId);
log('[%s] appendBatch failed (non-fatal): %O', operationId, e);
}
}
@@ -97,6 +148,13 @@ export class HeteroTraceRecorder {
if (!this.store) return null;
try {
+ // Always read the authoritative partial here, even with a copy in hand.
+ // `heteroFinish` is its own request and can land on an instance whose
+ // copy stopped at an earlier batch; finalizing from that would publish a
+ // snapshot missing every batch another instance recorded, and then delete
+ // the partial that had them. The per-batch write is fenced against that;
+ // this one write is not, so it does not get to guess.
+ partialCache.delete(operationId);
const partial = await this.store.loadPartial(operationId);
if (!partial) return null;
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeteroTraceRecorder.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeteroTraceRecorder.test.ts
index 806037714f7..fb2b9e2ba09 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeteroTraceRecorder.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeteroTraceRecorder.test.ts
@@ -1,5 +1,10 @@
import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
-import type { ExecutionSnapshot, ISnapshotStore } from '@lobechat/agent-tracing';
+import type {
+ ExecutionSnapshot,
+ ISnapshotStore,
+ PartialSaveOptions,
+ PartialSaveResult,
+} from '@lobechat/agent-tracing';
import { beforeEach, describe, expect, it } from 'vitest';
import { HeteroTraceRecorder } from '../HeteroTraceRecorder';
@@ -15,7 +20,11 @@ class FakeSnapshotStore implements ISnapshotStore {
// accidentally short-circuit the persist round-trip we want to exercise.
return p ? (JSON.parse(JSON.stringify(p)) as Partial<ExecutionSnapshot>) : null;
}
- async savePartial(operationId: string, partial: Partial<ExecutionSnapshot>) {
+ async savePartial(
+ operationId: string,
+ partial: Partial<ExecutionSnapshot>,
+ _options?: PartialSaveOptions,
+ ): Promise<PartialSaveResult | void> {
this.partials.set(operationId, partial);
}
async removePartial(operationId: string) {
@@ -38,6 +47,42 @@ class FakeSnapshotStore implements ISnapshotStore {
}
}
+/**
+ * Mirrors the S3 store: every write returns a token and a write that names a
+ * stale one is refused. Only such a store lets the recorder keep a copy.
+ */
+class FencingSnapshotStore extends FakeSnapshotStore {
+ tokens = new Map<string, string>();
+ reads = 0;
+ writes = 0;
+
+ async loadPartial(operationId: string) {
+ this.reads += 1;
+ return super.loadPartial(operationId);
+ }
+
+ async savePartial(
+ operationId: string,
+ partial: Partial<ExecutionSnapshot>,
+ options?: PartialSaveOptions,
+ ): Promise<PartialSaveResult> {
+ this.writes += 1;
+ const current = this.tokens.get(operationId);
+ if (options?.expected && options.expected !== current) return { conflict: true };
+
+ await super.savePartial(operationId, partial);
+ const token = `t${this.writes}`;
+ this.tokens.set(operationId, token);
+ return { token };
+ }
+
+ /** Another instance writing the same partial. */
+ writeElsewhere(operationId: string, partial: Partial<ExecutionSnapshot>) {
+ this.partials.set(operationId, partial);
+ this.tokens.set(operationId, `other-${this.writes}`);
+ }
+}
+
const ev = (
type: AgentStreamEvent['type'],
stepIndex: number,
@@ -165,6 +210,78 @@ describe('HeteroTraceRecorder', () => {
expect(store.partials.has('op-1')).toBe(false);
});
+ describe('cross-request partial reuse', () => {
+ const chunk = (op: string, step: number, ts: number, text: string): AgentStreamEvent => ({
+ data: { chunkType: 'text', content: text },
+ operationId: op,
+ stepIndex: step,
+ timestamp: ts,
+ type: 'stream_chunk',
+ });
+
+ it('reads the partial once and appends later batches from the copy it kept', async () => {
+ const fencing = new FencingSnapshotStore();
+ const rec = new HeteroTraceRecorder(fencing);
+
+ await rec.appendBatch('op-reuse', [chunk('op-reuse', 0, 100, 'a')]);
+ await rec.appendBatch('op-reuse', [chunk('op-reuse', 0, 110, 'b')]);
+ await rec.appendBatch('op-reuse', [chunk('op-reuse', 0, 120, 'c')]);
+
+ // One read for the first batch; the rest append to the copy in memory.
+ expect(fencing.reads).toBe(1);
+ expect(fencing.writes).toBe(3);
+ expect(fencing.partials.get('op-reuse')?.steps?.[0].content).toBe('abc');
+ });
+
+ it('re-reads and folds into the newer copy when another instance wrote meanwhile', async () => {
+ const fencing = new FencingSnapshotStore();
+ const rec = new HeteroTraceRecorder(fencing);
+
+ await rec.appendBatch('op-conflict', [chunk('op-conflict', 0, 100, 'a')]);
+
+ // A batch of the same run handled elsewhere lands first.
+ fencing.writeElsewhere('op-conflict', {
+ startedAt: 100,
+ steps: [{ content: 'aZ', startedAt: 100, stepIndex: 0 } as never],
+ });
+
+ await rec.appendBatch('op-conflict', [chunk('op-conflict', 0, 120, 'c')]);
+
+ // Our stale copy was refused, so the other instance's 'Z' survives.
+ expect(fencing.partials.get('op-conflict')?.steps?.[0].content).toBe('aZc');
+ });
+
+ it('finalizes from the stored partial, not from the copy it happens to hold', async () => {
+ const fencing = new FencingSnapshotStore();
+ const rec = new HeteroTraceRecorder(fencing);
+
+ await rec.appendBatch('op-final', [chunk('op-final', 0, 100, 'a')]);
+
+ // `heteroFinish` can land here while later batches were recorded
+ // elsewhere. Finalizing from the copy would drop them and then delete the
+ // partial that had them.
+ fencing.writeElsewhere('op-final', {
+ startedAt: 100,
+ steps: [{ content: 'a-then-elsewhere', startedAt: 100, stepIndex: 0 } as never],
+ });
+
+ await rec.finalize('op-final', { completionReason: 'done' });
+
+ expect(fencing.saved.get('op-final')?.steps[0].content).toBe('a-then-elsewhere');
+ });
+
+ it('keeps re-reading for a store that cannot fence a write', async () => {
+ await recorder.appendBatch('op-plain', [
+ ev('stream_chunk', 0, 100, { chunkType: 'text', content: 'a' }),
+ ]);
+ await recorder.appendBatch('op-plain', [
+ ev('stream_chunk', 0, 110, { chunkType: 'text', content: 'b' }),
+ ]);
+
+ expect(store.partials.get('op-plain')?.steps?.[0].content).toBe('ab');
+ });
+ });
+
it('returns null from finalize when no partial was accumulated', async () => {
expect(await recorder.finalize('never-seen', { completionReason: 'done' })).toBeNull();
});
diff --git a/packages/agent-tracing/src/index.ts b/packages/agent-tracing/src/index.ts
index 9143bdb5b31..98adb833f1a 100644
--- a/packages/agent-tracing/src/index.ts
+++ b/packages/agent-tracing/src/index.ts
@@ -30,7 +30,7 @@ export {
parseOperationId,
RemoteSnapshotStore,
} from './store/remote-store';
-export type { ISnapshotStore } from './store/types';
+export type { ISnapshotStore, PartialSaveOptions, PartialSaveResult } from './store/types';
export type { ExecutionSnapshot, SnapshotSummary, StepSnapshot } from './types';
export {
expandSnapshot,
diff --git a/packages/agent-tracing/src/store/types.ts b/packages/agent-tracing/src/store/types.ts
index f7bb9aeba33..448c927203e 100644
--- a/packages/agent-tracing/src/store/types.ts
+++ b/packages/agent-tracing/src/store/types.ts
@@ -1,5 +1,24 @@
import type { ExecutionSnapshot, SnapshotSummary } from '../types';
+export interface PartialSaveOptions {
+ /**
+ * Write only while the stored object still carries this token, which came
+ * from an earlier read or write of the same partial. A store that can fence
+ * answers `{ conflict: true }` instead of overwriting a newer copy; one that
+ * cannot ignores it.
+ */
+ expected?: string;
+ /** Cancels an upload whose result the caller no longer wants written. */
+ signal?: AbortSignal;
+}
+
+export interface PartialSaveResult {
+ /** The write was refused: someone else has written this partial since. */
+ conflict?: boolean;
+ /** Identifies what is stored now, to fence the caller's next write. */
+ token?: string;
+}
+
export interface ISnapshotStore {
get: (traceId: string) => Promise<ExecutionSnapshot | null>;
getLatest: () => Promise<ExecutionSnapshot | null>;
@@ -20,6 +39,6 @@ export interface ISnapshotStore {
savePartial: (
operationId: string,
partial: Partial<ExecutionSnapshot>,
- options?: { signal?: AbortSignal },
- ) => Promise<void>;
+ options?: PartialSaveOptions,
+ ) => Promise<PartialSaveResult | void>;
}