Repository navigation
fix(save): validate per-build reserved maps at the schema gate - #568
itsmiso-ai wants to merge 2 commits into
Conversation
Reject a present-but-malformed build.reserved — non-Dictionary values
and non-numeric quantities — through the existing _validate_numeric_dict
helper, the same rule delivered already follows. The sim dot-reads the
map via build.get("reserved", {}).get(resource, 0) and casts it in
_clean_stale_reservations, so malformed values must not load. Missing
keys (older saves) and valid reservation maps stay compatible.
Address the PR #568 review finding: _clean_stale_reservations() credits saved per-build reserved quantities straight to state.resources, so a negative reservation would drain the stockpile. Reuse _validate_numeric_dict() with a quantity bound, matching the existing reserved_resources check.
There was a problem hiding this comment.
{"schema":"review-handoff/v1","review_id":"5721e350efae956f","head_sha":"8aef920a3c1dcf9c29492773d7c6ab7d17022a8e","verdict":"approve","review_result":"findings","required_checks":"complete","items":[{"id":"b0461099d2a962a3bc299b7e8c8d7bde8ade1ed74c08afff6b596d4216595f11","severity":"minor","category":"docs","path":"scripts/game_state.gd","line":505,"message":"The PR description's handoff states \"non-negativity not enforced per-build\" and describes `_validate_numeric_dict(build, \"reserved\")`, but the head commit passes `true` and the gate now rejects negative quantities — the description no longer matches the shipped behavior."},{"id":"bf180a1178c022388d2f18c771287e393727f9ad177a77925dde5fea8f0e384c","severity":"minor","category":"docs","path":"docs/DESIGN.md","line":94,"message":"`docs/DESIGN.md` lists the persisted build shape without a `reserved` entry, so the now-gated per-build reservation field is undocumented in the save-format reference."},{"id":"b62c9e976c68452917928b4110b54bb65e4f99777322a755224e2131bf129787","severity":"info","category":"other","path":"scripts/colony_sim.gd","line":867,"message":"`backfill_colony_state()` still leaves `reserved` untouched, so state that bypasses the gate (direct assignment) can still raise on the `var reserved: Dictionary = build.reserved` cast — explicitly out of this issue's gate-only scope."}],"items_total":3,"items_truncated":false,"unresolved_requirement_ids":[],"unresolved_requirement_ids_total":0,"unresolved_requirement_ids_truncated":false,"unresolved_requirement_ids_source_total":0,"unresolved_required_checks":[],"unresolved_required_checks_total":0,"unresolved_required_checks_truncated":false,"unresolved_required_checks_source_total":0,"unresolved_review_obligations":[],"unresolved_review_obligations_total":0,"unresolved_review_obligations_truncated":false,"derived_obligation_state":null}AI Automated Review
✅ Automated recommendation: APPROVE
Full PR review.
Analysis engine: MiniMax-M3.1-Flash (anthropic) — primary route · pr-reviewer-action v3.11.2
Findings (2 minor, 1 info)
| Severity | Location | Finding |
|---|---|---|
| Minor | scripts/game_state.gd:505 |
The PR description's handoff states "non-negativity not enforced per-build" and describes `_validate_numeric_dict(build, "reserved")`, but the head commit passes `true` and the gate now rejects negative quantities — the description no longer matches the shipped behavior. |
| Minor | docs/DESIGN.md:94 |
`docs/DESIGN.md` lists the persisted build shape without a `reserved` entry, so the now-gated per-build reservation field is undocumented in the save-format reference. |
| Info | scripts/colony_sim.gd:867 |
`backfill_colony_state()` still leaves `reserved` untouched, so state that bypasses the gate (direct assignment) can still raise on the `var reserved: Dictionary = build.reserved` cast — explicitly out of this issue's gate-only scope. |
Recommendation: approve — the schema gate now rejects malformed per-build reserved maps exactly where issue PR 553 asked, and the previously open non-negativity gap is closed at the head commit.
What I verified. validate_save_schema() rejects a present non-dictionary reserved, a non-numeric quantity, and a negative quantity at scripts/game_state.gd:500-507, reusing the shared _validate_numeric_dict helper, so the rejection reason matches the delivered style. Every load path funnels through the same gate (GameState.load_game() → _validate_and_apply_save(), scripts/game_state.gd:280-309, and the web/localStorage branch), and main.gd:1036-1070 (load_saved_game()) plus backup restore (game_state.gd:1236-1248) route through it, so the new load-path assertions exercise the same gate the game uses. The sim readers cited by the PR are real: colony_sim.gd:587 dot-reads build.get("reserved", {}) and colony_sim.gd:867 casts var reserved: Dictionary = build.reserved. Runtime never writes a negative reservation (_shift_build_reserved clamps with maxi(..., 0), colony_sim.gd:742-744), so the newly enforced non-negativity bound cannot reject a save the game itself produced.
Linked Issue Fit. Issue PR 553's acceptance — reject present non-dictionary reserved and nonnumeric amounts at the shared gate, keep absent/valid maps loadable, and add regression tests including the shared load path — is met by flow_malformed_reserved_rejected() (tests/test_save_schema_defaults.gd:471-556), which covers numeric/string reserved, a nonnumeric quantity, negatives, the missing-key acceptance case, and the load path (malformed rejected with the running colony untouched, valid map preserved).
Tool Harness Findings. 40 read-only calls confirmed the gate, the sim readers, the load-path wiring, and the test coverage; no unverified path was relied on for the verdict.
Minor issues (description drift, missing docs row) are in the findings array.
Courier run handoff (issue-553 / docs follow-up)Re-run to settle the assigned review scope on this PR. No code or body change was required; both review findings were already addressed at head Findings disposition
Settled decisions (unchanged): gate-only fix; one numeric-map rule via Local checks (head
Published state: head Remaining external verification: none from this run; CI already green. Independent PR review remains deferred to the dedicated reviewer. |
Closes #553
What changed
validate_save_schema()now checks each build's optionalreservedmap: it must be aDictionarywith non-negative numeric quantities, or the save is rejected at the shared load gate. A missing key (older saves) and valid maps keep loading.scripts/game_state.gd: in the per-build loop, reuse_validate_numeric_dict(build, "reserved", true). Shape/type follows thedeliveredrule from issue fix(save): heal per-build delivered/progress, reject unknown build kinds #552; the new quantity bound answers the PR review finding that a negative reservation is subtracted fromstate.resourcesby_clean_stale_reservations()(colony_sim.gdcredits each saved quantity straight to the stockpile)._validate_numeric_dict()takes an optionalrequire_non_negativeflag (defaultfalse), soresources,harvested, anddeliveredkeep their current behavior.tests/test_save_schema_defaults.gd:flow_malformed_reserved_rejected()covers the shape cases (numericreserved, stringreserved, non-numeric quantity naming the resource), the new bound (negative int with a pinned reason, negative float), acceptance (missing key, valid map with a zero entry), and the shared load path (load_saved_game()rejects malformed and negative maps and leaves the running colony alone; a valid map loads untouched).Why it matters
The sim dot-reads the map on tick paths (
colony_sim.gd:int(build.get("reserved", {}).get(resource, 0))in the haul/need math) and casts it withvar reserved: Dictionary = build.reservedin_clean_stale_reservations(). AStringor numericreserved, or a value like{"wood": "many"}, crashed the tick with a Variant error. A value like{"wood": -5}did not crash: the stale-reservation cleanup added it tostate.resources, draining 5 wood from the stockpile on the first tick after load. Per the standing policy, malformed saved data is rejected at the gate, never rewritten by the validator.Invariants this change must keep, and every path enforcing the same rule
build.reservedis absent, or aDictionaryof non-negative numeric quantities. Enforced byvalidate_save_schema()(scripts/game_state.gd), the only schema gate. Every load path runs it: desktopGameState.load_game(), the web/localStorage branch, and both share_validate_and_apply_save()(issue [P2] Web localStorage load path skips save-schema validation and migration #313). Startup cold-load, the Load Game button, and Restore Backup (main.gd_confirm_restore_backup()→load_saved_game()) all funnel through it — covered by the load-path asserts in the new flow. No other path can put a saved reservation into the credit loop._shift_build_reserved()(colony_sim.gd) is the single writer for pickup (+1), delivery (-deliver), and break refunds (-carried), and it clamps withmaxi(..., 0).release_reservation()clamps the top-level counter withmaxi(0, ...)the same way. So the gate is the only place a negative could enter, and it now refuses one.reservedis rejected at the gate, not healed. Matches the delivered/progress policy from issue fix(save): heal per-build delivered/progress, reject unknown build kinds #552: the validator rejects,backfill_colony_state()heals only state that bypassed the gate, and backfill intentionally leavesreservedalone because the sim treats a missing map as{}everywhere (build.get("reserved", {})). Untouched by this diff.reserved_resourceskeeps its own existing check (Dictionary, numeric, non-negative) atscripts/game_state.gd; the new flag makes the per-build map match that bound instead of replacing that block.resources/harvested/deliveredquantity bounds are unchanged. They call_validate_numeric_dict()without the flag, so their rejection reasons and acceptance stay as pinned intests/test_runner.gd(test_save_schema_resources_harvested). Negativedeliveredis a real but separate gap (it inflates the remaining need rather than draining the stockpile): tracked in [P3] Schema gate accepts negative per-builddeliveredquantities, which inflate the remaining build need #569.reserved(all pre-reservation saves) and saves with valid maps, including a zero quantity, must keep loading — covered by the acceptance asserts.Validation
mise exec -- just --justfile .justfile validate(full CI matrix, 40 GDScript suites) — exit 0; every suite reported0 failed, and noParse ErrororSCRIPT ERRORappeared in the log. Godot 4.7.1-stable headless (Linux binary fromgodot-toolchain.json, sha256 verified), cwd/workspace. The only later edit was one test comment, re-checked by the suite below.tests/test_save_schema_defaults.gdalone at head8aef920: 108 passed, 0 failed (6 asserts added for the non-negative bound).CI is left pending for the operator; no external checks were awaited.
Handoff
reserved); reuse_validate_numeric_dictwithrequire_non_negativeso there is one definition of the numeric-map rule and the reason readsbuild[N]: 'reserved.<res>' must be non-negative, matching the helper's existingmust be numericshape; no clamp added in_clean_stale_reservations()because the gate now refuses the input and the runtime writer already clamps.{"wood": 1.0};_validate_numeric_dictaccepts int and float alike, and the bound comparesfloat(value) < 0.0.scripts/game_state.gd(per-buildreservedquantities unchecked for non-negativity) is addressed at8aef920. Independent review is deferred to the dedicated PR reviewer; treat it as pending.