π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β‘οΈ perf(agent-tracing): zstd-compress S3 snapshots (#14807)
Arvin Xu3dae46911b1a
diff --git a/packages/agent-tracing/src/store/remote-store.ts b/packages/agent-tracing/src/store/remote-store.tsindex 82b29830754..decfa4b5b81 100644--- a/packages/agent-tracing/src/store/remote-store.ts+++ b/packages/agent-tracing/src/store/remote-store.ts@@ -1,8 +1,12 @@import fs from 'node:fs/promises';import path from 'node:path';+import { promisify } from 'node:util';+import { zstdDecompress } from 'node:zlib';import type { ExecutionSnapshot } from '../types';+const decompressZstd = promisify(zstdDecompress);+const REMOTE_DIR = '_remote';const ENV_FILE = '.env';const DEFAULT_DIR = '.agent-tracing';@@ -32,7 +36,7 @@ export function buildRemoteUrl(baseUrl: string, opId: string): string | null {const parsed = parseOperationId(opId);if (!parsed) return null;const base = baseUrl.replace(/\/$/, '');- return `${base}/${parsed.agentId}/${parsed.topicId}/${parsed.operationId}.json`;+ return `${base}/${parsed.agentId}/${parsed.topicId}/${parsed.operationId}.json.zst`;}/**@@ -90,15 +94,17 @@ export class RemoteSnapshotStore {return cached;}- // Download+ // Download β remote object is zstd-compressed JSON (`.json.zst`).console.error(`β Downloading: ${url}`);const res = await fetch(url);if (!res.ok) {throw new Error(`Failed to fetch snapshot: ${res.status} ${res.statusText}\n URL: ${url}`);}- const snapshot = (await res.json()) as ExecutionSnapshot;+ const compressed = Buffer.from(await res.arrayBuffer());+ const decompressed = await decompressZstd(compressed);+ const snapshot = JSON.parse(decompressed.toString('utf8')) as ExecutionSnapshot;- // Cache locally+ // Cache locally as plain JSON for easy inspection.await fs.mkdir(this.cacheDir, { recursive: true });const filePath = path.join(this.cacheDir, `${operationId}.json`);await fs.writeFile(filePath, JSON.stringify(snapshot, null, 2), 'utf8');diff --git a/src/server/modules/AgentTracing/S3SnapshotStore.test.ts b/src/server/modules/AgentTracing/S3SnapshotStore.test.tsnew file mode 100644index 00000000000..52ca2fed38e--- /dev/null+++ b/src/server/modules/AgentTracing/S3SnapshotStore.test.ts@@ -0,0 +1,160 @@+// @vitest-environment node+import { promisify } from 'node:util';+import { zstdCompress, zstdDecompress } from 'node:zlib';++import type { ExecutionSnapshot } from '@lobechat/agent-tracing';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const compressZstd = promisify(zstdCompress);+const decompressZstd = promisify(zstdDecompress);++// Stub FileS3 with vi.fn methods so we can assert calls + return canned data.+const uploadBuffer = vi.fn();+const getFileByteArray = vi.fn();+const getFileContent = vi.fn();+const deleteFile = vi.fn();++vi.mock('@/server/modules/S3', () => ({+ FileS3: vi.fn(() => ({+ deleteFile,+ getFileByteArray,+ getFileContent,+ uploadBuffer,+ })),+}));++// Imported after the mock so the constructor pulls in the stub.+const { S3SnapshotStore } = await import('./S3SnapshotStore');++const sampleSnapshot = (overrides: Partial<ExecutionSnapshot> = {}): ExecutionSnapshot =>+ ({+ agentId: 'agt_abc',+ completedAt: 1_777_000_000_500,+ operationId: 'op_1777000000000_agt_abc_tpc_xyz_QwErTy',+ startedAt: 1_777_000_000_000,+ steps: [],+ topicId: 'tpc_xyz',+ totalCost: 0,+ totalSteps: 0,+ totalTokens: 0,+ ...overrides,+ }) as unknown as ExecutionSnapshot;++beforeEach(() => {+ uploadBuffer.mockReset().mockResolvedValue(undefined);+ getFileByteArray.mockReset();+ getFileContent.mockReset();+ deleteFile.mockReset().mockResolvedValue(undefined);+});++describe('S3SnapshotStore.save', () => {+ it('writes to agent-traces/{agentId}/{topicId}/{operationId}.json.zst with zstd body', async () => {+ const store = new S3SnapshotStore();+ const snap = sampleSnapshot();++ await store.save(snap);++ expect(uploadBuffer).toHaveBeenCalledTimes(1);+ const [key, body, contentType] = uploadBuffer.mock.calls[0];+ expect(key).toBe(`agent-traces/${snap.agentId}/${snap.topicId}/${snap.operationId}.json.zst`);+ expect(contentType).toBe('application/zstd');+ expect(Buffer.isBuffer(body)).toBe(true);++ // zstd frame magic: 0x28 b5 2f fd+ expect([body[0], body[1], body[2], body[3]]).toEqual([0x28, 0xb5, 0x2f, 0xfd]);++ const roundtripped = JSON.parse((await decompressZstd(body)).toString('utf8'));+ expect(roundtripped).toEqual(snap);+ });++ it('falls back to "unknown" when agentId or topicId is missing', async () => {+ const store = new S3SnapshotStore();+ await store.save(sampleSnapshot({ agentId: undefined, topicId: undefined }));++ const [key] = uploadBuffer.mock.calls[0];+ expect(key).toBe(+ 'agent-traces/unknown/unknown/op_1777000000000_agt_abc_tpc_xyz_QwErTy.json.zst',+ );+ });+});++describe('S3SnapshotStore.savePartial', () => {+ it('writes to agent-traces/_partial/{operationId}.json.zst with compressed body', async () => {+ const store = new S3SnapshotStore();+ const partial = { operationId: 'op_partial_1', steps: [{ stepIndex: 0 }] };++ await store.savePartial('op_partial_1', partial as Partial<ExecutionSnapshot>);++ expect(uploadBuffer).toHaveBeenCalledTimes(1);+ const [key, body, contentType] = uploadBuffer.mock.calls[0];+ expect(key).toBe('agent-traces/_partial/op_partial_1.json.zst');+ expect(contentType).toBe('application/zstd');++ const roundtripped = JSON.parse((await decompressZstd(body)).toString('utf8'));+ expect(roundtripped).toEqual(partial);+ });+});++describe('S3SnapshotStore.loadPartial', () => {+ it('decodes the zstd-compressed .json.zst object when present', async () => {+ const partial = { operationId: 'op_load_1', steps: [{ stepIndex: 7 }] };+ const compressed = await compressZstd(Buffer.from(JSON.stringify(partial)));+ getFileByteArray.mockResolvedValueOnce(new Uint8Array(compressed));++ const store = new S3SnapshotStore();+ const result = await store.loadPartial('op_load_1');++ expect(getFileByteArray).toHaveBeenCalledWith('agent-traces/_partial/op_load_1.json.zst');+ expect(result).toEqual(partial);+ });++ it('falls back to legacy uncompressed .json when .json.zst is missing', async () => {+ const partial = { operationId: 'op_legacy_1' };+ getFileByteArray.mockRejectedValueOnce(new Error('NoSuchKey'));+ getFileContent.mockResolvedValueOnce(JSON.stringify(partial));++ const store = new S3SnapshotStore();+ const result = await store.loadPartial('op_legacy_1');++ expect(getFileByteArray).toHaveBeenCalledWith('agent-traces/_partial/op_legacy_1.json.zst');+ expect(getFileContent).toHaveBeenCalledWith('agent-traces/_partial/op_legacy_1.json');+ expect(result).toEqual(partial);+ });++ it('returns null when neither key exists', async () => {+ getFileByteArray.mockRejectedValueOnce(new Error('NoSuchKey'));+ getFileContent.mockRejectedValueOnce(new Error('NoSuchKey'));++ const store = new S3SnapshotStore();+ expect(await store.loadPartial('op_missing')).toBeNull();+ });+});++describe('S3SnapshotStore.removePartial', () => {+ it('deletes both the .json.zst and legacy .json keys', async () => {+ const store = new S3SnapshotStore();+ await store.removePartial('op_remove_1');++ const keys = deleteFile.mock.calls.map(([k]) => k);+ expect(keys).toContain('agent-traces/_partial/op_remove_1.json.zst');+ expect(keys).toContain('agent-traces/_partial/op_remove_1.json');+ expect(deleteFile).toHaveBeenCalledTimes(2);+ });++ it('does not throw when one delete fails (allSettled)', async () => {+ deleteFile.mockRejectedValueOnce(new Error('NoSuchKey')).mockResolvedValueOnce(undefined);++ const store = new S3SnapshotStore();+ await expect(store.removePartial('op_partial_err')).resolves.toBeUndefined();+ });+});++describe('S3SnapshotStore query stubs', () => {+ it('returns null/[] for unsupported query methods (OTEL backend owns querying)', async () => {+ const store = new S3SnapshotStore();+ expect(await store.get('any')).toBeNull();+ expect(await store.getLatest()).toBeNull();+ expect(await store.list()).toEqual([]);+ expect(await store.listPartials()).toEqual([]);+ });+});diff --git a/src/server/modules/AgentTracing/S3SnapshotStore.ts b/src/server/modules/AgentTracing/S3SnapshotStore.tsindex 47e512788c6..46d1291a654 100644--- a/src/server/modules/AgentTracing/S3SnapshotStore.ts+++ b/src/server/modules/AgentTracing/S3SnapshotStore.ts@@ -1,18 +1,33 @@+import { promisify } from 'node:util';+import { zstdCompress, zstdDecompress } from 'node:zlib';+import type { ExecutionSnapshot, ISnapshotStore, SnapshotSummary } from '@lobechat/agent-tracing';import debug from 'debug';import { FileS3 } from '@/server/modules/S3';+const compressZstd = promisify(zstdCompress);+const decompressZstd = promisify(zstdDecompress);+const log = debug('lobe-server:agent-tracing:s3');const TRACE_PREFIX = 'agent-traces';+const SNAPSHOT_SUFFIX = '.json.zst';+const LEGACY_SUFFIX = '.json';+const ZSTD_CONTENT_TYPE = 'application/zstd';/*** S3-backed snapshot store for production agent trace persistence.** S3 paths:- * - Final: agent-traces/{agentId}/{topicId}/{operationId}.json- * - Partial: agent-traces/_partial/{operationId}.json (temporary, deleted after finalization)+ * - Final: agent-traces/{agentId}/{topicId}/{operationId}.json.zst+ * - Partial: agent-traces/_partial/{operationId}.json.zst (temporary, deleted after finalization)+ *+ * Snapshots are zstd-compressed (level 3) before upload β measured 8-9Γ average+ * size reduction across production traces. The `.zst` suffix is the format+ * indicator; Content-Encoding is intentionally NOT set so the object is served+ * as opaque bytes (avoids HTTP middleware auto-decompressing into clients that+ * don't expect it). Readers explicitly decompress.** Partial snapshots are needed because QStash executes each step in a* separate HTTP request (no shared memory). Step data is accumulated@@ -27,16 +42,30 @@ export class S3SnapshotStore implements ISnapshotStore {}private partialKey(operationId: string): string {- return `${TRACE_PREFIX}/_partial/${operationId}.json`;+ return `${TRACE_PREFIX}/_partial/${operationId}${SNAPSHOT_SUFFIX}`;+ }++ private legacyPartialKey(operationId: string): string {+ return `${TRACE_PREFIX}/_partial/${operationId}${LEGACY_SUFFIX}`;+ }++ private async encodeSnapshot(value: unknown): Promise<Buffer> {+ return compressZstd(Buffer.from(JSON.stringify(value)));+ }++ private async decodeSnapshot<T>(bytes: Uint8Array): Promise<T> {+ const buf = await decompressZstd(Buffer.from(bytes));+ return JSON.parse(buf.toString('utf8')) as T;}async save(snapshot: ExecutionSnapshot): Promise<void> {const agentId = snapshot.agentId ?? 'unknown';const topicId = snapshot.topicId ?? 'unknown';- const key = `${TRACE_PREFIX}/${agentId}/${topicId}/${snapshot.operationId}.json`;+ const key = `${TRACE_PREFIX}/${agentId}/${topicId}/${snapshot.operationId}${SNAPSHOT_SUFFIX}`;log('Saving snapshot to S3: %s', key);- await this.s3.uploadContent(key, JSON.stringify(snapshot));+ const compressed = await this.encodeSnapshot(snapshot);+ await this.s3.uploadBuffer(key, compressed, ZSTD_CONTENT_TYPE);}// === Query methods β not supported, use OTEL backend ===@@ -60,8 +89,18 @@ export class S3SnapshotStore implements ISnapshotStore {}async loadPartial(operationId: string): Promise<Partial<ExecutionSnapshot> | null> {+ // Current format: .json.zst (zstd-compressed)+ try {+ const bytes = await this.s3.getFileByteArray(this.partialKey(operationId));+ return await this.decodeSnapshot<Partial<ExecutionSnapshot>>(bytes);+ } catch {+ // fall through to legacy+ }+ // Legacy format: uncompressed .json. Kept to bridge in-flight partials across the+ // deploy window β partials are deleted on finalization so this branch dies off+ // naturally once the longest-running operation completes.try {- const content = await this.s3.getFileContent(this.partialKey(operationId));+ const content = await this.s3.getFileContent(this.legacyPartialKey(operationId));return JSON.parse(content) as Partial<ExecutionSnapshot>;} catch {return null;@@ -69,14 +108,16 @@ export class S3SnapshotStore implements ISnapshotStore {}async savePartial(operationId: string, partial: Partial<ExecutionSnapshot>): Promise<void> {- await this.s3.uploadContent(this.partialKey(operationId), JSON.stringify(partial));+ const compressed = await this.encodeSnapshot(partial);+ await this.s3.uploadBuffer(this.partialKey(operationId), compressed, ZSTD_CONTENT_TYPE);}async removePartial(operationId: string): Promise<void> {- try {- await this.s3.deleteFile(this.partialKey(operationId));- } catch {- // ignore β partial may already be cleaned up- }+ // Clean up both the current key and any legacy uncompressed sibling that may+ // exist if the operation was started before the zstd rollout.+ await Promise.allSettled([+ this.s3.deleteFile(this.partialKey(operationId)),+ this.s3.deleteFile(this.legacyPartialKey(operationId)),+ ]);}}