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-runtime): externalize operationToolSet out of the per-step Redis state blob (#21606)

Arvin Xuf0026708ee28
diff --git a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
index e8599508a29..7c22ebcab74 100644
--- a/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
+++ b/apps/server/src/modules/AgentRuntime/AgentStateManager.ts
@@ -46,6 +46,68 @@ if redis.call('get', KEYS[1]) == ARGV[1] then
end
return 0`;
+/**
+ * Process-local cache of each operation's serialized tool set, keyed by
+ * operationId.
+ *
+ * The tool set is the heaviest thing on an AgentState (manifest schemas + tool
+ * definitions, ~300–400 KB) and is immutable for the life of the operation β€”
+ * nothing ever reassigns `state.operationToolSet` after creation. So rather
+ * than re-serialize it into the state blob at every step (and re-download it at
+ * every step entry), it lives in its own Redis key written once per process,
+ * and this cache lets the inline step loop β€” which runs many steps in one
+ * process under one lock β€” attach it on load without a second Redis round-trip.
+ *
+ * Bounded + TTL'd: the value is always re-fetchable from Redis, so eviction
+ * only costs a re-read. The cached string is exactly what a normal blob parse
+ * would have produced, so `JSON.parse(json)` on load yields the same fresh,
+ * independent object the old inline path handed each reader.
+ */
+const TOOLSET_CACHE_MAX = 64;
+const toolSetJsonCache = new Map<string, { expiresAt: number; json: string }>();
+
+const readToolSetCache = (operationId: string): string | undefined => {
+ const hit = toolSetJsonCache.get(operationId);
+ if (!hit) return undefined;
+ if (hit.expiresAt <= Date.now()) {
+ toolSetJsonCache.delete(operationId);
+ return undefined;
+ }
+ // Touch for LRU recency.
+ toolSetJsonCache.delete(operationId);
+ toolSetJsonCache.set(operationId, hit);
+ return hit.json;
+};
+
+const writeToolSetCache = (operationId: string, json: string, ttlSeconds: number): void => {
+ toolSetJsonCache.delete(operationId);
+ toolSetJsonCache.set(operationId, { expiresAt: Date.now() + ttlSeconds * 1000, json });
+ while (toolSetJsonCache.size > TOOLSET_CACHE_MAX) {
+ const oldest = toolSetJsonCache.keys().next().value;
+ if (oldest === undefined) break;
+ toolSetJsonCache.delete(oldest);
+ }
+};
+
+/**
+ * Whether a persisted blob may leave its tool set out.
+ *
+ * Reading the external key and writing it are two separate deploys. A queue
+ * continuation targets the shared runtime URL, not a versioned deployment, so
+ * during a rolling deploy (or a rollback) an operation saved by this build can
+ * next execute on a worker running the previous one β€” and that worker's
+ * `loadAgentState` never reads `agent_runtime_toolset`. Stripping on the first
+ * deploy would hand it a blob with no tool set, and the next LLM call would go
+ * out with the empty set `selectOperationToolSet` falls back to.
+ *
+ * So this build ships the reader only: while the flag is off nothing changes β€”
+ * the blob keeps its inline tool set byte-for-byte and no external key is
+ * written. Operators flip it on once the previous build has drained, which is
+ * when the mixed-version window is gone.
+ */
+const isToolSetStripEnabled = (): boolean =>
+ process.env.AGENT_RUNTIME_STRIP_OPERATION_TOOLSET === '1';
+
export interface StepResult {
events?: AgentEvent[];
executionTime: number;
@@ -105,6 +167,7 @@ export interface AgentOperationMetadata {
export class AgentStateManager {
private redis: Redis;
private readonly STATE_PREFIX = 'agent_runtime_state';
+ private readonly TOOLSET_PREFIX = 'agent_runtime_toolset';
private readonly STEPS_PREFIX = 'agent_runtime_steps';
private readonly METADATA_PREFIX = 'agent_runtime_meta';
private readonly INTERRUPT_PREFIX = 'agent_runtime_interrupt';
@@ -144,13 +207,70 @@ export class AgentStateManager {
* the prompt.
*/
private serializeStateForPersist(state: AgentState): string {
- if (hasNonPersistedMessage((state as { messages?: unknown }).messages)) {
- return JSON.stringify(state);
+ // `operationToolSet` is externalized to its own key (see
+ // `externalizeToolSet`) and re-attached on load, so it never travels in the
+ // blob β€” once stripping is enabled. Until then the blob keeps its inline
+ // copy so a previous-build worker can still execute the operation (see
+ // `isToolSetStripEnabled`). It is immutable after creation, so a single
+ // write per operation replaces re-serializing ~300–400 KB of tool schemas
+ // at every step.
+ const { operationToolSet: _toolSet, ...withoutToolSet } = state as AgentState & {
+ operationToolSet?: unknown;
+ };
+ const persistable = (isToolSetStripEnabled() ? withoutToolSet : state) as AgentState & {
+ messages?: unknown;
+ operationToolSet?: unknown;
+ };
+ if (hasNonPersistedMessage(persistable.messages)) {
+ return JSON.stringify(persistable);
}
- const { messages: _messages, ...rest } = state as AgentState & { messages?: unknown };
+ const { messages: _messages, ...rest } = persistable;
return JSON.stringify(rest);
}
+ private toolSetKey(operationId: string): string {
+ return `${this.TOOLSET_PREFIX}:${operationId}`;
+ }
+
+ /**
+ * Persist the operation's tool set to its own key, once per process.
+ *
+ * Write-once is guarded by the process cache: the first save in a process
+ * writes the key and seeds the cache; every later save (each step of an
+ * inline loop) finds the cache warm and skips the ~300–400 KB write
+ * entirely β€” the save paths only refresh the key's TTL in lockstep with the
+ * state blob. A queue redelivery lands in a fresh process and re-writes once,
+ * which is negligible beside the per-step writes it removes.
+ */
+ private async externalizeToolSet(operationId: string, state: AgentState): Promise<void> {
+ const toolSet = (state as { operationToolSet?: unknown }).operationToolSet;
+ if (!toolSet) return;
+ if (readToolSetCache(operationId)) return;
+ const json = JSON.stringify(toolSet);
+ await this.redis.setex(this.toolSetKey(operationId), this.DEFAULT_TTL, json);
+ writeToolSetCache(operationId, json, this.DEFAULT_TTL);
+ }
+
+ /**
+ * Re-attach the externalized tool set to a freshly loaded state. Served from
+ * the process cache after the first read, so an inline loop reads it from
+ * Redis at most once per process. A blob that still carries its tool set
+ * inline β€” written by pre-externalization code during a rolling deploy β€” is
+ * left untouched, and an operation whose key has genuinely gone degrades to
+ * the same empty-tool-set fallback the selectors already apply.
+ */
+ private async rehydrateToolSet(operationId: string, state: AgentState): Promise<void> {
+ if ((state as { operationToolSet?: unknown }).operationToolSet) return;
+ let json = readToolSetCache(operationId);
+ if (!json) {
+ json = (await this.redis.get(this.toolSetKey(operationId))) ?? undefined;
+ if (json) writeToolSetCache(operationId, json, this.DEFAULT_TTL);
+ }
+ if (json) {
+ (state as { operationToolSet?: unknown }).operationToolSet = JSON.parse(json);
+ }
+ }
+
/**
* Save Agent state
*/
@@ -158,8 +278,13 @@ export class AgentStateManager {
const stateKey = `${this.STATE_PREFIX}:${operationId}`;
try {
+ const stripToolSet = isToolSetStripEnabled();
+ if (stripToolSet) await this.externalizeToolSet(operationId, state);
const serializedState = this.serializeStateForPersist(state);
await this.redis.setex(stateKey, this.DEFAULT_TTL, serializedState);
+ // Keep the externalized tool set alive in lockstep with the blob so a
+ // long run never loads a stripped blob whose tool set has expired.
+ if (stripToolSet) await this.redis.expire(this.toolSetKey(operationId), this.DEFAULT_TTL);
// Update metadata
await this.updateOperationMetadata(operationId, {
@@ -194,6 +319,7 @@ export class AgentStateManager {
// Blobs written before the typed `world` / `binding` slots existed carry
// that context in `metadata`; lift it once here so readers see one shape.
const state = normalizeAgentState(JSON.parse(serializedState) as AgentState);
+ await this.rehydrateToolSet(operationId, state);
log('[%s] Loaded state (step %d)', operationId, state.stepCount);
return state;
@@ -241,9 +367,14 @@ export class AgentStateManager {
* Save step execution result
*/
async saveStepResult(operationId: string, stepResult: StepResult): Promise<void> {
- const pipeline = this.redis.multi();
-
try {
+ // Write-once before opening the pipeline; the inline loop warms the cache
+ // on its first step and every later step skips the tool-set write.
+ const stripToolSet = isToolSetStripEnabled();
+ if (stripToolSet) await this.externalizeToolSet(operationId, stepResult.newState);
+
+ const pipeline = this.redis.multi();
+
// Save latest state
const stateKey = `${this.STATE_PREFIX}:${operationId}`;
pipeline.setex(
@@ -251,6 +382,8 @@ export class AgentStateManager {
this.DEFAULT_TTL,
this.serializeStateForPersist(stepResult.newState),
);
+ // Refresh the externalized tool set's TTL alongside the blob.
+ if (stripToolSet) pipeline.expire(this.toolSetKey(operationId), this.DEFAULT_TTL);
// Save step history
const stepsKey = `${this.STEPS_PREFIX}:${operationId}`;
@@ -448,6 +581,7 @@ export class AgentStateManager {
async deleteAgentOperation(operationId: string): Promise<void> {
const keys = [
`${this.STATE_PREFIX}:${operationId}`,
+ this.toolSetKey(operationId),
`${this.STEPS_PREFIX}:${operationId}`,
`${this.METADATA_PREFIX}:${operationId}`,
`${this.INTERRUPT_PREFIX}:${operationId}`,
@@ -456,6 +590,7 @@ export class AgentStateManager {
];
try {
+ toolSetJsonCache.delete(operationId);
await this.redis.del(...keys);
log('Deleted operation %s', operationId);
} catch (error) {
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts
index 43d53ac8eaa..075e1490fbb 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/AgentStateManager.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it, vi } from 'vitest';
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { AgentStateManager } from '../AgentStateManager';
@@ -202,6 +202,159 @@ describe('AgentStateManager', () => {
});
});
+ // The tool set is immutable, the heaviest thing on the state, and re-written
+ // at every step; it lives in its own key written once per process and is
+ // re-attached on load. Distinct operationIds per test: the write-once cache
+ // is process-global and survives `clearAllMocks`.
+ describe('operationToolSet externalization', () => {
+ const toolSet = { enabledToolIds: ['foo'], manifestMap: { foo: { api: [] } }, tools: [{}] };
+
+ // Stripping is opt-in so a previous-build worker can still execute an
+ // operation mid-rollout (see `isToolSetStripEnabled`).
+ const STRIP_FLAG = 'AGENT_RUNTIME_STRIP_OPERATION_TOOLSET';
+ const originalFlag = process.env[STRIP_FLAG];
+
+ beforeEach(() => {
+ process.env[STRIP_FLAG] = '1';
+ });
+
+ afterAll(() => {
+ if (originalFlag === undefined) delete process.env[STRIP_FLAG];
+ else process.env[STRIP_FLAG] = originalFlag;
+ });
+
+ it('writes the tool set to its own key and strips it from the state blob', async () => {
+ await stateManager.saveAgentState('op-ots-strip', {
+ operationToolSet: toolSet,
+ status: 'running',
+ stepCount: 1,
+ } as any);
+
+ expect(redisMock.setex).toHaveBeenCalledWith(
+ 'agent_runtime_toolset:op-ots-strip',
+ 2 * 3600,
+ JSON.stringify(toolSet),
+ );
+ const blob = redisMock.setex.mock.calls.find(
+ (c) => c[0] === 'agent_runtime_state:op-ots-strip',
+ );
+ expect(JSON.parse(blob![2] as string).operationToolSet).toBeUndefined();
+ expect(JSON.parse(blob![2] as string).status).toBe('running');
+ });
+
+ it('writes the tool set once per process and only refreshes its TTL after that', async () => {
+ const op = 'op-ots-once';
+ const state = { operationToolSet: toolSet, status: 'running', stepCount: 1 } as any;
+
+ await stateManager.saveAgentState(op, state);
+ await stateManager.saveAgentState(op, state);
+
+ const writes = redisMock.setex.mock.calls.filter(
+ (c) => c[0] === `agent_runtime_toolset:${op}`,
+ );
+ expect(writes).toHaveLength(1);
+ expect(redisMock.expire).toHaveBeenCalledWith(`agent_runtime_toolset:${op}`, 2 * 3600);
+ });
+
+ it('refreshes the tool-set TTL inside the step pipeline and strips the blob', async () => {
+ const op = 'op-ots-step';
+ await stateManager.saveStepResult(op, {
+ executionTime: 1,
+ newState: { operationToolSet: toolSet, status: 'running', stepCount: 1 },
+ stepIndex: 1,
+ } as any);
+
+ expect(redisMock.setex).toHaveBeenCalledWith(
+ `agent_runtime_toolset:${op}`,
+ 2 * 3600,
+ JSON.stringify(toolSet),
+ );
+ expect(pipelineMock.expire).toHaveBeenCalledWith(`agent_runtime_toolset:${op}`, 2 * 3600);
+ const blob = pipelineMock.setex.mock.calls.find((c) => c[0] === `agent_runtime_state:${op}`);
+ expect(JSON.parse(blob![2] as string).operationToolSet).toBeUndefined();
+ });
+
+ it('re-attaches the tool set from its key when the loaded blob has none', async () => {
+ const op = 'op-ots-load';
+ redisMock.get.mockImplementation((key: string) =>
+ key === `agent_runtime_state:${op}`
+ ? JSON.stringify({ status: 'running', stepCount: 2 })
+ : key === `agent_runtime_toolset:${op}`
+ ? JSON.stringify(toolSet)
+ : null,
+ );
+
+ const loaded = await stateManager.loadAgentState(op);
+ expect(loaded?.operationToolSet).toEqual(toolSet);
+ });
+
+ it('leaves an inline (legacy / rolling-deploy) tool set untouched', async () => {
+ const op = 'op-ots-inline';
+ const inline = { enabledToolIds: [], manifestMap: { bar: {} }, tools: [] };
+ redisMock.get.mockImplementation((key: string) =>
+ key === `agent_runtime_state:${op}`
+ ? JSON.stringify({ operationToolSet: inline, status: 'running', stepCount: 1 })
+ : null,
+ );
+
+ const loaded = await stateManager.loadAgentState(op);
+ expect(loaded?.operationToolSet).toEqual(inline);
+ expect(redisMock.get).not.toHaveBeenCalledWith(`agent_runtime_toolset:${op}`);
+ });
+ });
+
+ // A queue continuation targets the shared runtime URL, so an operation saved
+ // by this build can next run on a previous-build worker that never reads the
+ // external key. Until operators drain that build the blob must stay
+ // self-contained.
+ describe('operationToolSet externalization Β· rolling-deploy compatibility', () => {
+ const STRIP_FLAG = 'AGENT_RUNTIME_STRIP_OPERATION_TOOLSET';
+ const originalFlag = process.env[STRIP_FLAG];
+
+ afterAll(() => {
+ if (originalFlag === undefined) delete process.env[STRIP_FLAG];
+ else process.env[STRIP_FLAG] = originalFlag;
+ });
+
+ it('keeps the inline tool set and writes no external key while stripping is off', async () => {
+ delete process.env[STRIP_FLAG];
+ const op = 'op-ots-compat-off';
+ const toolSet = { enabledToolIds: ['compat'], manifestMap: { bar: {} }, tools: [{}] };
+
+ await stateManager.saveAgentState(op, {
+ operationToolSet: toolSet,
+ status: 'running',
+ stepCount: 1,
+ } as any);
+
+ expect(redisMock.setex.mock.calls.some((c) => c[0] === `agent_runtime_toolset:${op}`)).toBe(
+ false,
+ );
+ expect(redisMock.expire).not.toHaveBeenCalledWith(`agent_runtime_toolset:${op}`, expect.anything());
+ const blob = redisMock.setex.mock.calls.find((c) => c[0] === `agent_runtime_state:${op}`);
+ expect(JSON.parse(blob![2] as string).operationToolSet).toEqual(toolSet);
+ });
+
+ it('keeps the inline tool set in the step pipeline while stripping is off', async () => {
+ delete process.env[STRIP_FLAG];
+ const op = 'op-ots-compat-step';
+ const toolSet = { enabledToolIds: ['compat-step'], manifestMap: {}, tools: [] };
+
+ await stateManager.saveStepResult(op, {
+ executionTime: 1,
+ newState: { operationToolSet: toolSet, status: 'running', stepCount: 1 },
+ stepIndex: 1,
+ } as any);
+
+ expect(pipelineMock.expire).not.toHaveBeenCalledWith(
+ `agent_runtime_toolset:${op}`,
+ expect.anything(),
+ );
+ const blob = pipelineMock.setex.mock.calls.find((c) => c[0] === `agent_runtime_state:${op}`);
+ expect(JSON.parse(blob![2] as string).operationToolSet).toEqual(toolSet);
+ });
+ });
+
describe('step execution lock', () => {
it('claims an operation-scoped lock with the provided owner token', async () => {
redisMock.eval.mockResolvedValue(1);
@@ -286,6 +439,7 @@ describe('AgentStateManager', () => {
expect(redisMock.del).toHaveBeenCalledWith(
'agent_runtime_state:op-del',
+ 'agent_runtime_toolset:op-del',
'agent_runtime_steps:op-del',
'agent_runtime_meta:op-del',
'agent_runtime_interrupt:op-del',