[PR #3118] [MERGED] fix(shared): make macro display resolution linear, not super-linear (#3104) #5806

Closed
opened 2026-10-22 04:19:41 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/3118
Author: @kolacheee
Created: 6/30/2026
Status: ✅ Merged
Merged: 7/2/2026
Merged by: @SpicyMarinara

Base: staging ← Head: fix/3104-macro-engine-perf


📝 Commits (3)

  • fe48df1 fix(shared): make macro display resolution linear, not super-linear (#3104)
  • d4b9b92 fix(shared): tighten macro fast-path edges found by adversarial audit
  • e7e4ff8 test(shared): cover macro passthrough optimization

📊 Changes

2 files changed (+73 additions, -11 deletions)

View changed files

📝 packages/shared/src/utils/macro-engine.ts (+36 -11)
📝 scripts/regressions/prompt.regression.ts (+37 -0)

📄 Description

Linked issue

Relates to #3104 — this is the primary per-resolution-cost fix (the macro engine), complementary to #3114 ("Reduce chat area render scope", the re-render-frequency side). It should not auto-close #3104 until an affected user confirms the freeze is gone (see below).

Why this change

A Bottom-Up CPU profile from an affected user pinned the #3104 freeze: resolveMacros at 75% self-time (~38s). resolveMacros runs per message during display render in every mode (ChatMessage, ConversationMessage, GameNarration), so this is the cross-mode cause behind the game / roleplay / conversation reports.

The root cause: resolveMacros eagerly and unconditionally rebuilt personaText — resolving all five persona fields, each of which recurses back into resolveMacros when it contains macros — on every call, before checking whether the template even uses {{persona}}. Worse, that rebuild is re-paid at every nested field-resolution frame, so it compounds. On agent chats with large, self-referential persona fields, per-message display resolution goes super-linear. (Introduced by the v2.0.7 macro rewrite, afa0cc3ab.)

What changed

Two behavior-preserving changes in packages/shared/src/utils/macro-engine.ts:

  1. Top-level early-out. Every step of resolveMacros is triggered by either {{ (live macros) or the \x1e deferred-character-token sentinel. A template containing neither has nothing to resolve, so it's returned unchanged (with the same trimResult/clampMacroOutput finalize) instead of running the comment strip, bracket/conditional expansion, the global substitution passes, and the persona build. This covers the bulk of display content (plain prose).
  2. Lazy personaText. Build it only when {{persona}} is actually present in the result, keeping the string-replace form so $-sequences substitute exactly as before. This stops the unconditional (and per-recursion-frame) persona rebuild.

No budget caps were touched. MAX_MACRO_EXPANSIONS / MAX_MACRO_OUTPUT_LENGTH / depth limits are unchanged, so this does not trade speed for unresolved (literal) macros — macros still fully resolve, always for API prompts and on user-visible display content.

Validation

  • pnpm check passes locally
  • Container (Docker / Podman) built and ran without issue
  • Ran the app, clicked through the changes manually
  • Checked edge cases (light + dark mode, mobile viewport, empty states, error paths)
  • Above manual verification completed (describe below)
  • Read and followed CONTRIBUTING.md

Manual verification notes

Done by the agent:

  • pnpm check → exit 0 (TypeScript + ESLint + build).
  • Byte-identical output proven old (staging) vs new across: plain prose, {{user}}/{{char}}, {{persona}} with a $& sequence (string-replace semantics preserved), char-field macros, {{#if}} conditionals, and a \x1e deferred-character token (passed through untouched). Output matched exactly in every case.
  • Timing on a synthetic ~12KB self-referential persona context: plain msg 59ms → 0ms, {{char}} msg 57ms → 0.13ms, {{persona}} msg 58ms → 1.26ms (~50–450×).

Still needs manual verification (decisive — don't merge on synthetic/code-reading alone):

  • An affected user re-tests the real laggy chat on this branch and confirms the multi-second chat-area freeze is gone (their data is what produced the 38s; the synthetic case only proves the shape).
  • Spot-check that {{user}}/{{char}}/{{persona}} and conditionals still render correctly in a real roleplay/conversation/game chat, and that an API prompt (peek-prompt) still fully resolves macros.

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed
  • Version/release files updated (only if this PR includes a version bump)

UI evidence (if applicable)

No UI change — macro output is identical; only the cost of producing it changes.

Summary by CodeRabbit

  • Performance Improvements
    • Improved macro processing so plain text templates are handled faster, with less unnecessary work.
    • Reduced extra processing for persona content by generating it only when needed.

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Pasta-Devs/Marinara-Engine/pull/3118 **Author:** [@kolacheee](https://github.com/kolacheee) **Created:** 6/30/2026 **Status:** ✅ Merged **Merged:** 7/2/2026 **Merged by:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Base:** `staging` ← **Head:** `fix/3104-macro-engine-perf` --- ### 📝 Commits (3) - [`fe48df1`](https://github.com/Pasta-Devs/Marinara-Engine/commit/fe48df1b942ffb9abd227a6251058f3c2d20450a) fix(shared): make macro display resolution linear, not super-linear (#3104) - [`d4b9b92`](https://github.com/Pasta-Devs/Marinara-Engine/commit/d4b9b927e645e15d914922064ab2107bb6425600) fix(shared): tighten macro fast-path edges found by adversarial audit - [`e7e4ff8`](https://github.com/Pasta-Devs/Marinara-Engine/commit/e7e4ff83caf9af55ae303bd5a2983dcfd9813f2c) test(shared): cover macro passthrough optimization ### 📊 Changes **2 files changed** (+73 additions, -11 deletions) <details> <summary>View changed files</summary> 📝 `packages/shared/src/utils/macro-engine.ts` (+36 -11) 📝 `scripts/regressions/prompt.regression.ts` (+37 -0) </details> ### 📄 Description ## Linked issue Relates to #3104 — this is the **primary per-resolution-cost** fix (the macro engine), complementary to #3114 ("Reduce chat area render scope", the re-render-frequency side). It should **not** auto-close #3104 until an affected user confirms the freeze is gone (see below). ## Why this change A Bottom-Up CPU profile from an affected user pinned the #3104 freeze: **`resolveMacros` at 75% self-time (~38s)**. `resolveMacros` runs **per message during display render in every mode** (`ChatMessage`, `ConversationMessage`, `GameNarration`), so this is the cross-mode cause behind the game / roleplay / conversation reports. The root cause: `resolveMacros` **eagerly and unconditionally rebuilt `personaText`** — resolving all five persona fields, each of which **recurses back into `resolveMacros`** when it contains macros — on *every* call, *before* checking whether the template even uses `{{persona}}`. Worse, that rebuild is **re-paid at every nested field-resolution frame**, so it compounds. On agent chats with large, self-referential persona fields, per-message display resolution goes super-linear. (Introduced by the v2.0.7 macro rewrite, `afa0cc3ab`.) ## What changed Two **behavior-preserving** changes in `packages/shared/src/utils/macro-engine.ts`: 1. **Top-level early-out.** Every step of `resolveMacros` is triggered by either `{{` (live macros) or the `\x1e` deferred-character-token sentinel. A template containing neither has nothing to resolve, so it's returned unchanged (with the same `trimResult`/`clampMacroOutput` finalize) instead of running the comment strip, bracket/conditional expansion, the global substitution passes, and the persona build. This covers the bulk of display content (plain prose). 2. **Lazy `personaText`.** Build it only when `{{persona}}` is actually present in the result, keeping the **string-replace form** so `$`-sequences substitute exactly as before. This stops the unconditional (and per-recursion-frame) persona rebuild. **No budget caps were touched.** `MAX_MACRO_EXPANSIONS` / `MAX_MACRO_OUTPUT_LENGTH` / depth limits are unchanged, so this does **not** trade speed for unresolved (literal) macros — macros still fully resolve, always for API prompts and on user-visible display content. ## Validation - [ ] `pnpm check` passes locally - [ ] Container (Docker / Podman) built and ran without issue - [ ] Ran the app, clicked through the changes manually - [ ] Checked edge cases (light + dark mode, mobile viewport, empty states, error paths) - [ ] Above manual verification completed (describe below) - [ ] Read and followed `CONTRIBUTING.md` ### Manual verification notes Done by the agent: - `pnpm check` → exit 0 (TypeScript + ESLint + build). - **Byte-identical output proven** old (staging) vs new across: plain prose, `{{user}}`/`{{char}}`, `{{persona}}` with a `$&` sequence (string-replace semantics preserved), char-field macros, `{{#if}}` conditionals, and a `\x1e` deferred-character token (passed through untouched). Output matched exactly in every case. - Timing on a synthetic ~12KB self-referential persona context: plain msg **59ms → 0ms**, `{{char}}` msg **57ms → 0.13ms**, `{{persona}}` msg **58ms → 1.26ms** (~50–450×). Still needs manual verification (decisive — don't merge on synthetic/code-reading alone): - **An affected user re-tests the real laggy chat on this branch** and confirms the multi-second `chat-area` freeze is gone (their data is what produced the 38s; the synthetic case only proves the *shape*). - Spot-check that `{{user}}`/`{{char}}`/`{{persona}}` and conditionals still render correctly in a real roleplay/conversation/game chat, and that an API prompt (peek-prompt) still fully resolves macros. ## Docs and release impact - [ ] No docs changes needed - [ ] Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed - [ ] Version/release files updated (only if this PR includes a version bump) ## UI evidence (if applicable) No UI change — macro output is identical; only the cost of producing it changes. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Performance Improvements** * Improved macro processing so plain text templates are handled faster, with less unnecessary work. * Reduced extra processing for persona content by generating it only when needed. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-22 04:19:41 +07:00
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#5806
No description provided.