Skip to content

refactor(state): normalize current_best once at load and drop its reader-side dict guards - #1883

Open
fengshaoyi-amd wants to merge 7 commits into
lean/shafeng/cc-writeback-config-envfrom
lean/shafeng/cc-current-best-normalize
Open

fengshaoyi-amd wants to merge 7 commits into
lean/shafeng/cc-writeback-config-envfrom
lean/shafeng/cc-current-best-normalize

Conversation

@fengshaoyi-amd

@fengshaoyi-amd fengshaoyi-amd commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor
  • Description: what and why

Stacked on #1877. The base is lean/shafeng/cc-writeback-config-env, so the diff here is only the commits on top of it. It will be retargeted to main once #1877 merges.

SharedState.current_best is declared dict[str, Any], its dataclass default is {}, and both writers in writeback.py assign dict literals. The one way a non-dict got in was a state.json whose current_best was null or another non-object, because from_dict passed it through. So 44 readers across 14 modules re-checked the type, each with its own fallback. from_dict now normalizes the field the way it already normalizes pending_kernel_integrations and the other dict fields, and the readers trust that. Main's #1890 added one more, roofline_recipe: it takes a real SharedState, so it reads state.current_best directly.

  • A reader of a real SharedState (self.current_best, state.current_best, self.shared_state.current_best) uses the field directly. That includes six reads that applied or {} and then isinstance to the same value.
  • A reader that takes a duck-typed or optional state keeps getattr(state, "current_best", None) or {} for an absent state and loses only the type check.
  • Single-use aliases are inlined. The cb_now alias in _promote_explore stays, because it holds the pre-promotion dict that later lines read.
  • Kept, because a non-dict or absent value means something there, or the input is not SharedState.current_best:
    • gap_for_state: no state means no gap, so it returns None.
    • RemoteRecipe from_state: raises its validation error by contract.
    • The two report.py reads: they read the report payload, not SharedState.
    • geak_config: its current_best is a number.
    • first_positive_tput: generic over several sources.
    • Checks on fields inside current_best (extra_envs, measurement) are untouched.

Not included: twelve reads of a real SharedState that spell (x.current_best or {}) with no type check. The invariant makes them redundant too. They are left out to keep this diff to the audited guards.

  • Linked issue(s): none

  • Tests: added/updated? commands run?

Added: test_a_non_object_current_best_loads_as_empty, parametrized over None, [], a string and a number.

Updated: two _MoreState doubles in test_critic_verdict_map.py subclassed a dataclass without @dataclass, so their current_best was a dataclasses.Field object. The removed stack_base_params guard had hidden that. They are now dataclasses, like their sibling doubles.

Every changed function was compared between base and head after mechanically stripping, on both sides:

  • the current_best isinstance checks;
  • or {} on current_best;
  • dead defaults;
  • single-use aliases.

After merging the updated base at 794d477d3, the same comparison covers 36 functions. 33 match once the current_best guards are stripped, including roofline_recipe. Three differ: from_dict, which is the normalization, and the two narrowed signatures (stack_base_params, _current_best_throughput). This also covers the dedent in _fill_integrate_defaults_from_state and _build_recipe_attrs_from_state.

Checks run locally on Windows:

  • ruff check and ruff format --check: clean.
  • lint-imports: 7 kept, 0 broken.
  • python scripts/code_metrics.py --base-ref origin/lean/shafeng/cc-writeback-config-env: PASSED.
  • mypy on the 13 source files of the original change: same findings as the base. analysis_failures.py is the file added since; the edit only drops a guard on a parameter typed Any.

pytest over the 76 test files that exercise the changed functions, one roofline test deselected because on Windows its os.kill(pid, 0) probe sends Ctrl+C to the whole console: 3325 passed, 3 skipped, 92 failed. All 92 fail the same way on the base commit 794d477d3, each for a Windows-only reason: bash-based fakes, symlink privileges, path separators, encoding, or git path detection. test_promote_shared_state_lock.py hangs on Windows and is left to CI, as is the full suite.

  • Size/complexity triggers crossed: none.

Every touched unit shrinks:

  • _resolve_forge_server_log drops under the cyclomatic ceiling (it was 21).

  • 28 entries are lowered, for example:

    • _fill_integrate_defaults_from_state: cognitive 102 → 92.
    • _build_recipe_attrs_from_state: 48 → 41.
    • _promote_explore: 237 → 231.
    • lift_to_current_best: 148 → 144.
  • If this simplifies or refactors: which mechanism was removed, which contract was preserved, and the tests that show it:

Removed: 44 reader-side type checks on current_best and the fallback each one carried. The invariant is now stated once, in from_dict.

Preserved: each reader's output for every state.json that loads. The existing suites pin it:

  • profile identity: test_shared_state_units;

  • KB recipe writes: test_coordinator_kb_writes, test_recipe_sedimentation;

  • integrate defaults: test_integrate_payload_defaults, test_kernel_request_handlers_units;

  • GEAK handoff: test_geak_handoff_*;

  • conc sweep: test_conc_sweep*;

  • the load shape: the new test.

  • Observable effect:

A state.json whose current_best is null, a list, a string or a number now loads as {}, and the next save writes {} back. The readers this PR touches already treated such a value as "no current best", so a run makes the same decisions. Readers that guarded only against None, with (x.current_best or {}).get(...), used to raise AttributeError on a truthy non-dict; they now see {}.

  • Breaking changes: no.

stack_base_params narrows its annotation from Any to dict[str, Any] | None. Every caller passes one of those.

  • PR addresses single concern: yes. The concern is the current_best dict invariant: the loader enforces it once and the readers rely on it.

  • Root cause is upstream (Magpie/TraceLens/GEAK/IntelliKit/AgentKernelArena), ticket filed: no

fengshaoyi-amd and others added 2 commits October 14, 2026 17:59
SharedState.from_dict now normalizes current_best the way it already
normalizes the other dict-valued fields. Together with the dataclass
default and the two writers in writeback, which only assign dicts, every
SharedState now carries a dict in current_best whatever state.json holds.

Co-authored-by: Cursor <cursoragent@cursor.com>
Every SharedState carries a dict in current_best, so the 43 readers
that re-checked it drop the check. A reader of a real SharedState uses
the field directly; a reader that takes a duck-typed state keeps
getattr(state, "current_best", None) or {} for an absent state and
loses only the type check. Checks on the fields inside current_best
(extra_envs, measurement) stay.

The code-metrics baseline is tightened for the 29 entries that went
down.

Co-authored-by: Cursor <cursoragent@cursor.com>
@github-actions

github-actions Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

Code metrics gate: PASSED

Judged: the 17 files this change touches. Files it does not touch never fail it; anything found there is listed under Outside this change for information.

Dimension Limit New Worse Baseline out of date Baseline entries vs base
Cyclomatic complexity fails > 20 0 0 0 69 -1
Cognitive complexity fails > 30 0 0 0 280 +0
Function length (lines) fails > 80 0 0 0 449 +0
Nested block depth fails > 5 0 0 0 27 +0
Module length (lines) warns > 800, fails > 1200 0 0 0 53 +0
Duplicated lines per file fails > 0 0 0 0 117 +0
Dead code (vulture) fails > 0 0 0 0 2 +0
Check Findings Effect
Comments 0
English only 0
Production code imports test code 0
Repeated literals 0
A1 Private name of another package 0
A8 Flag argument 0
A9 Tuple return 0
A10 Raw vocabulary comparison 0
A11 Hidden global write 0
A12 Pure forwarder 0
A12 Single-implementation abstraction 0

Module length warning: over 800 lines, within the 1200-line failure limit (not failing): 3

Module Lines Limit
src/hyperloom/orchestrator/phases/close.py 1000 warns > 800
src/hyperloom/orchestrator/specialists/dispatch.py 1058 warns > 800
src/hyperloom/orchestrator/state/_shared_state/render.py 948 warns > 800

Already over at the base (backlog, not this change's): 16

Unit Dimension Base Now
src/hyperloom/orchestrator/state/shared_state.py:97 resolve_graded_comparison Cognitive complexity 34 34
src/hyperloom/orchestrator/kernel/request_handlers.py:2987 _run_forge_gemm_tuning Cognitive complexity 125 125
src/hyperloom/orchestrator/loop/writeback.py:3470 WritebackCollaborator.build_env_spec Cognitive complexity 37 36
src/hyperloom/orchestrator/phases/kernel.py:1217 KernelPhase._run_geak_kernel_phase Cognitive complexity 132 130
src/hyperloom/orchestrator/state/_shared_state/render.py:730 _RenderMixin._format_variant_line Cognitive complexity 40 40
src/hyperloom/orchestrator/kernel/request_handlers.py:2987 _run_forge_gemm_tuning Cyclomatic complexity 57 57
src/hyperloom/orchestrator/phases/kernel.py:1217 KernelPhase._run_geak_kernel_phase Cyclomatic complexity 52 52
src/hyperloom/orchestrator/loop/writeback.py:3470 WritebackCollaborator.build_env_spec Function length (lines) 111 111
src/hyperloom/orchestrator/loop/writeback.py:4507 WritebackCollaborator.validate_geak_via_geak_harness Function length (lines) 187 187
src/hyperloom/orchestrator/phases/kernel.py:1909 KernelPhase._record_geak_candidate Function length (lines) 107 107
src/hyperloom/orchestrator/phases/kernel.py:1217 KernelPhase._run_geak_kernel_phase Function length (lines) 487 485
src/hyperloom/orchestrator/phases/kernel.py:2117 KernelPhase.promote_geak_from_candidate Function length (lines) 167 167
src/hyperloom/orchestrator/kernel/request_handlers.py:1 Module length (lines) 5149 5144
src/hyperloom/orchestrator/loop/writeback.py:1 Module length (lines) 4777 4771
src/hyperloom/orchestrator/phases/kernel.py:1 Module length (lines) 4299 4295
src/hyperloom/orchestrator/state/shared_state.py:1 Module length (lines) 2696 2692
80 findings in files this change does not touch

Outside this change (informational): 80

Unit Dimension Baseline Now
src/hyperloom/orchestrator/enablement/recipe/projections.py project_launch_evidence Cognitive complexity absent 36
src/hyperloom_kb/collect/mapping.py _experience Cognitive complexity absent 31
src/hyperloom_kb/schema.py FieldDeclaration.__post_init__ Cognitive complexity absent 32
src/kernelforge/cli/forge_loop_command.py _prepare_measurement_driver Cognitive complexity absent 36
src/kernelforge/cli/forge_loop_command.py _read_kb_warm_start Cognitive complexity absent 40
src/kernelforge/loop/runner.py IterationLoop._collect_session_candidate Cognitive complexity absent 44
src/kernelforge/loop/runner.py IterationLoop._rule_on_attempt Cognitive complexity absent 38
src/hyperloom_kb/tests/test_cli.py Duplicated lines per file absent 18
src/hyperloom_kb/tests/test_global_identity_and_pull.py Duplicated lines per file absent 13
src/hyperloom_kb/tests/test_local_state.py Duplicated lines per file absent 18
src/hyperloom/inference_optimizer/cli/__init__.py _reexport_session_environment Function length (lines) absent 112
src/hyperloom/inference_optimizer/cli/__init__.py _resolve_agent_lineup Function length (lines) absent 89
src/hyperloom/inference_optimizer/cli/__init__.py _resolve_run_topology Function length (lines) absent 92
src/hyperloom/inference_optimizer/cli/__init__.py _resume_session Function length (lines) absent 171
src/hyperloom/inference_optimizer/cli/__init__.py _seed_fresh_session Function length (lines) absent 183
src/hyperloom/inference_optimizer/multi_node/cli.py _restart_multinode Function length (lines) absent 107
src/hyperloom/inference_optimizer/multi_node/scripts/launch_multinode.py _build_parser Function length (lines) absent 84
src/hyperloom/inference_optimizer/multi_node/scripts/launch_multinode.py _spawn_rank_actors Function length (lines) absent 90
src/hyperloom_kb/http_service.py RequestHandler._dispatch Function length (lines) absent 91
src/hyperloom_kb/sync.py GlobalSync.pull Function length (lines) absent 86
src/kernelforge/cli/forge_loop_command.py _RunReporter.build_result Function length (lines) absent 91
src/kernelforge/cli/forge_loop_command.py _prepare_measurement_driver Function length (lines) absent 140
src/kernelforge/cli/forge_loop_command.py _read_kb_warm_start Function length (lines) absent 154
src/kernelforge/loop/knowledge_integration.py _measure_warmstart_field Function length (lines) absent 83
src/kernelforge/loop/runner.py IterationLoop._close_iteration Function length (lines) absent 135

...and 55 more; the job log lists every row.

Verdict computed by the gate scripts in /home/runner/work/_temp/code-metrics-gate, not by this tree's copy.

Thresholds and sources: [tool.hyperloom.code_metrics] in pyproject.toml. Tools: complexipy 8.0.1, jscpd 5.4.1, ruff 0.16.2, vulture 2.16.

@fengshaoyi-amd

Copy link
Copy Markdown
Contributor Author

/review

@github-actions

Copy link
Copy Markdown

Automated review started for head 37545f4. Progress: https://github.com/AMD-AGI/Hyperloom/actions/runs/38551918107

…sses

Two _MoreState doubles subclass the _BareSharedState dataclass without
the decorator, so their field(default_factory=dict) declarations left
dataclasses.Field objects on the class instead of dicts. The explore
materialize path reads current_best through stack_base_params, which
relies on it being a dict as it is on every SharedState. Decorate both
like their sibling doubles.

Co-authored-by: Cursor <cursoragent@cursor.com>
@github-actions

Copy link
Copy Markdown

Automated review: no verdict applied -- the PR head moved from 37545f4 to 08b215d during the review. Comment /review to retry. Run: https://github.com/AMD-AGI/Hyperloom/actions/runs/38551918107

PR #1883 -- refactor(state): normalize current_best once at load and drop its reader-side dict guards

What it does: A state.json whose current_best was null, a list, a string or a number was passed through by SharedState.from_dict unchanged, leaving 43 readers to re-establish the field's declared dict type with their own fallbacks. from_dict now normalizes the field to {} at load — the same normalization it already applies to pending_kernel_integrations — and the reader-side guards are deleted; such a state now loads and re-saves as an empty dict, and readers that previously raised AttributeError on a truthy non-dict now see {}.

Blocking issues: none

Checked: head-tree reads of shared_state.py (from_dict :1102, load_or_init :1052, field :472), writeback.py writers :1695/:2023, request_handlers.py, recipe_journal.py, forge_handoff.py, roofline_ceiling.py, _partition_shape.py, dispatch.py, experience_kb.py, close.py, kernel.py, render.py; tree-wide greps for every writer of .current_best, every remaining current_best or {} read and every caller of the reshaped stack_base_params/_current_best_throughput; diff.txt re-checked per family; comments.txt (code-metrics report) read | Ran: direct SharedState.from_dict runs on base e611a05 (non-dict passthrough confirmed) and head; pytest at head: test_shared_state_evolution (26), test_integrate_payload_defaults + test_kernel_request_handlers_units + test_shared_state_units (384), test_geak_revalidation_dispatch + test_recipe_sedimentation + test_conc_sweep (215), test_close_stack_revalidation (9), test_specialist_auto_retry (23) — all pass | Base: e611a05 | Head: 37545f4

…-env' into lean/shafeng/cc-current-best-normalize

Co-authored-by: Cursor <cursoragent@cursor.com>

# Conflicts:
#	scripts/code_metrics_baseline.txt
…-env' into lean/shafeng/cc-current-best-normalize

Brings in main's phase-budget (#1873) and gemm-tune MoE routing (#1862)
fixes through the base branch. The baseline conflicts are adjacent
entries both sides tightened; each takes the lower value, which is the
merged tree's measured value except for request_handlers.py's
module-lines. That entry keeps the base's 5138: main's file is 5149
lines because the two fixes landed one after the other, each recording
its own count, and this branch's 5144 is five below it, so the excess is
the base's backlog and the baseline does not grow.
@chaojhou

Copy link
Copy Markdown
Collaborator

PR #1883 -- refactor(state): normalize current_best once at load and drop its reader-side dict guards

What it does: SharedState.current_best is declared a dict and both runtime writers assign dict literals, but from_dict passed a non-object current_best from state.json through, so 43 readers in 13 modules re-checked its type. from_dict now normalizes a non-dict current_best to {} the way it already normalizes the other dict fields, and the readers drop the type check (readers of a duck-typed or optional state keep getattr(..., None) or {}). A non-object current_best now loads as {} and the next save writes {}.

Blocking issues: none

Checked: diff of all 16 files; every writer of current_best at head (writeback.py:1695, writeback.py:2023, the enablement record_keep field tuples, constructor and replace call sites) and its history (no nullable declaration or None write in any non-test module); SharedState.load_or_init -> from_dict as the load path and the field declaration; each reader whose guard was removed, including the local current_best in _fill_integrate_defaults_from_state; stack_base_params callers; the _MoreState doubles in test_critic_verdict_map.py; writes to current_best added by open PRs (all dict literals in tests) | Ran: python pr_tools/c901.py (ruff C901 counting; ruff is not installed here): _resolve_forge_server_log 21->20, _fill_integrate_defaults_from_state 27->26, lift_to_current_best 44->43, from_dict 8->9; direct SharedState.from_dict call on the head tree: None, [], "880.0", 880.0 -> {}, a dict is kept unchanged; the head moved from 35fe346 to 6d4218a by merging the updated #1877 branch, and the PR's own hunks compare identical across it apart from the re-aligned shared_state.py module-lines entry, while the merged main adds no current_best writer outside tests | Base: 5836d15 (head of #1877, the stacked base) | Head: 6d4218a

LGTM

@chaojhou

Copy link
Copy Markdown
Collaborator

Non-blocking suggestions. None of these blocks merging; each removes a defensive check rather than adding one.

  1. Finish the replacement here: the twelve (x.current_best or {}) reads of a real SharedState listed under "Not included" are redundant under the invariant this PR establishes. Leaving them gives the field three spellings (direct, or {}, getattr(...) or {}), and the next reader cannot tell which one the invariant allows. Each is a one-line change within the same concern.
  2. specialists/dispatch.py:223: state is self.shared_state, typed SharedState, and the same function calls state.find_gap and reads state.gpu_type directly. By the description's own rule it should read state.current_best.get("tput") rather than getattr(state, "current_best", None) or {}. More generally, where getattr(..., None) or {} survives only because a test double lacks the field, fixing the double (as done for _MoreState) beats keeping the fallback in production code; the root is helpers typed state: Any, such as inject_stack_base_params.
  3. No module has ever declared SharedState.current_best nullable or written None to it (git log -G over the non-test code finds only the unrelated numeric current_best parameter of geak_config), and both runtime writers assign dict literals. A non-dict on disk is therefore a hand-edited or damaged state.json, which from_dict now rewrites to {}, and the next save persists that without a trace. The same loader refuses damaged crash evidence with ValueError (_validate_resume_fields); refusing here too, or at least logging a warning, keeps the damage visible. Either way the four parametrized shapes in the new test all stand for the same damaged-file case, so one is enough.

…-env' into lean/shafeng/cc-current-best-normalize

The baseline conflicted only on adjacent lines each side lowered: every
entry keeps the lower value, which is also the measured one.
SharedState.current_best is always a dict, so roofline_recipe reads it
without an isinstance guard, like every other SharedState reader.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants