Skip to content

recipes: compile structural schema validators once - #1097

Merged
juliankang4 merged 1 commit into
midagedev:mainfrom
juliankang4:dgx-spark-q38-spd-t0-wall
Nov 1, 2026
Merged

juliankang4 merged 1 commit into
midagedev:mainfrom
juliankang4:dgx-spark-q38-spd-t0-wall

Conversation

@juliankang4

Copy link
Copy Markdown
Collaborator

기록 검사기가 구조 스키마를 값마다 다시 해석하던 것을 한 번만 해석하도록 바꿔, 기존 key inputs 검사 시간을 약 4.4% 줄였습니다.

What and why

tools/bloomery/reach_cache.py validated every structural cache field by walking the annotation again for each value (_typed(value, annotation)). The recipes key self test runs that check very many times, and the annotation analysis (origin, args, dataclass lookup) was repeated on each call. _typed(annotation) now builds a checking closure once per annotation and caches it. Every value, field and element is still checked on each call with the same exact-type rules and the same order, and nothing about a value or its result is cached. _schema_shape is folded into _typed and removed. No test, case, assertion, gate or tolerance changed.

On the same machine and the same existing key inputs section, the median goes from 200.562 s to 191.761 s (4.388% shorter), and the base and head ranges do not overlap (table below).

Release notes: Under the hood: the recipe key analysis checks its cached structural graph faster, which shortens the just contrib-check t0 run.

Code shape

The review reads these first. A box left unticked needs one line of why.

  • No second copy. Logic two models (or two call sites) share has one common owner; I lifted it there instead of
    copying it (AGENTS.md "Common code first", docs/rust-quality.md R14). Where I found an existing copy, I
    named it below.
  • Model code holds only architecture facts. A model's own files carry only what its architecture forces
    (tensor shapes, the attention kind, the quant). A common owner gained no per-model branch, flag or trait method.
  • Dead code is gone. Nothing I made unused is left behind (functions, flags, gate clauses, docs).
  • No silent failure. Undefined input is a named error or panic, never a defined-looking output.
  • Comments state what is true now. No dates, issue numbers or how a bug was found (tools/check-comments.sh).
  • No relaxed gate. No band, tolerance or lint moved to make a check pass; a re-pin carries PIN(YYYY-MM-DD):
    and its reason.
  • cargo fmt and cargo clippy are clean on what I touched; the lint count did not go up.

Duplication found or removed (path:line), or "none": none. _schema_shape in tools/bloomery/reach_cache.py is removed.

What I ran

Base b8a8dcc4de75239bcca63563fdc7931c8750f336 (upstream/main), head 397730aa96b0a590771d6ac52bfbbcbe59bdcff2. CPU only, Python 3.14, no profiler. The change does not reach a GPU gate or the engine binary.

The A/B runs the existing key_self_test(..., "inputs") section (24 checks) in a fresh Python process per arm, base and head alternating, three rounds each, then four existing regression tests for the structural cache. NR_BASE_WT is a checkout of the base commit; the working directory is the head checkout.

set -e
free -h
python3 -u - <<'PY'
import json, os, statistics, subprocess, sys
from pathlib import Path
head = Path.cwd()
base = Path(os.environ["NR_BASE_WT"])
driver = "import json, sys, time\nsys.path.insert(0, \"tools\")\nimport recipes as r\nfails = []\ncount = 0\ndef expect(ok, what):\n    global count\n    count += 1\n    if not ok:\n        fails.append(what)\nstart = time.monotonic()\nside = r.make_side(r.ROOT)\nr.key_self_test(expect, side, \"inputs\")\nprint(json.dumps(dict(arm=sys.argv[1], round=int(sys.argv[2]), seconds=time.monotonic()-start, checks=count, failures=fails)), flush=True)\nsys.exit(bool(fails))\n"
values = {"base": [], "head": []}
checks = set()
for round_no in range(1, 4):
    for arm in (("base", "head") if round_no % 2 else ("head", "base")):
        print("MEASURE start arm=%s round=%s" % (arm, round_no), flush=True)
        done = subprocess.run([sys.executable, "-u", "-c", driver, arm, str(round_no)], cwd=base if arm == "base" else head, text=True, capture_output=True)
        print(done.stdout, end="", flush=True)
        if done.stderr: print(done.stderr, file=sys.stderr, end="", flush=True)
        if done.returncode: sys.exit(done.returncode)
        row = json.loads(done.stdout.splitlines()[-1])
        values[arm].append(row["seconds"])
        checks.add(row["checks"])
if len(checks) != 1:
    raise RuntimeError("existing key-inputs checks differ between arms: " + repr(checks))
before, after = (statistics.median(values[k]) for k in ("base", "head"))
print("A/B key-inputs " + json.dumps(values), flush=True)
print("A/B median base=%.3fs head=%.3fs gain=%.3f%% checks=%s nonoverlap=%s" % (before, after, 100*(before-after)/before, next(iter(checks)), max(values["head"]) < min(values["base"])), flush=True)
PY
RECIPES_KEY_TEST_FILTER='malformed_and_foreign_cache,repeated_key_validation,analysis_code_edited,module_added_between_eager' python3 tools/recipes-key-test.py --self-test

Output:

A/B key-inputs {"base": [198.83777694002492, 200.5616269040038, 207.32762870198349], "head": [190.8608626020141, 191.76089633401716, 197.65085299598286]}
A/B median base=200.562s head=191.761s gain=4.388% checks=24 nonoverlap=True
test_analysis_code_edited_after_import_never_emits_a_skippable_key (__main__.RecipeKeyCLI.test_analysis_code_edited_after_import_never_emits_a_skippable_key) ... ok
test_malformed_and_foreign_cache_recompute_safely (__main__.RecipeKeyCLI.test_malformed_and_foreign_cache_recompute_safely) ... ok
test_module_added_between_eager_discovery_and_key_is_included_or_refused (__main__.RecipeKeyCLI.test_module_added_between_eager_discovery_and_key_is_included_or_refused) ... ok
test_repeated_key_validation_reuses_stable_source_hashes (__main__.RecipeKeyCLI.test_repeated_key_validation_reuses_stable_source_hashes) ... ok

----------------------------------------------------------------------
Ran 4 tests in 16.264s

OK
Metric Base (s) Head (s) Difference Ranges overlap
key inputs section, median of 3 200.562 191.761 4.388% shorter no (base 198.838 to 207.328, head 190.861 to 197.651)

AI help

AI 코딩 에이전트가 코드를 작성한 후 설명을 썼고, 테스트를 마쳤습니다. diff 리뷰와 PR 초안 리뷰는 제가 직접 했습니다.

@github-actions github-actions Bot added the tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo label Nov 1, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: CLEAN: No must-fix finding remains in the compiled-validator change.

Non-blocking

⚠ Timing evidence: tools/bloomery/reach_cache.py:240. The PR's A/B names b8a8dcc/397730a; this review covers cd7d880/019e5f1.
Confirm that the measured revisions contain the same validator change, or attach output for the reviewed pair so the speed claim can be tied to this change.

Checked

Duplicates: _schema_shape is removed; its annotation analysis is folded into _typed. No new types or constants.
Complexity: no Rust functions changed; no crapper results.
Silent failure: the 3 changed validation conditions still raise ValueError before hydration; prepare catches malformed-cache errors and recomputes.
Tests: no tests changed. The PR reports four cache regressions passing; the validator did not rerun them.
Gates: no tests, cases, thresholds or pins changed.
Escape catalog: no patterns matched.

Notes

Dryer and crapper did not run because no Rust file changed.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

@juliankang4

Copy link
Copy Markdown
Collaborator Author

The review is done and the contribution check passed, so I'm merging this.

@juliankang4
juliankang4 merged commit e9f238b into midagedev:main Nov 1, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant