[GH-ISSUE #8036] [Feature]: Build ruleset live-state schemas once and cache the live-less sheet evaluation per combat command #7533

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

Originally created by @Promansis on GitHub (Oct 22, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/8036

Originally assigned to: @Promansis on GitHub.

What problem does this solve?

A ruleset fight re-evaluates the same character sheets hundreds of times per combat command. scripts/regressions/ruleset-combat-director.regression.ts is the slowest Node regression (123 s solo, 131–300 s inside the 4-worker CI pool, one pool timeout at 300 s in five observed runs), and a CPU profile of it shows that the time is in the engine, not the test:

Self time (of 128 s CPU) Where
44 s evaluateRulesetSheet and helpers in packages/shared/src/features/rulesets/sheet-math.ts
31 s packages/shared/src/features/rulesets/live-state.ts (listRulesetLivePools, resolveLive, wound work)
29 s zod, of which 22.8 s is constructing ZodString/ZodType inside readStoredLiveStateAsIs

Two causes:

  1. readStoredLiveStateAsIs builds z.string().max(...) twice on every call (keepValid(source.text, z.string().max(MAX_LIVE_TEXT_LENGTH), …) and the same for states). It runs for every combatant on every read of a stored live state.
  2. resolveLive → listRulesetLivePools → evaluateRulesetSheet(definition, build) (no live values) is called from the option enumeration and picker loops. Counted with an instrumented build: the regression makes 9.7 million live-less evaluations for only 13,085 distinct (definition, build) pairs. One evaluation costs about 4 µs; the volume is the cost.

The same code runs in the live server on the combat-director route, skill-check resolution, and the inventory and market services, so each ruleset combat turn pays this too.

Proposed solution

Two commits in one PR, the first mergeable on its own.

Commit 1 (near zero risk): build the two schemas once. In live-state.ts, next to liveNumber:

const liveTextValue = z.string().max(MAX_LIVE_TEXT_LENGTH);
const liveStateValue = z.string().max(MAX_LIVE_STATE_VALUE_LENGTH);

and in readStoredLiveStateAsIs use keepValid(source.text, liveTextValue, MAX_LIVE_TEXTS) and keepValid(source.states, liveStateValue, MAX_LIVE_STATES). Same schema, same validation, four lines. Measured: the regression drops from 123 s to 102 s solo.

Commit 2 (medium risk, so scoped and proven): cache the live-less sheet evaluation for the duration of one director command.

  • In sheet-math.ts, keep the existing function body as evaluateRulesetSheetUncached and export evaluateRulesetSheet as a wrapper that, only while a scope is open, memoizes the live === undefined case in a WeakMap<RulesetDefinition, WeakMap<RulesetSheetBuild, EvaluatedRulesetSheet>>. Calls with live values are never cached. Export withRulesetSheetEvaluationCache<T>(run: () => T): T that opens a fresh map, runs, and always clears it in finally (nested calls reuse the open scope).
  • Open the scope in commandRulesetCombatDirector (packages/server/src/services/game/ruleset-combat-director.service.ts) around its body. Builds are not edited during a command (fight creation, sheet import and the creature-sheet hold run outside it), which is what makes an identity-keyed cache sound there. Outside a scope the function behaves exactly as today.
  • Fix the one known clone-then-edit site, which a probe of this cache found: in packages/shared/src/features/ruleset-combat/hold.ts (health clamp, near line 525) the code clones proposed, evaluates the clone through resolveRulesetValueRef(definition, sheet, { field: field.id }), then writes sheet.fields[field.id] = … and evaluates it again. Read current from proposed (identical before the write) so the clone is only evaluated after its edit. With a globally enabled cache this is the only failure in the 269 ruleset-combat-* and game-ruleset-* regressions (game-ruleset-combat-creature-sheets reported "is now 200" instead of "is now 67").
  • Audit the other in-place writes to a build so none evaluates the object before writing to it: hold.ts lines ~206, 260, 323, 472; sheet-builder.ts ~1402, 1408, 2078–2089; sheet-math.ts ~151; live-state.ts ~1043. All are clone-then-edit builders and all passed the probe, but the rule "evaluate a build only after its last write" should be stated in a comment on the cache.
  • Regression proof, scripts/regressions/ruleset-sheet-evaluation-cache.regression.ts: (a) inside withRulesetSheetEvaluationCache, evaluating the same (definition, build) twice returns the same object and a third call with live values does not; (b) outside the scope two calls return distinct objects; (c) the hold.ts health clamp, run inside the scope on a creature whose health is outside its tier, still reports the clamped maximum; (d) a nested scope does not clear the outer one. Keep the file deterministic and under a second.
  • One-off verification for the PR, not shipped: run the full suite once with the cache enabled globally and every cached object deep-frozen (Object.freeze recursively) so any aliasing write throws. The probe run of this found no frozen-object writes.

Measured with both commits applied: the regression runs in 60 s solo (from 123 s), with 9.7 million evaluations collapsing to 13,085 misses. Outputs are byte-identical; the only way the cache can change behaviour is the clone-then-edit pattern above, which the scope, the fix and the regression close.

Alternatives considered

  • A global, always-on identity cache: simplest, but it is exactly what the probe broke on, and every future clone-then-edit site would silently read stale numbers. The command scope bounds the hazard to code that runs inside one command.
  • Passing an evaluated sheet down through listRulesetLivePools and the option loops: correct and explicit, but touches dozens of call sites in encounter.ts, options.ts and resolve.ts for the same result.
  • A structural cache key (hashing the build): safe against in-place edits, but hashing a build per call costs more than the 4 µs evaluation it would save.
  • Only splitting or trimming the regression file: hides the cost instead of removing it from the server's hot path.

Additional context

  • Profile and probe numbers come from PR #8033 work (issue #8032), on a clean worktree of staging at 4d67fe75b, Node 24.15. The regression's own lane effect: shard 1 of complete-node-regressions stops being the longest shard and the 300 s pool timeout (seen in run 39664968247, job 119474763718) cannot recur.
  • Related: #8037 widens the two pool timeouts in the harness so it can land immediately; #8038 splits the regression file and is only needed if this issue does not land.
  • Callers never mutate an evaluated sheet (grep for writes to evaluated.* finds none in packages/), and the client already memoizes sheet evaluation per render (GameRulesetSheet.tsx), so no client change is needed.

Template check

Please uncheck (untick) the box below before submitting so we know you read the template. It is intentionally pre-checked:

  • I DID NOT read this template and provide the requested details.
Originally created by @Promansis on GitHub (Oct 22, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/8036 Originally assigned to: @Promansis on GitHub. ## What problem does this solve? A ruleset fight re-evaluates the same character sheets hundreds of times per combat command. `scripts/regressions/ruleset-combat-director.regression.ts` is the slowest Node regression (123 s solo, 131–300 s inside the 4-worker CI pool, one pool timeout at 300 s in five observed runs), and a CPU profile of it shows that the time is in the engine, not the test: | Self time (of 128 s CPU) | Where | | --- | --- | | 44 s | `evaluateRulesetSheet` and helpers in `packages/shared/src/features/rulesets/sheet-math.ts` | | 31 s | `packages/shared/src/features/rulesets/live-state.ts` (`listRulesetLivePools`, `resolveLive`, wound work) | | 29 s | zod, of which 22.8 s is **constructing** `ZodString`/`ZodType` inside `readStoredLiveStateAsIs` | Two causes: 1. `readStoredLiveStateAsIs` builds `z.string().max(...)` twice on every call (`keepValid(source.text, z.string().max(MAX_LIVE_TEXT_LENGTH), …)` and the same for `states`). It runs for every combatant on every read of a stored live state. 2. `resolveLive` → `listRulesetLivePools` → `evaluateRulesetSheet(definition, build)` (no live values) is called from the option enumeration and picker loops. Counted with an instrumented build: the regression makes **9.7 million** live-less evaluations for only **13,085** distinct `(definition, build)` pairs. One evaluation costs about 4 µs; the volume is the cost. The same code runs in the live server on the combat-director route, skill-check resolution, and the inventory and market services, so each ruleset combat turn pays this too. ## Proposed solution Two commits in one PR, the first mergeable on its own. **Commit 1 (near zero risk): build the two schemas once.** In `live-state.ts`, next to `liveNumber`: ```ts const liveTextValue = z.string().max(MAX_LIVE_TEXT_LENGTH); const liveStateValue = z.string().max(MAX_LIVE_STATE_VALUE_LENGTH); ``` and in `readStoredLiveStateAsIs` use `keepValid(source.text, liveTextValue, MAX_LIVE_TEXTS)` and `keepValid(source.states, liveStateValue, MAX_LIVE_STATES)`. Same schema, same validation, four lines. Measured: the regression drops from 123 s to 102 s solo. **Commit 2 (medium risk, so scoped and proven): cache the live-less sheet evaluation for the duration of one director command.** - In `sheet-math.ts`, keep the existing function body as `evaluateRulesetSheetUncached` and export `evaluateRulesetSheet` as a wrapper that, **only while a scope is open**, memoizes the `live === undefined` case in a `WeakMap<RulesetDefinition, WeakMap<RulesetSheetBuild, EvaluatedRulesetSheet>>`. Calls with live values are never cached. Export `withRulesetSheetEvaluationCache<T>(run: () => T): T` that opens a fresh map, runs, and always clears it in `finally` (nested calls reuse the open scope). - Open the scope in `commandRulesetCombatDirector` (`packages/server/src/services/game/ruleset-combat-director.service.ts`) around its body. Builds are not edited during a command (fight creation, sheet import and the creature-sheet hold run outside it), which is what makes an identity-keyed cache sound there. Outside a scope the function behaves exactly as today. - Fix the one known clone-then-edit site, which a probe of this cache found: in `packages/shared/src/features/ruleset-combat/hold.ts` (health clamp, near line 525) the code clones `proposed`, evaluates the **clone** through `resolveRulesetValueRef(definition, sheet, { field: field.id })`, then writes `sheet.fields[field.id] = …` and evaluates it again. Read `current` from `proposed` (identical before the write) so the clone is only evaluated after its edit. With a globally enabled cache this is the only failure in the 269 `ruleset-combat-*` and `game-ruleset-*` regressions (`game-ruleset-combat-creature-sheets` reported "is now 200" instead of "is now 67"). - Audit the other in-place writes to a build so none evaluates the object before writing to it: `hold.ts` lines ~206, 260, 323, 472; `sheet-builder.ts` ~1402, 1408, 2078–2089; `sheet-math.ts` ~151; `live-state.ts` ~1043. All are clone-then-edit builders and all passed the probe, but the rule "evaluate a build only after its last write" should be stated in a comment on the cache. - Regression proof, `scripts/regressions/ruleset-sheet-evaluation-cache.regression.ts`: (a) inside `withRulesetSheetEvaluationCache`, evaluating the same `(definition, build)` twice returns the same object and a third call with live values does not; (b) outside the scope two calls return distinct objects; (c) the `hold.ts` health clamp, run **inside** the scope on a creature whose health is outside its tier, still reports the clamped maximum; (d) a nested scope does not clear the outer one. Keep the file deterministic and under a second. - One-off verification for the PR, not shipped: run the full suite once with the cache enabled globally and every cached object deep-frozen (`Object.freeze` recursively) so any aliasing write throws. The probe run of this found no frozen-object writes. Measured with both commits applied: the regression runs in **60 s solo** (from 123 s), with 9.7 million evaluations collapsing to 13,085 misses. Outputs are byte-identical; the only way the cache can change behaviour is the clone-then-edit pattern above, which the scope, the fix and the regression close. ## Alternatives considered - A global, always-on identity cache: simplest, but it is exactly what the probe broke on, and every future clone-then-edit site would silently read stale numbers. The command scope bounds the hazard to code that runs inside one command. - Passing an evaluated sheet down through `listRulesetLivePools` and the option loops: correct and explicit, but touches dozens of call sites in `encounter.ts`, `options.ts` and `resolve.ts` for the same result. - A structural cache key (hashing the build): safe against in-place edits, but hashing a build per call costs more than the 4 µs evaluation it would save. - Only splitting or trimming the regression file: hides the cost instead of removing it from the server's hot path. ## Additional context - Profile and probe numbers come from PR #8033 work (issue #8032), on a clean worktree of `staging` at 4d67fe75b, Node 24.15. The regression's own lane effect: shard 1 of `complete-node-regressions` stops being the longest shard and the 300 s pool timeout (seen in run 39664968247, job 119474763718) cannot recur. - Related: #8037 widens the two pool timeouts in the harness so it can land immediately; #8038 splits the regression file and is only needed if this issue does not land. - Callers never mutate an evaluated sheet (grep for writes to `evaluated.*` finds none in `packages/`), and the client already memoizes sheet evaluation per render (`GameRulesetSheet.tsx`), so no client change is needed. ## Template check Please **uncheck (untick)** the box below before submitting so we know you read the template. It is intentionally pre-checked: - [ ] I DID NOT read this template and provide the requested details.
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#7533
No description provided.