[PR #8045] [MERGED] perf(rulesets): build live-state schemas once and cache live-less sheet evaluation per combat command #8072

Closed
opened 2026-10-24 04:10:08 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/8045
Author: @Promansis
Created: 10/22/2026
Status: ✅ Merged
Merged: 10/22/2026
Merged by: @Promansis

Base: staging ← Head: feature(rulesets)/8036-sheet-evaluation-cache


📝 Commits (4)

  • 3cfd002 perf(rulesets): build live-state schemas once and cache live-less sheet evaluation per combat command (#8036)
  • e9ebf9a Merge upstream/staging into feature(rulesets)/8036-sheet-evaluation-cache
  • c22217c fix(rulesets): refuse async work in the sheet evaluation cache scope (#8036)
  • 54b2246 Merge upstream/staging into feature(rulesets)/8036-sheet-evaluation-cache

📊 Changes

5 files changed (+149 additions, -7 deletions)

View changed files

📝 packages/server/src/services/game/ruleset-combat-director.service.ts (+12 -0)
📝 packages/shared/src/features/ruleset-combat/hold.ts (+5 -2)
📝 packages/shared/src/features/rulesets/live-state.ts (+7 -4)
📝 packages/shared/src/features/rulesets/sheet-math.ts (+47 -1)
➕ scripts/regressions/ruleset-sheet-evaluation-cache.regression.ts (+78 -0)

📄 Description

Important

Contributions target staging. Only SpicyMarinara may promote this repository's staging branch or a same-repository hotfix/* branch to main.
Outside and first-time contributors also require an approving review from SpicyMarinara.

Linked issue

Closes #8036

Why this change

  • Every ruleset fight command re-evaluated the same character sheets millions of times. Profiling ruleset-combat-director.regression.ts (the slowest Node regression: 123 s alone, 131–300 s in the CI pool, one pool timeout) put the time in the engine, not the test: 9.7 million live-less evaluateRulesetSheet calls for 13,085 distinct sheets, plus 22.8 s spent rebuilding two zod string schemas on every stored live-state read.
  • The same code runs on the live server for each ruleset combat turn (every command and AI answer on the combat-director route), so players pay that cost too.

What changed

  • Ruleset fight commands are faster. Inside one combat command, each character sheet is now worked out once instead of thousands of times, and reading a fighter's stored live state no longer rebuilds its validators. Nothing a player sees changes: results are the same.

  • How the cache stays safe:

     commandRulesetCombatDirector(definition, state, command, source)
    +  withRulesetSheetEvaluationCache(() =>      // opens one scope per command, cleared in finally
         runRulesetCommand(...)                    // the old body, unchanged
           evaluateRulesetSheet(definition, build)  // no live values
    +        same (definition, build) object seen in this scope → the earlier result
           evaluateRulesetSheet(definition, build, live)  // never cached
    

    Outside a command (fight creation, sheet import, the client) evaluation works exactly as before. The scope takes synchronous work only: a callback that returns a promise throws, because the promise would be awaited after the scope had closed. The cache keys on the build object, so it is only sound if nothing edits a build after evaluating it; the doc comment states that rule.

  • Two places in hold.ts evaluated a clone and then edited it. Both now read the original instead, which is identical until the edit: the creature-sheet health clamp (holdRulesetSheetHealth, named in the issue) and fillRulesetSheetChoices, which the audit of the issue's write sites found. Both run only in createRulesetFight, outside the scope, so this changes no current result; it keeps them correct if they are ever called inside a command.

  • live-state.ts: the two string schemas are built once at load and shared by the stored-state reader and the live-state schema.

  • New regression scripts/regressions/ruleset-sheet-evaluation-cache.regression.ts: inside a scope the same sheet returns the same object and live values bypass the cache; outside a scope results are fresh; the health clamp still reports the clamped maximum inside a scope (it reported "is now 200" instead of "is now 67" before the hold.ts fix); a nested scope does not clear the outer one; a scope that throws still closes; a callback that returns a promise is refused, at the top level and nested.

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

Agent-run checks on e9ebf9a8d (staging be91aab32 merged in), Node v24.15.0:

Command Result
pnpm check exit 0 (one existing react-hooks/exhaustive-deps warning in client code this PR doesn't touch)
node scripts/run-regressions.mjs --concurrency 8 (complete Node lane) exit 0, 993/993 passed, no retries
node scripts/run-regressions.mjs --filter scripts/regressions/ruleset-sheet-evaluation-cache.regression.ts passed (0.9 s in the pool run)

After the Dottore repair (c22217cec), on 54b2246b2 (staging 010829b36 merged in):

Command Result
pnpm check exit 0 (the same existing warning)
node scripts/run-regressions.mjs --filter ruleset --concurrency 8 exit 0, 278/278 passed (combat director 119.7 s, the new regression 1.2 s, both inside the --concurrency 8 pool)
node scripts/run-regressions.mjs --filter scripts/regressions/ruleset-sheet-evaluation-cache.regression.ts, case (e) fails without the guard ("Missing expected exception"), passes with it

Evidence:

  • Before (the hold.ts health line reverted to read the clone): the new regression fails with "…and is now 200".
    After: it passes in under a second.
  • Before: ruleset-combat-director.regression.ts 123 s alone (issue baseline, CI-class runner).
    After: 52.9 s alone on the worker's machine, 77.9 s inside the full local pool (--concurrency 8).
  • Before: 131–300 s inside CI's 4-worker pool, one 300 s timeout in five runs (issue #8036).
    After: 56.0 s and 124.1 s inside that pool on this PR's two runs (jobs 119678441872 and 119724308944), no timeout.
  • One-off probe, not shipped: with the cache forced on everywhere and every cached result deep-frozen, the full Node suite passed except the new regression's own outside-a-scope assertion (which the probe breaks by design). No code wrote to a cached sheet.

Manual verification notes

  • Manually play a ruleset fight in Game Mode (a d20 ruleset such as Ember Roads and a dice-pool one) for a few turns: the options, picker, turn results and health numbers should be the same as on staging, and turns should come back noticeably faster.
  • Manually start a fight with a bestiary creature whose health is outside its tier and confirm the opening still reports the clamped health.

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README) as needed
  • Translated docs on the docs-i18n branch updated to match, or a [docs-i18n] follow-up issue opened (see CONTRIBUTING.md § Translated documentation)
  • Version/release files updated (only if this PR includes a version bump)

Merge danger: two-way door (no stored data or format changes; reverting the commit restores the old path). Blast radius: ruleset combat commands on the server.

UI evidence (if applicable)

Not applicable: no UI change.

🤖 Generated with Claude Code


🔄 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/8045 **Author:** [@Promansis](https://github.com/Promansis) **Created:** 10/22/2026 **Status:** ✅ Merged **Merged:** 10/22/2026 **Merged by:** [@Promansis](https://github.com/Promansis) **Base:** `staging` ← **Head:** `feature(rulesets)/8036-sheet-evaluation-cache` --- ### 📝 Commits (4) - [`3cfd002`](https://github.com/Pasta-Devs/Marinara-Engine/commit/3cfd00286a381db71bed37ccc4c2065bdb31670a) perf(rulesets): build live-state schemas once and cache live-less sheet evaluation per combat command (#8036) - [`e9ebf9a`](https://github.com/Pasta-Devs/Marinara-Engine/commit/e9ebf9a8d378676ed956c6c761c80ff2dde085b2) Merge upstream/staging into feature(rulesets)/8036-sheet-evaluation-cache - [`c22217c`](https://github.com/Pasta-Devs/Marinara-Engine/commit/c22217cec88ea94e3c115269c3a4fb949408e6d3) fix(rulesets): refuse async work in the sheet evaluation cache scope (#8036) - [`54b2246`](https://github.com/Pasta-Devs/Marinara-Engine/commit/54b2246b278d346282af3ee8a521049fe188441b) Merge upstream/staging into feature(rulesets)/8036-sheet-evaluation-cache ### 📊 Changes **5 files changed** (+149 additions, -7 deletions) <details> <summary>View changed files</summary> 📝 `packages/server/src/services/game/ruleset-combat-director.service.ts` (+12 -0) 📝 `packages/shared/src/features/ruleset-combat/hold.ts` (+5 -2) 📝 `packages/shared/src/features/rulesets/live-state.ts` (+7 -4) 📝 `packages/shared/src/features/rulesets/sheet-math.ts` (+47 -1) ➕ `scripts/regressions/ruleset-sheet-evaluation-cache.regression.ts` (+78 -0) </details> ### 📄 Description > [!IMPORTANT] > Contributions target `staging`. Only `SpicyMarinara` may promote this repository's `staging` branch or a same-repository `hotfix/*` branch to `main`. > Outside and first-time contributors also require an approving review from `SpicyMarinara`. <!-- See CONTRIBUTING.md § Branches. --> ## Linked issue Closes #8036 ## Why this change - Every ruleset fight command re-evaluated the same character sheets millions of times. Profiling `ruleset-combat-director.regression.ts` (the slowest Node regression: 123 s alone, 131–300 s in the CI pool, one pool timeout) put the time in the engine, not the test: 9.7 million live-less `evaluateRulesetSheet` calls for 13,085 distinct sheets, plus 22.8 s spent rebuilding two zod string schemas on every stored live-state read. - The same code runs on the live server for each ruleset combat turn (every command and AI answer on the combat-director route), so players pay that cost too. ## What changed - Ruleset fight commands are faster. Inside one combat command, each character sheet is now worked out once instead of thousands of times, and reading a fighter's stored live state no longer rebuilds its validators. Nothing a player sees changes: results are the same. - How the cache stays safe: ```diff commandRulesetCombatDirector(definition, state, command, source) + withRulesetSheetEvaluationCache(() => // opens one scope per command, cleared in finally runRulesetCommand(...) // the old body, unchanged evaluateRulesetSheet(definition, build) // no live values + same (definition, build) object seen in this scope → the earlier result evaluateRulesetSheet(definition, build, live) // never cached ``` Outside a command (fight creation, sheet import, the client) evaluation works exactly as before. The scope takes synchronous work only: a callback that returns a promise throws, because the promise would be awaited after the scope had closed. The cache keys on the build object, so it is only sound if nothing edits a build after evaluating it; the doc comment states that rule. - Two places in `hold.ts` evaluated a clone and then edited it. Both now read the original instead, which is identical until the edit: the creature-sheet health clamp (`holdRulesetSheetHealth`, named in the issue) and `fillRulesetSheetChoices`, which the audit of the issue's write sites found. Both run only in `createRulesetFight`, outside the scope, so this changes no current result; it keeps them correct if they are ever called inside a command. - `live-state.ts`: the two string schemas are built once at load and shared by the stored-state reader and the live-state schema. - New regression `scripts/regressions/ruleset-sheet-evaluation-cache.regression.ts`: inside a scope the same sheet returns the same object and live values bypass the cache; outside a scope results are fresh; the health clamp still reports the clamped maximum inside a scope (it reported "is now 200" instead of "is now 67" before the `hold.ts` fix); a nested scope does not clear the outer one; a scope that throws still closes; a callback that returns a promise is refused, at the top level and nested. ## 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` Agent-run checks on e9ebf9a8d (staging be91aab32 merged in), Node v24.15.0: | Command | Result | | --- | --- | | `pnpm check` | exit 0 (one existing `react-hooks/exhaustive-deps` warning in client code this PR doesn't touch) | | `node scripts/run-regressions.mjs --concurrency 8` (complete Node lane) | exit 0, 993/993 passed, no retries | | `node scripts/run-regressions.mjs --filter scripts/regressions/ruleset-sheet-evaluation-cache.regression.ts` | passed (0.9 s in the pool run) | After the Dottore repair (c22217cec), on 54b2246b2 (staging 010829b36 merged in): | Command | Result | | --- | --- | | `pnpm check` | exit 0 (the same existing warning) | | `node scripts/run-regressions.mjs --filter ruleset --concurrency 8` | exit 0, 278/278 passed (combat director 119.7 s, the new regression 1.2 s, both inside the `--concurrency 8` pool) | | `node scripts/run-regressions.mjs --filter scripts/regressions/ruleset-sheet-evaluation-cache.regression.ts`, case (e) | fails without the guard ("Missing expected exception"), passes with it | Evidence: - **Before** (the `hold.ts` health line reverted to read the clone): the new regression fails with "…and is now 200". **After:** it passes in under a second. - **Before:** `ruleset-combat-director.regression.ts` 123 s alone (issue baseline, CI-class runner). **After:** 52.9 s alone on the worker's machine, 77.9 s inside the full local pool (`--concurrency 8`). - **Before:** 131–300 s inside CI's 4-worker pool, one 300 s timeout in five runs (issue #8036). **After:** 56.0 s and 124.1 s inside that pool on this PR's two runs (jobs 119678441872 and 119724308944), no timeout. - One-off probe, not shipped: with the cache forced on everywhere and every cached result deep-frozen, the full Node suite passed except the new regression's own outside-a-scope assertion (which the probe breaks by design). No code wrote to a cached sheet. ### Manual verification notes - Manually play a ruleset fight in Game Mode (a d20 ruleset such as Ember Roads and a dice-pool one) for a few turns: the options, picker, turn results and health numbers should be the same as on `staging`, and turns should come back noticeably faster. - Manually start a fight with a bestiary creature whose health is outside its tier and confirm the opening still reports the clamped health. ## Docs and release impact - [ ] No docs changes needed - [ ] Updated docs (README / CONTRIBUTING / android/README) as needed - [ ] Translated docs on the `docs-i18n` branch updated to match, or a `[docs-i18n]` follow-up issue opened (see CONTRIBUTING.md § Translated documentation) - [ ] Version/release files updated (only if this PR includes a version bump) Merge danger: two-way door (no stored data or format changes; reverting the commit restores the old path). Blast radius: ruleset combat commands on the server. ## UI evidence (if applicable) Not applicable: no UI change. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-24 04:10:08 +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#8072
No description provided.