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(agent): keep the trace partial in memory and upload it off the step path (#19716)

Arvin Xu7895ce032869
diff --git a/apps/server/src/modules/AgentTracing/S3SnapshotStore.ts b/apps/server/src/modules/AgentTracing/S3SnapshotStore.ts
index 38b1b8d239a..a0d0d013b42 100644
--- a/apps/server/src/modules/AgentTracing/S3SnapshotStore.ts
+++ b/apps/server/src/modules/AgentTracing/S3SnapshotStore.ts
@@ -129,9 +129,19 @@ export class S3SnapshotStore implements ISnapshotStore {
}
}
- async savePartial(operationId: string, partial: Partial<ExecutionSnapshot>): Promise<void> {
+ async savePartial(
+ operationId: string,
+ partial: Partial<ExecutionSnapshot>,
+ options?: { signal?: AbortSignal },
+ ): Promise<void> {
const compressed = await this.encodeSnapshot(partial);
- await this.s3.uploadBuffer(this.partialKey(operationId), compressed, ZSTD_CONTENT_TYPE);
+ await this.s3.uploadBuffer(
+ this.partialKey(operationId),
+ compressed,
+ ZSTD_CONTENT_TYPE,
+ undefined,
+ { abortSignal: options?.signal },
+ );
}
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 bdbe7fd1938..e49be379826 100644
--- a/apps/server/src/modules/S3/index.ts
+++ b/apps/server/src/modules/S3/index.ts
@@ -337,6 +337,8 @@ export class S3 {
buffer: Buffer,
contentType?: string,
cacheControl?: string,
+ /** `abortSignal` cancels an upload whose result the caller no longer wants written. */
+ options?: { abortSignal?: AbortSignal },
) {
const command = new PutObjectCommand({
ACL: this.setAcl ? 'public-read' : undefined,
@@ -347,7 +349,7 @@ export class S3 {
Key: path,
});
- return this.client.send(command);
+ return this.client.send(command, { abortSignal: options?.abortSignal });
}
public async uploadContent(path: string, content: string) {
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index 9008983dbeb..beaa6be44b8 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -1489,6 +1489,11 @@ export class AgentRuntimeService {
stepLockOwner,
);
if (!claimed) {
+ // Someone else owns this operation now. Whatever this invocation buffered
+ // for the trace belongs to their partial from here β€” every return below
+ // leaves without it, so drop it once, up front, rather than per exit.
+ this.traceRecorder.discardPartial();
+
let currentState: AgentState | null | undefined = null;
try {
currentState = await this.coordinator.loadAgentState(operationId);
@@ -1648,6 +1653,11 @@ export class AgentRuntimeService {
// success path.
const stepStartAt = Date.now();
+ // Hoisted so the shared `finally` knows whether the next step stays in this
+ // invocation. When it does, the accumulated trace partial stays in memory;
+ // on every other exit some other process reads it, so it has to be durable.
+ let handedOffInline = false;
+
// OTel invoke_agent span. Wraps the entire step body so child spans
// (chat / execute_tool / context_engineering) auto-nest via the active
// context. Started with minimal attrs; agent/model/topic are added once
@@ -2415,6 +2425,7 @@ export class AgentRuntimeService {
}
if (parked) {
+ handedOffInline = true;
// Hand the next step back to the caller instead of paying a full
// queue round-trip for it. The caller either runs it in this same
// invocation or publishes it via `scheduleContinuation` when its
@@ -2425,6 +2436,9 @@ export class AgentRuntimeService {
}));
log('[%s][%d] Next step %d deferred to caller', operationId, stepIndex, nextStepIndex);
} else {
+ // The next step runs in another invocation, which rebuilds the
+ // partial from the store β€” it has to see this step.
+ await this.traceRecorder.flushPartial();
await this.queueService.scheduleMessage({ ...next, endpoint: `${this.baseURL}/run` });
nextStepScheduled = true;
logToolCallPc(operationId, stepIndex, 'post.next_step_scheduled', () => ({
@@ -2663,6 +2677,10 @@ export class AgentRuntimeService {
stepAbortPollStopped = true;
if (stepAbortPoll) clearTimeout(stepAbortPoll);
stopStepLockHeartbeat();
+ // Parked runs (human input, async tools) and finished ones are read back
+ // by a different invocation, so the partial cannot stay in memory only.
+ // An inline hand-off keeps it: the next step runs on this recorder.
+ if (!handedOffInline) await this.traceRecorder.flushPartial();
// The inline step loop keeps the lock across step boundaries β€” releasing
// here would open a window for a stale redelivery to claim it mid-run.
// Its caller releases once, in a `finally`, for the whole invocation.
@@ -2684,6 +2702,10 @@ export class AgentRuntimeService {
);
}
+ // The steps this invocation inlined are still only in memory β€” the
+ // invocation that picks the run up reads the partial from the store.
+ await this.traceRecorder.flushPartial();
+
await this.queueService.scheduleMessage({
...continuation,
endpoint: `${this.baseURL}/run`,
diff --git a/apps/server/src/services/agentRuntime/OperationTraceRecorder.test.ts b/apps/server/src/services/agentRuntime/OperationTraceRecorder.test.ts
new file mode 100644
index 00000000000..bca66f3b9ec
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/OperationTraceRecorder.test.ts
@@ -0,0 +1,154 @@
+import type { ExecutionSnapshot, ISnapshotStore } from '@lobechat/agent-tracing';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { type AppendStepParams, OperationTraceRecorder } from './OperationTraceRecorder';
+
+const OPERATION_ID = 'op_1';
+
+const deferred = () => {
+ let resolve!: () => void;
+ const promise = new Promise<void>((r) => {
+ resolve = r;
+ });
+ return { promise, resolve };
+};
+
+const stepParams = (stepIndex: number): AppendStepParams => ({
+ afterStepSignalEvents: [],
+ agentState: { messages: [] },
+ beforeStepSignalEvents: [],
+ externalRetryCount: 0,
+ presentation: { executionTimeMs: 1, stepType: 'call_llm', thinking: false } as any,
+ startedAt: 0,
+ stepIndex,
+ stepResult: { events: [], newState: { messages: [] } },
+});
+
+const createStore = () => {
+ const store = {
+ loadPartial: vi.fn<(operationId: string) => Promise<Partial<ExecutionSnapshot> | null>>(
+ async () => null,
+ ),
+ removePartial: vi.fn<(operationId: string) => Promise<void>>(async () => {}),
+ save: vi.fn<(snapshot: ExecutionSnapshot) => Promise<void>>(async () => {}),
+ savePartial: vi.fn<
+ (
+ operationId: string,
+ partial: Partial<ExecutionSnapshot>,
+ options?: { signal?: AbortSignal },
+ ) => Promise<void>
+ >(async () => {}),
+ };
+ return store as typeof store & ISnapshotStore;
+};
+
+describe('OperationTraceRecorder partial accumulation', () => {
+ let store: ReturnType<typeof createStore>;
+ let recorder: OperationTraceRecorder;
+
+ beforeEach(() => {
+ store = createStore();
+ recorder = new OperationTraceRecorder(store);
+ });
+
+ it('reads the stored partial once for a run of steps', async () => {
+ await recorder.appendStep(OPERATION_ID, stepParams(0));
+ await recorder.appendStep(OPERATION_ID, stepParams(1));
+ await recorder.appendStep(OPERATION_ID, stepParams(2));
+ await recorder.flushPartial();
+
+ expect(store.loadPartial).toHaveBeenCalledTimes(1);
+ expect(store.savePartial.mock.calls.at(-1)?.[1].steps).toHaveLength(3);
+ });
+
+ it('returns from the step without waiting for the upload', async () => {
+ const upload = deferred();
+ let uploaded = false;
+ store.savePartial.mockImplementation(async () => {
+ await upload.promise;
+ uploaded = true;
+ });
+
+ await recorder.appendStep(OPERATION_ID, stepParams(0));
+ expect(uploaded).toBe(false);
+
+ upload.resolve();
+ await recorder.flushPartial();
+ expect(uploaded).toBe(true);
+ });
+
+ it('collapses steps appended during an upload into a single follow-up upload', async () => {
+ const first = deferred();
+ store.savePartial.mockImplementationOnce(async () => {
+ await first.promise;
+ });
+
+ await recorder.appendStep(OPERATION_ID, stepParams(0));
+ await recorder.appendStep(OPERATION_ID, stepParams(1));
+ await recorder.appendStep(OPERATION_ID, stepParams(2));
+
+ first.resolve();
+ await recorder.flushPartial();
+
+ // One upload for step 0, one for the three that landed while it ran.
+ expect(store.savePartial).toHaveBeenCalledTimes(2);
+ expect(store.savePartial.mock.calls.at(-1)?.[1].steps).toHaveLength(3);
+ });
+
+ it('finalizes from memory and deletes the partial after the final snapshot', async () => {
+ await recorder.appendStep(OPERATION_ID, stepParams(0));
+ await recorder.finalize(OPERATION_ID, { completionReason: 'done', state: {} });
+
+ expect(store.loadPartial).toHaveBeenCalledTimes(1);
+ expect(store.save).toHaveBeenCalledTimes(1);
+ expect(store.save.mock.calls[0][0].steps).toHaveLength(1);
+ expect(store.removePartial).toHaveBeenCalledTimes(1);
+ expect(store.save.mock.invocationCallOrder[0]).toBeLessThan(
+ store.removePartial.mock.invocationCallOrder[0],
+ );
+ });
+
+ it('does not upload steps after the operation lock is lost', async () => {
+ const first = deferred();
+ store.savePartial.mockImplementationOnce(async () => {
+ await first.promise;
+ });
+
+ await recorder.appendStep(OPERATION_ID, stepParams(0));
+ await recorder.appendStep(OPERATION_ID, stepParams(1));
+ recorder.discardPartial();
+
+ first.resolve();
+ await recorder.flushPartial();
+
+ expect(store.savePartial).toHaveBeenCalledTimes(1);
+ });
+
+ it('aborts the upload in flight when the operation is handed over', async () => {
+ const upload = deferred();
+ let seenSignal: AbortSignal | undefined;
+ store.savePartial.mockImplementation(async (_id, _partial, options) => {
+ seenSignal = options?.signal;
+ await upload.promise;
+ });
+
+ await recorder.appendStep(OPERATION_ID, stepParams(0));
+ expect(seenSignal?.aborted).toBe(false);
+
+ recorder.discardPartial();
+
+ // The upload already on the wire is cancelled, so it cannot land on top of
+ // the partial the new owner is writing.
+ expect(seenSignal?.aborted).toBe(true);
+
+ upload.resolve();
+ await recorder.flushPartial();
+ expect(store.savePartial).toHaveBeenCalledTimes(1);
+ });
+
+ it('is a no-op without a store', async () => {
+ const disabled = new OperationTraceRecorder(null);
+ await disabled.appendStep(OPERATION_ID, stepParams(0));
+ await expect(disabled.flushPartial()).resolves.toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/OperationTraceRecorder.ts b/apps/server/src/services/agentRuntime/OperationTraceRecorder.ts
index d75c3a7ab7b..0b1509dbfb1 100644
--- a/apps/server/src/services/agentRuntime/OperationTraceRecorder.ts
+++ b/apps/server/src/services/agentRuntime/OperationTraceRecorder.ts
@@ -1,4 +1,4 @@
-import type { ISnapshotStore, StepSnapshot } from '@lobechat/agent-tracing';
+import type { ExecutionSnapshot, ISnapshotStore, StepSnapshot } from '@lobechat/agent-tracing';
import type { ChatMessageErrorAttribution, ChatMessageErrorSeverity } from '@lobechat/types';
import debug from 'debug';
@@ -88,6 +88,23 @@ export interface FinalizeParams {
* methods are no-ops.
*/
export class OperationTraceRecorder {
+ /**
+ * The partial this invocation is accumulating, kept in memory so a step
+ * boundary no longer pays a full read-modify-write of the whole trace.
+ * Measured in production (Tempo, 75 steps): ~570ms GET + ~960ms PUT per step,
+ * on the critical path between two steps of an inlined run.
+ */
+ private cached: { operationId: string; partial: Partial<ExecutionSnapshot> } | null = null;
+
+ /** In-flight upload, if any. Never rejects β€” `drainSaves` logs and continues. */
+ private pendingSave: Promise<void> | undefined;
+
+ /** Set when the cached partial has steps the store has not seen yet. */
+ private dirty = false;
+
+ /** Aborts the upload in flight when this invocation stops owning the operation. */
+ private saveAbort: AbortController | undefined;
+
constructor(private readonly store: ISnapshotStore | null) {}
get enabled(): boolean {
@@ -98,7 +115,7 @@ export class OperationTraceRecorder {
if (!this.store) return;
try {
- const partial = (await this.store.loadPartial(operationId)) ?? { steps: [] };
+ const partial = await this.loadCachedPartial(operationId);
this.initPartialHeader(partial, params.agentState);
@@ -107,17 +124,103 @@ export class OperationTraceRecorder {
this.deduplicateCeSnapshot(newStep, partial.steps);
partial.steps.push(newStep);
- await this.store.savePartial(operationId, partial);
+ // Upload in the background: the next step only needs the in-memory copy,
+ // and the upload overlaps with it instead of delaying it. Anything that
+ // reads the partial from another process waits via `flushPartial`.
+ this.scheduleSave(operationId);
} catch (e) {
log('[%s] snapshot step recording failed: %O', operationId, e);
}
}
+ /**
+ * Wait for the accumulated partial to become durable. Required before any
+ * other process reads it: a queue hand-off, a parked operation, or
+ * finalization.
+ */
+ async flushPartial(): Promise<void> {
+ if (!this.store) return;
+
+ if (this.dirty && this.cached) this.scheduleSave(this.cached.operationId);
+ await this.pendingSave;
+ }
+
+ /**
+ * Drop the in-memory partial without uploading it. Used when this invocation
+ * loses the operation lock: the worker that took over owns the partial now,
+ * and writing ours over it would roll back the steps it recorded.
+ */
+ discardPartial(): void {
+ this.dirty = false;
+ this.cached = null;
+ // An upload already in flight was started while this invocation still owned
+ // the operation, and carries a partial the new owner has moved past. Abort
+ // it rather than let it land on top of theirs.
+ this.saveAbort?.abort();
+ this.saveAbort = undefined;
+ }
+
+ private async loadCachedPartial(operationId: string): Promise<Partial<ExecutionSnapshot>> {
+ if (this.cached?.operationId === operationId) return this.cached.partial;
+
+ // A different operation must not inherit this cache, and its queued upload
+ // still points at the object we are about to forget β€” land it first.
+ if (this.cached) await this.flushPartial();
+
+ const partial = (await this.store!.loadPartial(operationId)) ?? { steps: [] };
+ this.cached = { operationId, partial };
+ return partial;
+ }
+
+ private scheduleSave(operationId: string): void {
+ this.dirty = true;
+ if (this.pendingSave) return;
+
+ this.pendingSave = this.drainSaves(operationId).finally(() => {
+ this.pendingSave = undefined;
+ });
+ }
+
+ /**
+ * Uploads until the cached partial is clean. Steps appended while an upload is
+ * in flight are picked up by the next iteration, so a fast run collapses
+ * several step appends into one upload instead of one upload per step.
+ */
+ private async drainSaves(operationId: string): Promise<void> {
+ while (this.dirty) {
+ this.dirty = false;
+
+ const partial = this.cached?.operationId === operationId ? this.cached.partial : undefined;
+ if (!partial) return;
+
+ const abort = new AbortController();
+ this.saveAbort = abort;
+ try {
+ await this.store!.savePartial(operationId, partial, { signal: abort.signal });
+ } catch (e) {
+ // Matches the previous behaviour: a failed partial upload degrades the
+ // trace, it never fails the step that produced it. An abort lands here
+ // too β€” the partial it carried is deliberately not written.
+ log('[%s] partial snapshot upload failed: %O', operationId, e);
+ } finally {
+ if (this.saveAbort === abort) this.saveAbort = undefined;
+ }
+ }
+ }
+
async finalize(operationId: string, params: FinalizeParams): Promise<void> {
if (!this.store) return;
try {
- const partial = await this.store.loadPartial(operationId);
+ // Land whatever is still queued: the upload in flight writes the same
+ // object we are about to finalize, and `removePartial` below must not
+ // race an upload that would resurrect the partial afterwards.
+ await this.flushPartial();
+
+ const partial =
+ this.cached?.operationId === operationId
+ ? this.cached.partial
+ : await this.store.loadPartial(operationId);
if (!partial) {
// No partial recorded β€” nothing to finalize. Skip rather than write
// an empty snapshot.
@@ -189,6 +292,9 @@ export class OperationTraceRecorder {
};
await this.store.save(snapshot as any);
+ // Forget the partial before deleting it, so a late `appendStep` on this
+ // recorder cannot re-upload the object we just removed.
+ this.discardPartial();
await this.store.removePartial(operationId);
} catch (e) {
log('[%s] snapshot finalize failed (reason=%s): %O', operationId, params.completionReason, e);
diff --git a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
index 878a2eefd37..d6d5cd0e0d5 100644
--- a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
@@ -723,6 +723,40 @@ describe('AgentRuntimeService.executeStep - step idempotency (distributed lock)'
expect(coordinator.releaseStepLock).not.toHaveBeenCalled();
});
+ it.each([
+ ['a stale delivery it acks', 9],
+ ['a live holder it hands back', 5],
+ ])('drops the buffered trace partial on %s', async (_label, stepCount) => {
+ const service = createService();
+ const coordinator = (service as any).coordinator;
+ coordinator.tryClaimStep = vi.fn().mockResolvedValue(false);
+ coordinator.loadAgentState = vi.fn().mockResolvedValue({ status: 'running', stepCount });
+ const discardPartial = vi.spyOn((service as any).traceRecorder, 'discardPartial');
+
+ await service.executeStep({ operationId: 'op-locked', stepIndex: 5 });
+
+ expect(discardPartial).toHaveBeenCalled();
+ });
+
+ it('drops the buffered trace partial when it re-queues itself after losing the lock', async () => {
+ const scheduleMessage = vi.fn().mockResolvedValue('msg-1');
+ const service = new AgentRuntimeService({} as any, 'user-1', {
+ queueService: { getImpl: () => ({}), scheduleMessage } as any,
+ });
+ const coordinator = (service as any).coordinator;
+ coordinator.tryClaimStep = vi.fn().mockResolvedValue(false);
+ coordinator.loadAgentState = vi.fn().mockResolvedValue({ status: 'running', stepCount: 5 });
+ const discardPartial = vi.spyOn((service as any).traceRecorder, 'discardPartial');
+
+ const result = await service.executeStep({ operationId: 'op-requeue', stepIndex: 5 });
+
+ // This path returns before the generic lock-conflict fallback, so it needs
+ // the same hand-over cleanup: the steps this invocation buffered belong to
+ // whoever holds the operation now.
+ expect(result.lockRescheduled).toBe(true);
+ expect(discardPartial).toHaveBeenCalled();
+ });
+
it('should re-queue the same step on its own backoff for a non-stale lock conflict', async () => {
const scheduleMessage = vi.fn().mockResolvedValue('msg-1');
const service = new AgentRuntimeService({} as any, 'user-1', {
diff --git a/packages/agent-tracing/src/store/types.ts b/packages/agent-tracing/src/store/types.ts
index 7a3c392d5bb..f7bb9aeba33 100644
--- a/packages/agent-tracing/src/store/types.ts
+++ b/packages/agent-tracing/src/store/types.ts
@@ -12,6 +12,14 @@ export interface ISnapshotStore {
/** Remove partial snapshot (after finalizing) */
removePartial: (operationId: string) => Promise<void>;
save: (snapshot: ExecutionSnapshot) => Promise<void>;
- /** Save in-progress partial snapshot */
- savePartial: (operationId: string, partial: Partial<ExecutionSnapshot>) => Promise<void>;
+ /**
+ * Save in-progress partial snapshot. `signal` lets a caller that no longer
+ * owns the operation abort an upload it already started, so it cannot land on
+ * top of the partial the new owner is writing.
+ */
+ savePartial: (
+ operationId: string,
+ partial: Partial<ExecutionSnapshot>,
+ options?: { signal?: AbortSignal },
+ ) => Promise<void>;
}