[GH-ISSUE #3011] [Issue]: MAX_CHAT_VARIABLES cap is a TOCTOU soft-guard; concurrent agents bypass it #1582

Closed
opened 2026-10-21 05:39:50 +07:00 by bsakaguchi · 1 comment
Owner

Originally created by @kolacheee on GitHub (Jun 29, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/3011

Originally assigned to: @SpicyMarinara on GitHub.

What's wrong

writeChatVariable enforces the 256-variable limit by reading context.chatMeta (a shared, refreshed-after-commit reference) BEFORE entering the serialized per-chat metadata patch queue, and the actual write inside the queue's patcher never re-checks the limit. The patcher rebuilds agentVariables from the FRESH currentMeta but unconditionally adds the new key. So the cap is advisory: it is checked against one state and committed against another. Tool-using agents run concurrently and all share the same chatMeta reference. When the count is at 255, multiple concurrent write_chat_variable calls for distinct NEW keys all read 255, all pass the < 256 check, and all commit, pushing the persisted map past MAX_CHAT_VARIABLES.

How to reproduce (try it yourself)

  1. In a chat with two tool-enabled agents that both call write_chat_variable, seed agentVariables to 255 entries.
  2. Trigger a generation where both agents fire write_chat_variable for two different brand-new keys in the same concurrent tool phase.

You'll see: both calls read chatMeta showing 255 (the < 256 check passes for both), both enter the patch queue, and the patcher (which does not re-check the count) writes each key. Persisted metadata.agentVariables now contains 257 entries, exceeding MAX_CHAT_VARIABLES.

Expected: the cap holds under concurrency; the 257th distinct key is rejected with the established { error: "chat variable limit reached (256)" }.

Where it is

packages/server/src/services/tools/tool-executor.ts:567-577 (writeChatVariable): the out-of-queue pre-check at 567-571 and the read-modify-write patcher at 574-577 that omits the limit check. The patcher runs inside withChatMetadataPatchQueue (packages/server/src/services/storage/chats.storage.ts:467-489).

What's happening

The existence/limit pre-check reads context.chatMeta?.agentVariables outside the withChatMetadataPatchQueue critical section, while the authoritative read-modify-write reads fresh currentMeta but omits the limit check. Check-then-act is split across two snapshots with no re-validation inside the serialized section; the shared chatMeta is only refreshed after each completed write, so concurrent agents at count 255 all read 255 before any commit lands.

Suggested fix

Make the cap authoritative inside the serialized patcher and surface the rejection via a closure flag so the tool still returns the established { error } object. Replace the body from line 567:

const value = trimToUtf8Bytes(args.value, MAX_CHAT_VARIABLE_VALUE_BYTES);
let existed = false;
let limitReached = false;
const updated = await context.onUpdateMetadata((currentMeta) => {
  const variables = normalizeAgentVariables(currentMeta.agentVariables);
  existed = Object.prototype.hasOwnProperty.call(variables, keyResult.key);
  if (!existed && Object.keys(variables).length >= MAX_CHAT_VARIABLES) {
    limitReached = true;
    return {}; // no-op patch: do not add the new key
  }
  return { agentVariables: { ...variables, [keyResult.key]: value } };
});
if (limitReached) {
  return { error: `chat variable limit reached (${MAX_CHAT_VARIABLES})` };
}
const variables = normalizeAgentVariables(updated.agentVariables);
return {
  key: keyResult.key,
  value: variables[keyResult.key] ?? value,
  replaced: existed,
  truncated: value !== args.value,
  bytes: utf8ByteLength(value),
};

This removes the stale out-of-queue pre-check entirely; the count, existence check, and cap are now evaluated against the FRESH currentMeta inside withChatMetadataPatchQueue.

Regression avoided: the original suggestion ("return the unchanged agentVariables and surface an error") would, taken literally, fall through to the success return and report success:true for a rejected write — a false-success that misleads the model. Throwing instead would convert to success:false with a bare message string, breaking the structured { error } contract every other tool failure here uses. The closure-flag approach returns {} (a true no-op patch) and then branches to the same { error } object the original returned, and derives replaced from fresh state.


AI-investigated against v2.0.6; cited lines read and confirmed. Please verify before fixing.

Originally created by @kolacheee on GitHub (Jun 29, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/3011 Originally assigned to: @SpicyMarinara on GitHub. **What's wrong** `writeChatVariable` enforces the 256-variable limit by reading `context.chatMeta` (a shared, refreshed-after-commit reference) BEFORE entering the serialized per-chat metadata patch queue, and the actual write inside the queue's patcher never re-checks the limit. The patcher rebuilds `agentVariables` from the FRESH `currentMeta` but unconditionally adds the new key. So the cap is advisory: it is checked against one state and committed against another. Tool-using agents run concurrently and all share the same `chatMeta` reference. When the count is at 255, multiple concurrent `write_chat_variable` calls for distinct NEW keys all read 255, all pass the `< 256` check, and all commit, pushing the persisted map past `MAX_CHAT_VARIABLES`. **How to reproduce (try it yourself)** 1. In a chat with two tool-enabled agents that both call `write_chat_variable`, seed `agentVariables` to 255 entries. 2. Trigger a generation where both agents fire `write_chat_variable` for two different brand-new keys in the same concurrent tool phase. You'll see: both calls read `chatMeta` showing 255 (the `< 256` check passes for both), both enter the patch queue, and the patcher (which does not re-check the count) writes each key. Persisted `metadata.agentVariables` now contains 257 entries, exceeding `MAX_CHAT_VARIABLES`. Expected: the cap holds under concurrency; the 257th distinct key is rejected with the established `{ error: "chat variable limit reached (256)" }`. **Where it is** `packages/server/src/services/tools/tool-executor.ts:567-577` (`writeChatVariable`): the out-of-queue pre-check at 567-571 and the read-modify-write patcher at 574-577 that omits the limit check. The patcher runs inside `withChatMetadataPatchQueue` (`packages/server/src/services/storage/chats.storage.ts:467-489`). **What's happening** The existence/limit pre-check reads `context.chatMeta?.agentVariables` outside the `withChatMetadataPatchQueue` critical section, while the authoritative read-modify-write reads fresh `currentMeta` but omits the limit check. Check-then-act is split across two snapshots with no re-validation inside the serialized section; the shared `chatMeta` is only refreshed after each completed write, so concurrent agents at count 255 all read 255 before any commit lands. **Suggested fix** Make the cap authoritative inside the serialized patcher and surface the rejection via a closure flag so the tool still returns the established `{ error }` object. Replace the body from line 567: ```ts const value = trimToUtf8Bytes(args.value, MAX_CHAT_VARIABLE_VALUE_BYTES); let existed = false; let limitReached = false; const updated = await context.onUpdateMetadata((currentMeta) => { const variables = normalizeAgentVariables(currentMeta.agentVariables); existed = Object.prototype.hasOwnProperty.call(variables, keyResult.key); if (!existed && Object.keys(variables).length >= MAX_CHAT_VARIABLES) { limitReached = true; return {}; // no-op patch: do not add the new key } return { agentVariables: { ...variables, [keyResult.key]: value } }; }); if (limitReached) { return { error: `chat variable limit reached (${MAX_CHAT_VARIABLES})` }; } const variables = normalizeAgentVariables(updated.agentVariables); return { key: keyResult.key, value: variables[keyResult.key] ?? value, replaced: existed, truncated: value !== args.value, bytes: utf8ByteLength(value), }; ``` This removes the stale out-of-queue pre-check entirely; the count, existence check, and cap are now evaluated against the FRESH `currentMeta` inside `withChatMetadataPatchQueue`. *Regression avoided:* the original suggestion ("return the unchanged agentVariables and surface an error") would, taken literally, fall through to the success return and report `success:true` for a rejected write — a false-success that misleads the model. Throwing instead would convert to `success:false` with a bare message string, breaking the structured `{ error }` contract every other tool failure here uses. The closure-flag approach returns `{}` (a true no-op patch) and then branches to the same `{ error }` object the original returned, and derives `replaced` from fresh state. --- *AI-investigated against v2.0.6; cited lines read and confirmed. Please verify before fixing.*
Author
Owner

@SpicyMarinara commented on GitHub (Jun 29, 2026):

Fixed in merged staging PR #3018.

<!-- gh-comment-id:4833018158 --> @SpicyMarinara commented on GitHub (Jun 29, 2026): Fixed in merged staging PR #3018.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Pasta-Devs/Marinara-Engine#1582
No description provided.