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
Generated
+1
View File
@@ -1350,6 +1350,7 @@ dependencies = [
"leleka-cuda-driver",
"leleka-engine-core",
"leleka-experimental-ref",
"leleka-gateway-text",
"leleka-memory",
"leleka-memory-os",
"leleka-model-format",
+2
View File
@@ -46,5 +46,7 @@ workspace = true
[dev-dependencies]
serde_json = "1"
leleka-engine-core = { path = "../engine-core", features = ["testing"] }
# The GPU proofs render prompts with the gateway renderer itself (they used to compile its source file as a module).
leleka-gateway-text = { path = "../gateway-text" }
# Model-free device probe of the VRAM expert tier (test builds only).
leleka-cuda-driver = { path = "../cuda-driver", features = ["cuda-driver", "expert-tier-probe"] }
-9
View File
@@ -157,11 +157,9 @@ mod backend_measurement_sdet;
#[cfg(feature = "preview-path")]
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
#[path = "gpu_proofs/combined_prefix_numeric.rs"]
mod combined_prefix_numeric;
#[cfg(feature = "preview-path")]
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
#[path = "gpu_proofs/combined_prefix_numeric_sdet.rs"]
mod combined_prefix_numeric_sdet;
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
mod original_serve_arms;
@@ -179,37 +177,30 @@ mod original_serve_smoke;
mod original_serve_ttft;
#[cfg(feature = "preview-path")]
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
#[path = "gpu_proofs/singleload_proof.rs"]
mod singleload_proof;
#[cfg(feature = "preview-path")]
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
#[path = "gpu_proofs/resident_mmq_model_proof.rs"]
mod resident_mmq_model_proof;
#[cfg(feature = "preview-path")]
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
#[path = "gpu_proofs/native_resident_mmq_model_proof.rs"]
mod native_resident_mmq_model_proof;
#[cfg(feature = "preview-path")]
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
#[path = "gpu_proofs/layer0_native_mmq_proof.rs"]
mod layer0_native_mmq_proof;
#[cfg(feature = "preview-path")]
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
#[path = "gpu_proofs/combined_changed_boundary_proof.rs"]
mod combined_changed_boundary_proof;
#[cfg(feature = "preview-path")]
#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))]
#[path = "gpu_proofs/native_down_public_pair.rs"]
mod native_down_public_pair;
#[cfg(feature = "preview-path")]
#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))]
#[path = "gpu_proofs/native_down_candidate_only.rs"]
mod native_down_candidate_only;
#[cfg(test)]
@@ -2,7 +2,6 @@
use super::*;
use crate::qwen_forward::loaded_target_owners::LoadedTargetOwners as LoadedTarget;
use std::env;
#[path = "combined_changed_boundary_proof/rig.rs"]
pub(super) mod rig;
use rig::{DEVICE_BUDGET, Owners, bind_pinned, require_opt_in, unwrap_phase};
@@ -10,29 +10,22 @@ use std::{
panic::{AssertUnwindSafe, catch_unwind, resume_unwind},
};
// EXACT existing daemon pure renderer, Effort::None. No hand-built ChatML.
#[path = "../../../../crates/gateway-text/src/prompt.rs"]
#[allow(dead_code)]
mod public_renderer;
use leleka_gateway_text::prompt as public_renderer;
// Files, request framing and counters shared with the one-load pair (native_down_public_pair.rs).
#[path = "native_down_pair_io.rs"]
mod pair_io;
use pair_io::*;
// The retained completed Native arm and the checks of the MTP window witnesses.
#[path = "native_down_pair_checks.rs"]
mod pair_checks;
use pair_checks::*;
// One actual owner generation on a fresh target/draft state.
#[path = "native_down_pair_arm.rs"]
mod pair_arm;
use pair_arm::*;
// The one loaded owner, its ordered teardown and the run of a proof on it.
#[path = "native_down_pair_owner.rs"]
mod pair_owner;
use pair_owner::*;
#[path = "native_down_pair_run.rs"]
mod pair_run;
use pair_run::*;
#[path = "native_down_pair_proofs.rs"]
mod pair_proofs;
use pair_proofs::*;
#[test]
@@ -90,7 +83,6 @@ fn pinned_five_public_cases_resident_owners() {
}
// Private framing only; Root owns the unchanged five-case consumer/caller.
#[path = "fivecase_frames.rs"]
mod fivecase_frames;
impl Inputs<'_, '_, '_> {
fn prepare_five_public_frames(&self) -> (PathBuf, String) {
@@ -99,7 +91,6 @@ impl Inputs<'_, '_, '_> {
}
// Private loaded-owner helper; Root supplies sealed genuine tokenizer frames.
#[path = "fivecase_runtime.rs"]
mod fivecase_runtime;
impl Inputs<'_, '_, '_> {
fn arm_five_public_cases(
@@ -111,5 +102,4 @@ impl Inputs<'_, '_, '_> {
}
}
#[path = "native_down_adaptive_candidate_only.rs"]
mod adaptive_slots;
@@ -5,10 +5,8 @@ use super::*;
use leleka_model_format::qwen4exp::{ProvisionalExpertSource, ResidentExpertSourceReport};
use std::path::Path;
#[path = "native_down_adaptive_candidate_only/observe.rs"]
mod observe;
use observe::*;
#[path = "native_down_adaptive_candidate_only/cleanup.rs"]
mod cleanup;
use cleanup::*;
@@ -30,7 +28,7 @@ fn save_public_admission(root: &Path, baseline: &Baseline, tokenizer: &Tokenizer
let (req, ids, canonical) = request(tokenizer);
assert_eq!(ids, baseline.input_ids);
assert_eq!(ids.len(), 202);
let renderer = sha(include_bytes!("../../../../crates/gateway-text/src/prompt.rs"));
let renderer = sha(include_bytes!("../../../../gateway-text/src/prompt.rs"));
save(
root,
"BASELINE-ADMISSION.json",
@@ -142,7 +142,7 @@ fn write_frame(
pub(super) fn prepare(inputs: &Inputs<'_, '_, '_>) -> (PathBuf, String) {
let (root, uid) = fresh_frames_root();
let requests = build_requests(inputs);
let renderer = sha(include_bytes!("../../../../crates/gateway-text/src/prompt.rs"));
let renderer = sha(include_bytes!("../../../../gateway-text/src/prompt.rs"));
check_requests(&requests);
let entries: Vec<Value> = requests
.iter()
@@ -94,7 +94,7 @@ fn admit_manifest_header(manifest: &Value) -> String {
assert_eq!(number(manifest, "case_count"), CASE_COUNT as u64);
assert_eq!(text(manifest, "baseline_frame_sha256"), BASE_FRAME_SHA);
assert_eq!(text(manifest, "model_digest"), MODEL_DIGEST);
let renderer = sha(include_bytes!("../../../../crates/gateway-text/src/prompt.rs"));
let renderer = sha(include_bytes!("../../../../gateway-text/src/prompt.rs"));
assert_eq!(text(manifest, "renderer_source_sha256"), renderer);
renderer
}
@@ -105,7 +105,7 @@ fn pinned_tokenizer(artifact: &Qwen4ExpArtifact) -> (Tokenizer, u32) {
(tokenizer, eos)
}
fn renderer_sha() -> String {
sha(include_bytes!("../../../../crates/gateway-text/src/prompt.rs"))
sha(include_bytes!("../../../../gateway-text/src/prompt.rs"))
}
fn baseline_admission_json() -> Value {
json!({"baseline_sha256":BASELINE_SHA,"retained_run":"24993ad2-9c7c-4a90-bfac-3e6e0b5685c1",
@@ -9,20 +9,15 @@ use std::{
panic::{AssertUnwindSafe, catch_unwind, resume_unwind},
};
// EXACT existing daemon pure renderer, Effort::None. No hand-built ChatML.
#[path = "long_public_preflight/long_public_request.rs"]
mod long_public_preflight;
#[path = "../../../../crates/gateway-text/src/prompt.rs"]
#[allow(dead_code)]
mod public_renderer;
use leleka_gateway_text::prompt as public_renderer;
// Files, request framing and counters shared with the candidate-only proofs (native_down_candidate_only.rs).
#[path = "native_down_pair_io.rs"]
mod pair_io;
use pair_io::*;
// One actual owner generation, and the run of the pair on the one loaded owner.
#[path = "native_down_public_pair_arm.rs"]
mod pair_arm;
use pair_arm::*;
#[path = "native_down_public_pair_run.rs"]
mod pair_run;
#[test]
@@ -9,9 +9,7 @@ use std::{
os::unix::fs::OpenOptionsExt,
path::Path,
};
#[path = "../../../../../crates/gateway-text/src/prompt.rs"]
#[allow(dead_code)]
mod public_renderer;
use leleka_gateway_text::prompt as public_renderer;
const BYTE_CAP: usize = 1024 * 1024;
const ARTIFACT_CAP: usize = 16 * 1024 * 1024;
const CONTEXT: usize = 262144;
@@ -176,7 +174,7 @@ fn push_frame_summary(
bound_model_digest: &str,
artifacts: &mut Vec<Artifact>,
) -> io::Result<Value> {
let renderer = digest(include_bytes!("../../../../../crates/gateway-text/src/prompt.rs"));
let renderer = digest(include_bytes!("../../../../gateway-text/src/prompt.rs"));
let frame = json!({
"schema":"public-long-preflight-v1","model_digest":bound_model_digest,
"renderer_source_sha256":renderer,
@@ -69,7 +69,7 @@ fn pinned_tokenizer(artifact: &Qwen4ExpArtifact) -> (Tokenizer, u32) {
(tokenizer, eos)
}
fn frame_json(case: &Case) -> Value {
json!({"renderer_source_sha256":sha(include_bytes!("../../../../crates/gateway-text/src/prompt.rs")),
json!({"renderer_source_sha256":sha(include_bytes!("../../../../gateway-text/src/prompt.rs")),
"framed_prompt":case.req.prompt,"framed_prompt_sha256":sha(case.req.prompt.as_bytes()),
"input_token_ids":case.ids,"framed_count":case.ids.len(),"model_digest":MODEL_DIGEST,
"max_output_tokens":CAP,"temperature_milli":0})
@@ -1,355 +0,0 @@
//! Supported text subset of the pinned Strata Qwen chat template.
//! The no-tool path and a representative tool continuation are byte-for-byte
//! checked against upstream golden cases. Tool definitions are adapted from
//! Responses function objects.
use serde_json::Value;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Role {
System,
Developer,
User,
Assistant,
}
#[derive(Clone, Copy, Debug)]
pub struct Message<'a> {
pub role: Role,
pub content: &'a str,
pub reasoning: Option<&'a str>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Effort {
None,
Low,
Medium,
High,
#[default]
XHigh,
}
const XHIGH: &str = "Reasoning effort is set to xhigh. Please think carefully through the task, validate key \
assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final \
answer.";
const LOW: &str = "Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the \
conclusion without unnecessary elaboration.";
pub fn render(messages: &[Message<'_>], effort: Effort) -> Result<String, &'static str> {
render_with_tools(messages, effort, &[])
}
const TOOLS_FOOTER: &str = "\
\n</tools>\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\
\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n\
</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can \
span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function \
calls MUST follow the specified format: an inner <function=...></function> block must be nested \
within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide \
optional reasoning for your function call in natural language BEFORE the function call, but NOT \
after\n- If there is no function call available, answer the question like normal with your current \
knowledge and do not tell the user about function calls\n</IMPORTANT>";
/// The index of the first message that is not system or developer; those must all come first and a user message
/// must come last.
fn first_non_system(messages: &[Message<'_>]) -> Result<usize, &'static str> {
if messages.is_empty() {
return Err("prompt needs a message");
}
let first_non_system = messages
.iter()
.position(|message| !matches!(message.role, Role::System | Role::Developer))
.unwrap_or(messages.len());
if first_non_system == messages.len()
|| messages[first_non_system..]
.iter()
.any(|message| matches!(message.role, Role::System | Role::Developer))
{
return Err("system and developer messages must be at the beginning");
}
if messages
.last()
.is_none_or(|message| message.role != Role::User)
{
return Err("generation needs a final user message");
}
Ok(first_non_system)
}
/// One tool definition as the template prints it.
fn push_tool(prompt: &mut String, tool: &Value) -> Result<(), &'static str> {
let name = tool
.get("name")
.and_then(Value::as_str)
.ok_or("tool needs a name")?;
prompt.push('\n');
prompt.push_str("{\"type\": \"function\", \"function\": {\"name\": ");
prompt.push_str(&serde_json::to_string(name).expect("string JSON"));
if let Some(description) = tool.get("description").and_then(Value::as_str) {
prompt.push_str(", \"description\": ");
prompt.push_str(&serde_json::to_string(description).expect("string JSON"));
}
if let Some(parameters) = tool.get("parameters") {
prompt.push_str(", \"parameters\": ");
write_template_json(parameters, prompt);
}
if let Some(strict) = tool.get("strict") {
prompt.push_str(", \"strict\": ");
write_template_json(strict, prompt);
}
prompt.push_str("}}");
Ok(())
}
/// The `# Tools` section of the system block.
fn push_tools(prompt: &mut String, instruction: &str, tools: &[Value]) -> Result<(), &'static str> {
if !instruction.is_empty() {
prompt.push_str("\n\n");
}
prompt.push_str("# Tools\n\nYou have access to the following functions:\n\n<tools>");
for tool in tools {
push_tool(prompt, tool)?;
}
prompt.push_str(TOOLS_FOOTER);
Ok(())
}
/// The system block: effort instruction, tool section and the joined system messages.
fn push_system_block(
prompt: &mut String,
instruction: &str,
system: &str,
tools: &[Value],
) -> Result<(), &'static str> {
if instruction.is_empty() && system.is_empty() && tools.is_empty() {
return Ok(());
}
prompt.push_str("<|im_start|>system\n");
prompt.push_str(instruction);
if !tools.is_empty() {
push_tools(prompt, instruction, tools)?;
}
if !system.is_empty() && (!instruction.is_empty() || !tools.is_empty()) {
prompt.push_str("\n\n");
}
prompt.push_str(system);
prompt.push_str("<|im_end|>\n");
Ok(())
}
/// The user and assistant turns after the system block.
fn push_turns(prompt: &mut String, turns: &[Message<'_>]) {
for message in turns {
match message.role {
Role::User => {
prompt.push_str("<|im_start|>user\n");
prompt.push_str(message.content.trim());
prompt.push_str("<|im_end|>\n");
}
Role::Assistant => {
prompt.push_str("<|im_start|>assistant\n<think>\n");
prompt.push_str(message.reasoning.unwrap_or("").trim());
prompt.push_str("\n</think>\n\n");
prompt.push_str(message.content.trim());
prompt.push_str("<|im_end|>\n");
}
Role::System | Role::Developer => unreachable!(),
}
}
}
pub fn render_with_tools(
messages: &[Message<'_>],
effort: Effort,
tools: &[Value],
) -> Result<String, &'static str> {
let first_non_system = first_non_system(messages)?;
let system = messages[..first_non_system]
.iter()
.map(|message| message.content.trim())
.filter(|content| !content.is_empty())
.collect::<Vec<_>>()
.join("\n");
let instruction = match effort {
Effort::None | Effort::Medium => "",
Effort::Low => LOW,
Effort::High | Effort::XHigh => XHIGH,
};
let mut prompt = String::new();
push_system_block(&mut prompt, instruction, &system, tools)?;
push_turns(&mut prompt, &messages[first_non_system..]);
prompt.push_str("<|im_start|>assistant\n<think>\n");
if effort == Effort::None {
prompt.push_str("\n</think>\n\n");
}
Ok(prompt)
}
/// The keys of a JSON-schema-like object in template order: `type` first when the object has one.
fn template_keys(fields: &serde_json::Map<String, Value>) -> Vec<&String> {
let mut keys = fields.keys().collect::<Vec<_>>();
if fields.contains_key("type") {
let priority = |key: &str| match key {
"type" => 0,
"properties" => 1,
"required" => 2,
"items" => 3,
"enum" => 4,
"description" => 5,
"additionalProperties" => 6,
_ => 7,
};
keys.sort_by_key(|key| (priority(key), key.as_str()));
}
keys
}
fn write_template_json(value: &Value, output: &mut String) {
match value {
Value::Object(fields) => {
output.push('{');
for (index, key) in template_keys(fields).into_iter().enumerate() {
if index > 0 {
output.push_str(", ");
}
output.push_str(&serde_json::to_string(key).expect("object key JSON"));
output.push_str(": ");
write_template_json(&fields[key], output);
}
output.push('}');
}
Value::Array(items) => {
output.push('[');
for (index, item) in items.iter().enumerate() {
if index > 0 {
output.push_str(", ");
}
write_template_json(item, output);
}
output.push(']');
}
_ => output.push_str(&value.to_string()),
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::{Value, json};
fn golden_cases() -> Vec<Value> {
serde_json::from_str(include_str!("../../../engine/strata/serve/chat_golden.json")).unwrap()
}
fn golden_messages(case: &Value) -> Vec<Message<'_>> {
case["messages"]
.as_array()
.unwrap()
.iter()
.map(|message| Message {
role: match message["role"].as_str().unwrap() {
"system" => Role::System,
"developer" => Role::Developer,
"user" => Role::User,
"assistant" => Role::Assistant,
role => panic!("unsupported role: {role}"),
},
content: message["content"].as_str().unwrap(),
reasoning: message["reasoning_content"].as_str(),
})
.collect::<Vec<_>>()
}
fn assert_text_case_matches(golden: &[Value], name: &str) {
let case = golden.iter().find(|case| case["name"] == name).unwrap();
let messages = golden_messages(case);
let effort = if name == "thinking disabled" {
Effort::None
} else {
Effort::XHigh
};
assert_eq!(
render(&messages, effort).unwrap(),
case["rendered"],
"{name}"
);
}
#[test]
fn text_prompt_matches_upstream_golden_bytes() {
let golden = golden_cases();
for name in [
"single user",
"system + user",
"multi-turn",
"assistant with thinking",
"unicode content",
"empty user",
"whitespace and newlines",
"thinking disabled",
] {
assert_text_case_matches(&golden, name);
}
}
fn weather_messages() -> [Message<'static>; 4] {
[
Message {
role: Role::User,
content: "Weather in Oslo?",
reasoning: None,
},
Message {
role: Role::Assistant,
content: "<tool_call>\n<function=get_weather>\n<parameter=city>\nOslo\n</parameter>\n\
</function>\n</tool_call>",
reasoning: None,
},
Message {
role: Role::User,
content: "<tool_response>\n{\"temp\": 3}\n</tool_response>",
reasoning: None,
},
Message {
role: Role::User,
content: "And in Bergen?",
reasoning: None,
},
]
}
#[test]
fn representative_tool_prompt_matches_upstream_golden_bytes() {
let golden = golden_cases();
let case = golden
.iter()
.find(|case| case["name"] == "tool call and response")
.unwrap();
let function = &case["tools"][0]["function"];
let tools = [json!({
"type":"function", "name":function["name"], "description":function["description"],
"parameters":function["parameters"]
})];
let messages = weather_messages();
assert_eq!(
render_with_tools(&messages, Effort::XHigh, &tools).unwrap(),
case["rendered"]
);
}
#[test]
fn rejects_unrepresentable_message_order() {
let system = Message {
role: Role::System,
content: "rules",
reasoning: None,
};
let user = Message {
role: Role::User,
content: "question",
reasoning: None,
};
assert!(render(&[user, system], Effort::XHigh).is_err());
assert!(render(&[system], Effort::XHigh).is_err());
}
}
+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()