engine-qwen35-cuda: the GPU proofs use leleka-gateway-text instead of compiling its prompt.rs as a module; 23 more #[path] modules become ordinary; orphan renderer copy to garbage

rust_modtree.py: a cfg(feature = "preview-path") attribute was taken for a #[path] attribute (two modules were invisible to the tools).
path_to_modules.py keeps a file that two parents declare (native_down_pair_io.rs, one copy of the state each).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-11-14 20:19:50 +01:00
co-authored by Claude Sonnet 5.5
parent 64669ed528
commit b66ed637ff
32 changed files with 415 additions and 396 deletions
+150
View File
@@ -0,0 +1,150 @@
"""Remove `#[allow(unused_imports)]` and what it hid (STRA-338 stage 10, ratchet `allow-unused-imports`).
Usage: python scripts/dev/drop_allow_unused.py WORKTREE CRATE_DIR PACKAGE [--keep-test-only]
The attribute sat on re-exports (`pub use child::name;`) that the splits kept so the old paths still resolve. Without it the compiler
says which of them nobody uses:
* a name unused in the unit-test build is unused everywhere (that build compiles all code and the tests): it is deleted from its
`use` statement, the statement goes when nothing is left;
* a name used by the test build only is kept as `#[cfg(test)] use ..;` (the statement is split when it names others too).
One round is `cargo check --lib --bins` and `--tests`; the loop repeats because deleting a re-export can make another one unused.
Offline refactoring aid, not part of the product.
"""
import collections
import json
import pathlib
import re
import sys
sys.path.insert(0, str(pathlib.Path(__file__).parent))
import explicit_imports as ei # noqa: E402
from unglob_by_errors import PLATFORM_FILES # noqa: E402
ALLOW = re.compile(r"^[ \t]*#\[allow\(unused_imports\)\][ \t]*\n", re.M)
USE_STATEMENT = re.compile(r"(?ms)^(?P<attrs>(?:[ \t]*(?:#\[[^\n]*\]|///[^\n]*)\n)*)(?P<head>[ \t]*(?:pub(?:\([^)]*\))?[ \t]+)?use[ \t]+)"
r"(?P<body>[^;]*?);[ \t]*\n")
NL = chr(10)
NAME = re.compile(rf"(?:\bas\s+)?({ei.IDENT})\s*$")
def bound(item):
"""The name an import item binds (`a::B` -> B, `a::b as c` -> c); None for globs and `as _`."""
m = NAME.search(item)
return m.group(1) if m and not item.rstrip().endswith("as _") else None
def statement_names(body):
"""[(name as it is bound, source text of the item)] of `a::b::{c, d as e}` or `a::b::c` (one level of braces)."""
body = body.strip()
brace = body.find("{")
if brace < 0:
return [(bound(body), body)], body, None
prefix, inner = body[:brace], body[brace + 1 : body.rindex("}")]
items = [i.strip() for i in inner.split(",") if i.strip()]
return [(bound(i), i) for i in items], prefix, items
def build(attrs, head, prefix, items):
"""One `use` statement for `items` below `prefix`, wrapped at 120 columns like rustfmt does."""
indent = head[: len(head) - len(head.lstrip())]
if len(items) == 1 and not items[0].startswith("self"):
return f"{attrs}{head}{prefix}{items[0]};{NL}"
one = f"{head}{prefix}{{{', '.join(items)}}};"
if len(one) <= 120:
return f"{attrs}{one}{NL}"
lines, cur = [], indent + " "
for item in items:
if len(cur) + len(item) + 1 > 120:
lines.append(cur.rstrip())
cur = indent + " "
cur += item + ", "
lines.append(cur.rstrip())
return f"{attrs}{head}{prefix}{{{NL}{NL.join(lines)}{NL}{indent}}};{NL}"
def rewrite(text, drop, test_only):
"""The text with `drop` names deleted and `test_only` names moved under `#[cfg(test)]`."""
def fix(m):
if "{" in m.group("body").split("{", 1)[-1]: # nested braces: left for a person
return m.group(0)
names, prefix, items = statement_names(m.group("body"))
gone = [i for n, i in names if n in drop]
moved = [i for n, i in names if n in test_only]
if not gone and not moved:
return m.group(0)
attrs, head = m.group("attrs"), m.group("head")
if items is None: # a single path
return f"{attrs}#[cfg(test)]{NL}{head}{m.group('body').strip()};{NL}" if moved else ""
left = [i for n, i in names if n not in drop and n not in test_only]
out = build(attrs, head, prefix, left) if left else ""
if moved:
out += build("" if left else attrs, head, prefix, moved).replace(head, "#[cfg(test)]" + NL + head, 1)
return out
return USE_STATEMENT.sub(fix, text)
def write(path, text):
with open(path, "w", encoding="utf-8", newline=chr(10)) as handle:
handle.write(text)
def flagged_counts(msgs):
"""Counter {(file, name): messages} of the unused-import warnings (a name flagged by two units counts twice)."""
counts = collections.Counter()
for m in msgs:
for r, names in ei.flagged([m], "unused").items():
counts.update((r, n) for n in names)
return counts
def classify(counts_a, counts_b):
"""({file: names unused everywhere}, {file: names used by the test build only}) from the two builds.
`--tests` builds the library once more as a dependency of the integration tests, so it repeats the first build's
warnings; what it says on top of that comes from the unit-test build."""
drop, test_only = collections.defaultdict(set), collections.defaultdict(set)
for (r, name), n_a in counts_a.items():
if counts_b.get((r, name), 0) > n_a:
drop[r].add(name)
else:
test_only[r].add(name)
for (r, name), n_b in counts_b.items():
if (r, name) not in counts_a: # a file only the test build compiles
drop[r].add(name)
return drop, test_only
def main():
wt, crate_dir, package = sys.argv[1:4]
wtp = pathlib.Path(wt).resolve()
rel = lambda f: f.resolve().relative_to(wtp).as_posix() # noqa: E731
crate = pathlib.Path(crate_dir).resolve()
files = {f: f.read_text(encoding="utf-8") for f in (crate / "src").rglob("*.rs")}
for f, text in files.items():
if ALLOW.search(text) and "--keep-allow" not in sys.argv:
files[f] = ALLOW.sub("", text)
write(f, files[f])
for round_no in range(1, 8):
a = ei.run_cargo(wt, f"-p {package} --lib --bins", "da-a.json")
b = ei.run_cargo(wt, f"-p {package} --tests", "da-b.json")
drop_by_file, test_by_file = classify(flagged_counts(a), flagged_counts(b))
touched = 0
by_rel = {rel(f): f for f in files}
for r in set(drop_by_file) | set(test_by_file):
f = by_rel.get(r)
if f is None or r.split("/src/", 1)[-1] in PLATFORM_FILES: # their other-platform code is not built here
continue
new = rewrite(files[f], drop_by_file.get(r, set()), test_by_file.get(r, set()))
if new != files[f]:
files[f] = new
write(f, new)
touched += 1
print(f"round {round_no}: {touched} files edited", flush=True)
if not touched:
break
if __name__ == "__main__":
main()
+5 -2
View File
@@ -9,6 +9,7 @@ a moved module are moved the same way (their `#[path]` or their place next to th
paths of `include_str!`/`include_bytes!` in a moved file are rewritten. Without --apply the plan is printed.
Offline refactoring aid, not part of the product.
"""
import collections
import os
import pathlib
import re
@@ -33,6 +34,7 @@ def canonical_base(new_file, keeps_attr):
def plan(crate, every):
src = crate.root_dir.resolve() / "src"
declared_by = collections.Counter(child.file for mod in crate.by_file.values() for child in mod.children.values())
"""(moves {old file: new file}, dropped [(parent file, module name)], problems [str])."""
moves, dropped, problems = {}, [], []
new_file = {crate.root.file: crate.root.file}
@@ -51,7 +53,8 @@ def plan(crate, every):
current = child.file
is_modrs = current.name == "mod.rs"
canonical = base / name / "mod.rs" if is_modrs else base / f"{name}.rs"
if not current.is_relative_to(src): # a file of the crate's `tests/` directory stays where it is
shared = declared_by[current] > 1 # a file two parents declare (each owns a copy of its state) cannot be moved
if shared or not current.is_relative_to(src): # a file of the crate's `tests/` directory stays where it is
new_file[current], keeps[current], changed[current] = current, True, False
queue.append(child)
continue
@@ -82,7 +85,7 @@ def rewrite_includes(text, old, new):
"""Fix the relative path of include_str!/include_bytes! in a file that moves from `old` to `new`."""
def fix(m):
target = (old.parent / m.group(2)).resolve()
return f'{m.group(1)}"{pathlib.PurePosixPath(os.path.relpath(target, new.parent)).as_posix()}"'
return f'{m.group(1)}"{os.path.relpath(target, new.parent).replace(os.sep, "/")}"'
return re.sub(r'(include_(?:str|bytes)!\()"([^"]+)"', fix, text)
+1 -1
View File
@@ -343,7 +343,7 @@ class Crate:
m = re.match(rf"(?:pub(?:\s*\([^)]*\))?\s+)?mod\s+({IDENT})\s*;", t)
if m:
child_name = m.group(1)
path_attr = next((re.search(r'path\s*=\s*"([^"]+)"', a) for a in attrs if "path" in a), None)
path_attr = next((m for m in (re.match(r'#\[path\s*=\s*"([^"]+)"', a) for a in attrs) if m), None)
if path_attr:
cand = [(file.parent / path_attr.group(1)).resolve()]
else:
+247
View File
@@ -0,0 +1,247 @@
"""Replace `use super::*;` by explicit imports, guided by the compiler's errors (STRA-338 stage 10, `glob-super-import`).
Usage: python scripts/dev/unglob_by_errors.py WORKTREE CRATE_DIR PACKAGE [--include-tests] [--max-rounds N]
`explicit_imports.py` expands every glob file at once and gives a file back its glob when the build fails. This driver keeps
the expansion and repairs it from the compiler's messages instead, so the files that tool could not close (GPU proofs, test
modules, names behind an inner cfg) become explicit too:
* a name the file uses but does not have (`cannot find type/value/function/trait/macro X`, an `enum Result takes 2 generic
arguments` from the prelude instead of the crate alias) is added as `use super::X;`;
* `unresolved import super::X` adds X to the parent's own imports when the parent is also expanded here;
* a trait whose methods are called but is not in scope is added with the path rustc suggests;
* a name that only the test build needs gets `#[cfg(test)]`; a name no build uses is removed.
Each round is one `cargo check --lib --bins` and one `--tests` (through scripts/dev/wsl-cargo.sh on Windows). The Plan, the module
tree and the rendering are those of explicit_imports.py. Offline refactoring aid, not part of the product.
"""
import collections
import json
import pathlib
import posixpath
import re
import sys
sys.path.insert(0, str(pathlib.Path(__file__).parent))
import explicit_imports as ei # noqa: E402
IDENT = ei.IDENT
MISSING = [
re.compile(rf"cannot find (?:type|value|function|trait|macro|struct, variant or union type|tuple struct or tuple variant|"
rf"unit struct, unit variant or constant|derive macro|attribute macro|function, tuple struct or tuple variant|"
rf"value, found) `({IDENT})` in this scope"),
re.compile(rf"failed to resolve: use of undeclared (?:type|module|crate or module) `({IDENT})`"),
re.compile(rf"failed to resolve: use of unresolved module or unlinked crate `({IDENT})`"),
re.compile(rf"failed to resolve: use of undeclared type or module `({IDENT})`"),
re.compile(rf"(?:enum|struct|type alias|trait) `({IDENT})` takes \d+ generic argument"),
re.compile(rf"cannot find .*? `({IDENT})` in module"),
]
BAD_IMPORT = re.compile(r"unresolved imports? (.*)")
SUPER_NAME = re.compile(rf"`super::({IDENT})`")
TRAIT_HELP = re.compile(r"(?:trait|traits).*(?:not in scope|perhaps you want to import)")
def messages(wt, package, args, out_name):
"""compiler-message dicts of `cargo check --message-format=json` over `args`."""
return ei.run_cargo(wt, f"-p {package} {args}", out_name)
def span_file(message):
for span in message.get("spans", []):
if span.get("is_primary"):
return posixpath.normpath(span["file_name"])
return None
def missing_names(message):
text = message["message"]
for rx in MISSING:
m = rx.search(text)
if m:
return [m.group(1)]
return []
def trait_paths(message):
"""`crate::a::Trait` paths rustc suggests importing for a method call (children of an E0599)."""
found = []
for child in message.get("children", []):
if not TRAIT_HELP.search(child.get("message", "")):
continue
for span in child.get("spans", []):
replacement = span.get("suggested_replacement") or ""
for m in re.finditer(r"use ([\w:]+);", replacement):
found.append(m.group(1))
return found
def collect(msgs):
"""({file: {name}}, {file: {bad super name}}, {file: {trait path}}, {file: other error text}) of one build."""
missing, bad, traits, other = (collections.defaultdict(set) for _ in range(4))
for m in msgs:
if m["level"] != "error":
continue
f = span_file(m)
if f is None:
continue
names = missing_names(m)
paths = trait_paths(m)
bad_import = BAD_IMPORT.match(m["message"])
if names:
missing[f].update(names)
elif bad_import:
bad[f].update(SUPER_NAME.findall(bad_import.group(1)))
elif paths:
traits[f].update(paths)
else:
other[f].add(m["message"][:100])
return missing, bad, traits, other
PLATFORM_FILES = {
"backend/original_serve/runner/owner_run_steps.rs", "memory_governor/page_cache.rs",
"model_binding/qwen4exp_input/mtp/backing.rs", "model_binding/qwen4exp_input/mtp/mtp_weight_reads.rs",
"model_binding/qwen4exp_input/mtp/read_expert_rows.rs", "model_binding/qwen4exp_kar_ple/pinned_profile_tests.rs",
"model_binding/qwen4exp_kar_ple/private_copy/inode.rs", "model_binding/qwen4exp_kar_ple/private_copy/checked_reader.rs",
"model_binding/qwen4exp_kar_ple/inherited_kar_archive.rs", "model_binding/qwen4exp_kar_ple/load_pinned_inherited_archive.rs",
"model_binding/qwen4exp_kar_ple/pinned_profile.rs", "qwen_forward/original_serve_residency/open_tier.rs",
}
def prune_existing(plan, rel):
"""Files that already carry explicit `use super::{..}` lists: their names become the seed of the prune."""
plan.prune = True
todo = []
for f, text in plan.texts.items():
names = {}
for m in ei.USE_SUPER_RE.finditer(text):
block = m.group(0)
cfg_lines = [ln for ln in block.splitlines() if ln.startswith("#[cfg(")]
cfg = chr(10).join(cfg_lines)
kind = "test" if cfg == "#[cfg(test)]" else "normal"
if cfg == "#[cfg(test)]":
cfg = ""
for name in re.findall(IDENT, block.split("use super::", 1)[1]):
names[name] = kind
if cfg:
plan.cfgs.setdefault(f, {})[name] = cfg
if names:
plan.imports[f] = names
todo.append(f)
return todo
def select(plan, rel):
"""(todo, skipped, keep_all) of the glob files, by the skip rules and the --include-tests/--platform/--opaque flags."""
only = [a for a in sys.argv[4:] if not a.startswith("--") and not a.isdigit()]
todo, skipped, keep_all = [], {}, set()
for f in plan.candidates():
reason = plan.skip_reason(f)
if reason == "test module" and "--include-tests" in sys.argv:
reason = None
if reason == "platform cfg" and "--platform" in sys.argv:
reason = None
keep_all.add(f) # the other platform's code is not compiled here: unused names are reported, not removed
if reason == "opaque glob in the parent chain" and "--opaque" in sys.argv:
reason = None
if only and not any(o in rel(f) for o in only):
continue
(skipped.__setitem__(f, reason) if reason else todo.append(f))
return todo, skipped, keep_all
def main():
wt, crate_dir, package = sys.argv[1:4]
max_rounds = int(sys.argv[sys.argv.index("--max-rounds") + 1]) if "--max-rounds" in sys.argv else 12
plan = ei.Plan(wt, crate_dir)
wtp = pathlib.Path(wt).resolve()
rel = lambda f: f.resolve().relative_to(wtp).as_posix() # noqa: E731
by_rel = {rel(f): f for f in plan.crate.by_file}
only = [a for a in sys.argv[4:] if not a.startswith("--") and not a.isdigit()]
todo, skipped, keep_all = [], {}, set()
if "--prune-existing" in sys.argv:
todo = prune_existing(plan, rel)
keep_all = {f for f in todo if rel(f).split("/src/", 1)[1] in PLATFORM_FILES}
todo = [f for f in todo if f not in keep_all]
for f in keep_all:
plan.imports.pop(f, None)
else:
todo, skipped, keep_all = select(plan, rel)
needs = plan.compute_needs(todo)
plan.blocked = {f for f in plan.blocked if f in todo} # a conditional name is repaired by the build below
plan.apply(todo, needs)
for f, conditional in plan.cfgs.items(): # a name declared twice under complementary platform cfgs is always there
for n in [n for n, c in conditional.items() if "not(true)" in c or c.strip() in ("", "true")]:
del conditional[n]
print(f"{package}: {len(todo)} files to expand, {len(skipped)} skipped", flush=True)
for reason, n in collections.Counter(skipped.values()).items():
print(f" skipped {n}: {reason}", flush=True)
for round_no in range(1, max_rounds + 1):
plan.write()
a = messages(wt, package, "--lib --bins", "ug-a.json")
b = messages(wt, package, "--tests", "ug-b.json")
am, ab, at, ao = collect(a)
bm, bb, bt, bo = collect(b)
changed = 0
for f in todo:
r, imp = rel(f), plan.imports.setdefault(f, {})
wanted = (am[r], "normal"), (bm[r] - am[r], "test")
for names, kind in wanted:
for n in names:
if n not in imp:
imp[n] = kind
changed += 1
elif plan.cfgs.get(f, {}).pop(n, None) is not None: # the name is there but its cfg hides it
changed += 1
for path in at[r] | bt[r]:
key = "@anon:" + path
if key not in imp:
imp[key] = "normal" if path in at[r] else "test"
changed += 1
for n in ab[r] | bb[r]:
parent = plan.crate.by_file[f].parent
if parent is not None and parent.file in todo:
kind = "normal" if n in ab[r] else "test"
if plan.imports.setdefault(parent.file, {}).get(n) != "normal":
plan.imports[parent.file][n] = kind
changed += 1
elif n in imp:
del imp[n] # the name is not in the parent: another path is needed (listed below)
changed += 1
other = {r: v for r, v in {**ao, **bo}.items() if r in {rel(f) for f in todo}}
print(f"round {round_no}: {changed} imports added, {sum(len(v) for v in other.values())} other errors in "
f"{len(other)} files", flush=True)
if changed:
continue
if other:
for r, v in sorted(other.items())[:20]:
print(" ", r, sorted(v)[:2])
break
unused_a, unused_b = ei.flagged(a, "unused"), ei.flagged(b, "unused")
pruned = 0
for f in todo:
r, imp = rel(f), plan.imports[f]
if f in keep_all:
print(" unused here, kept:", r, sorted(set(unused_a.get(r, ())) & set(unused_b.get(r, ()))), flush=True)
continue
for name in list(imp):
a_unused = name in unused_a.get(r, ())
b_unused = name in unused_b.get(r, ())
if b_unused:
del imp[name]
pruned += 1
elif a_unused and imp[name] == "normal":
imp[name] = "test"
pruned += 1
print(f" pruned or moved to cfg(test): {pruned}", flush=True)
if not pruned:
break
plan.write()
left = [rel(f) for f in plan.texts if ei.GLOB_RE.search(open(f, encoding="utf-8").read())]
print(f"{len(left)} files still carry the glob")
ei.WORK.mkdir(parents=True, exist_ok=True)
(ei.WORK / f"unglob_{package}.json").write_text(json.dumps(left, indent=0))
if __name__ == "__main__":
main()