Wave 39/45: diagnostics.kernel takes a typed contract, as main's other diagnostics commands do
1 commits, squashed; the originals stay reachable from branch jyviko/merge-main-develop-solidcore (#11360). - 7ad1d3e12 jyviko: diagnostics.kernel takes a typed contract, as main's other diagnostics commands do Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ
This commit is contained in:
@@ -55,11 +55,22 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
trace?: path (write the recorded spans as a Chrome trace-event file, for chrome://tracing or Perfetto). Returns what \
|
||||
was recorded before enabled and reset apply: {compiled, enabled, wall_ms, spans, dropped, by_category: [{category, \
|
||||
self_ms, share}], rows: [{category, name, count, total_ms, self_ms, max_ms}], rows_total, trace?}, the rows the most \
|
||||
self time first. Categories: smlib (SMLib's C API calls, timed by the C API), kernel, feature (one per feature \
|
||||
self time first. Categories: solidcore (the kernel's calls), smlib (SMLib's C API calls, timed by the C API, when it is asked for), kernel, feature (one per feature \
|
||||
computed, by its type), doc, command, import (STEP/IGES stages), io. Self time is a span's time less the spans \
|
||||
inside it; total counts its outermost run only. Recording also starts with SOLIDCRAFT_PROFILE=1, the CLI's \
|
||||
--profile and the app's preference; off, it costs nothing measurable. Read-only",
|
||||
),
|
||||
CommandSpec::new("diagnostics.kernel", "Geometry Kernel", crate::checked!("diagnostics.kernel", kernel))
|
||||
.icon("bug_report")
|
||||
.noundo()
|
||||
.contract(&KERNEL_CONTRACT)
|
||||
.output(output_schema_for::<crate::schema::diagnostics::KernelReply>)
|
||||
.params(
|
||||
"choice?: solidcore | smlib (sets which kernel answers every operation: solidcore, the default = the Rust port; \
|
||||
smlib = the C++ SMLib kernel, refused as not available on a build without it, such as the web app; bodies already \
|
||||
computed keep their results). SOLIDCRAFT_KERNEL, when set, wins over it. Returns {choice, environment}: choice is \
|
||||
the kernel in force, environment whether SOLIDCRAFT_KERNEL chose it",
|
||||
),
|
||||
CommandSpec::new("diagnostics.validation", "Validation", crate::checked!("diagnostics.validation", validation))
|
||||
.icon("bug_report")
|
||||
.noundo()
|
||||
@@ -85,6 +96,34 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
),
|
||||
];
|
||||
|
||||
fn kernel(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
use solidcraft_kernel::kernel_route as route;
|
||||
if let Some(v) = p.get("choice").filter(|v| !v.is_null()) {
|
||||
route::set_choice(kernel_asked(v, solidcraft_kernel::smlib_built())?);
|
||||
}
|
||||
use crate::schema::diagnostics::{KernelChoice, KernelReply};
|
||||
let choice = match route::choice() {
|
||||
route::Backend::Solidcore => KernelChoice::Solidcore,
|
||||
route::Backend::Smlib => KernelChoice::Smlib,
|
||||
};
|
||||
serde_json::to_value(KernelReply { choice, environment: route::overridden() }).map_err(|e| bad("diagnostics.kernel", e.to_string()))
|
||||
}
|
||||
|
||||
/// The kernel `choice` asks for, on a build that has (`built`) the C++ kernel or doesn't. A choice of
|
||||
/// the wrong type is refused like an unknown one, not read as no choice; `smlib` on a build without
|
||||
/// it is refused too, never answered by the other kernel.
|
||||
pub(crate) fn kernel_asked(choice: &Value, built: bool) -> Result<solidcraft_kernel::kernel_route::Backend> {
|
||||
use solidcraft_kernel::kernel_route::Backend;
|
||||
let asked = choice.as_str().and_then(Backend::from_id).ok_or_else(|| bad("diagnostics.kernel", "`choice` is solidcore or smlib"))?;
|
||||
if asked == Backend::Smlib && !built {
|
||||
return Err(EngineError::Disabled(
|
||||
"diagnostics.kernel".into(),
|
||||
"this build doesn't include the C++ SMLib kernel; build with --features smlib".into(),
|
||||
));
|
||||
}
|
||||
Ok(asked)
|
||||
}
|
||||
|
||||
fn dir(cmd: &str) -> Result<std::path::PathBuf> {
|
||||
crash::default_dir().ok_or_else(|| bad(cmd, "no crash folder on this system"))
|
||||
}
|
||||
@@ -143,6 +182,7 @@ fn crash_test(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
const PROFILE_CONTRACT: crate::schema::TypedContract<crate::schema::diagnostics::ProfileParams> = crate::schema::TypedContract::new();
|
||||
|
||||
const KERNEL_CONTRACT: crate::schema::TypedContract<crate::schema::diagnostics::KernelParams> = crate::schema::TypedContract::new();
|
||||
const VALIDATION_CONTRACT: crate::schema::TypedContract<crate::schema::diagnostics::ValidationParams> = crate::schema::TypedContract::new();
|
||||
|
||||
fn validation(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -1124,8 +1124,7 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
/// While the profiler records, a STEP import's reply carries its own profile: the import's
|
||||
/// stages and SMLib's calls, as diagnostics.profile reports them.
|
||||
#[cfg(feature = "smlib")]
|
||||
/// stages and the kernel's calls, as diagnostics.profile reports them.
|
||||
#[test]
|
||||
fn a_step_import_reports_its_profile_while_the_profiler_records() {
|
||||
let _serial = crate::schema::diagnostics::PROFILE_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
@@ -1144,7 +1143,7 @@ mod tests {
|
||||
let p = &out["profile"];
|
||||
let rows = p["rows"].as_array().unwrap();
|
||||
let has = |cat: &str| rows.iter().any(|r| r["category"] == cat);
|
||||
assert!(has("import") && has("smlib"), "{p}");
|
||||
assert!(has("import") && (has("solidcore") || has("smlib")), "{p}");
|
||||
assert!(p["by_category"].as_array().is_some_and(|c| !c.is_empty()) && p["wall_ms"].as_f64().is_some_and(|w| w > 0.0), "{p}");
|
||||
}
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ mod component_clone;
|
||||
mod component_clone_assembly;
|
||||
mod construct;
|
||||
mod delete;
|
||||
mod diagnostics;
|
||||
pub(crate) mod diagnostics;
|
||||
mod edit;
|
||||
mod face;
|
||||
mod features;
|
||||
|
||||
@@ -330,6 +330,44 @@ impl From<solidcraft_kernel::Validation> for ValidationMode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Read, or set, which kernel answers every operation.
|
||||
#[derive(Debug, Default, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct KernelParams {
|
||||
/// The kernel to use from now on. Default: leave it as it is. `smlib` is refused on a build
|
||||
/// without the C++ kernel; `SOLIDCRAFT_KERNEL`, when set, wins over it.
|
||||
#[serde(default, deserialize_with = "kernel_choice")]
|
||||
pub choice: Option<KernelChoice>,
|
||||
}
|
||||
|
||||
/// A geometry kernel.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum KernelChoice {
|
||||
/// solidcore, the Rust port of SMLib (the default).
|
||||
Solidcore,
|
||||
/// The C++ SMLib kernel.
|
||||
Smlib,
|
||||
}
|
||||
|
||||
fn kernel_choice<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<KernelChoice>, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::Null => Ok(None),
|
||||
Value::String(s) if s == "solidcore" => Ok(Some(KernelChoice::Solidcore)),
|
||||
Value::String(s) if s == "smlib" => Ok(Some(KernelChoice::Smlib)),
|
||||
_ => Err(serde::de::Error::custom(super::check::whole("`choice` is solidcore or smlib"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The reply of `diagnostics.kernel`.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct KernelReply {
|
||||
/// The kernel in force now.
|
||||
pub choice: KernelChoice,
|
||||
/// Whether `SOLIDCRAFT_KERNEL` chose it.
|
||||
pub environment: bool,
|
||||
}
|
||||
|
||||
/// Read, or set, when SMLib's full check runs on the features computed from now on.
|
||||
#[derive(Debug, Default, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
|
||||
@@ -2,7 +2,7 @@ use serde_json::{Value, json};
|
||||
|
||||
use super::{
|
||||
CrashReport, CrashReportList, CrashReportParams, CrashReportsClearParams, CrashReportsCleared, CrashReportsParams, CrashTestMode,
|
||||
CrashTestParams, ProfileParams, ValidationParams,
|
||||
CrashTestParams, KernelParams, ProfileParams, ValidationParams,
|
||||
};
|
||||
use crate::Session;
|
||||
use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
|
||||
@@ -16,6 +16,7 @@ fn schemas_and_the_key_check_agree() {
|
||||
assert_keys(input_schema_for::<CrashTestParams>(), &["mode"]);
|
||||
assert_keys(input_schema_for::<ProfileParams>(), &["enabled", "reset", "top", "trace"]);
|
||||
assert_keys(input_schema_for::<ValidationParams>(), &["mode"]);
|
||||
assert_keys(input_schema_for::<KernelParams>(), &["choice"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -29,6 +30,8 @@ fn strict_keeps_todays_errors() {
|
||||
("diagnostics.profile", json!({"trace": 5})),
|
||||
("diagnostics.validation", json!({"mode": "each step"})),
|
||||
("diagnostics.validation", json!({"mode": true})),
|
||||
("diagnostics.kernel", json!({"choice": "cpp"})),
|
||||
("diagnostics.kernel", json!({"choice": 1})),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -151,6 +154,94 @@ fn diagnostics_profile_reports_commands_features_and_the_kernel() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Tests that set the process-wide kernel choice run one at a time, and put `solidcore` back
|
||||
/// however they end (a failed assertion included).
|
||||
struct KernelChoice(#[allow(dead_code)] std::sync::MutexGuard<'static, ()>);
|
||||
|
||||
static KERNEL_TESTS: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
impl KernelChoice {
|
||||
fn take() -> Self {
|
||||
KernelChoice(KERNEL_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for KernelChoice {
|
||||
fn drop(&mut self) {
|
||||
solidcraft_kernel::kernel_route::set_choice(solidcraft_kernel::kernel_route::Backend::Solidcore);
|
||||
}
|
||||
}
|
||||
|
||||
/// diagnostics.kernel says the kernel in force and whether the environment chose it, and its
|
||||
/// `choice` sets it (unless SOLIDCRAFT_KERNEL overrides it).
|
||||
///
|
||||
/// The choice is process-wide and the other tests in this binary build bodies meanwhile, so only
|
||||
/// `solidcore` is set through the command; what `smlib` asks for is read from `kernel_asked`.
|
||||
#[test]
|
||||
fn diagnostics_kernel_reports_and_sets_the_choice() {
|
||||
use solidcraft_kernel::kernel_route as route;
|
||||
let _choice = KernelChoice::take();
|
||||
let mut s = Session::default();
|
||||
let r = s.execute("diagnostics.kernel", &json!({})).unwrap();
|
||||
let environment = route::overridden();
|
||||
assert_eq!(r, json!({ "choice": route::choice().id(), "environment": environment }));
|
||||
let r = s.execute("diagnostics.kernel", &json!({ "choice": "solidcore" })).unwrap();
|
||||
assert!(environment || r["choice"] == json!("solidcore"), "{r}");
|
||||
assert_eq!(crate::cmd::diagnostics::kernel_asked(&json!("solidcore"), false).unwrap(), route::Backend::Solidcore);
|
||||
assert_eq!(crate::cmd::diagnostics::kernel_asked(&json!("solidcore"), true).unwrap(), route::Backend::Solidcore);
|
||||
assert_eq!(crate::cmd::diagnostics::kernel_asked(&json!("smlib"), true).unwrap(), route::Backend::Smlib);
|
||||
}
|
||||
|
||||
/// `smlib` on a build without the C++ kernel is refused as not available, whichever kernel is in
|
||||
/// force, and leaves the choice alone: never an answer from the other kernel. Built with it, the
|
||||
/// command would move the other tests' bodies, so `kernel_asked` alone is asked.
|
||||
#[test]
|
||||
fn diagnostics_kernel_refuses_smlib_on_a_build_without_it() {
|
||||
let _choice = KernelChoice::take();
|
||||
let refused = crate::cmd::diagnostics::kernel_asked(&json!("smlib"), false).unwrap_err();
|
||||
assert!(matches!(&refused, crate::EngineError::Disabled(cmd, _) if cmd == "diagnostics.kernel"), "{refused}");
|
||||
if !solidcraft_kernel::smlib_built() {
|
||||
let mut s = Session::default();
|
||||
let before = s.execute("diagnostics.kernel", &json!({})).unwrap();
|
||||
assert!(matches!(s.execute("diagnostics.kernel", &json!({"choice": "smlib"})), Err(crate::EngineError::Disabled(..))));
|
||||
assert_eq!(s.execute("diagnostics.kernel", &json!({})).unwrap(), before);
|
||||
}
|
||||
}
|
||||
|
||||
/// An unknown or mistyped choice is an error that changes nothing; no hostile value panics.
|
||||
#[test]
|
||||
fn diagnostics_kernel_refuses_unknown_choices() {
|
||||
let _choice = KernelChoice::take();
|
||||
let mut s = Session::default();
|
||||
let before = s.execute("diagnostics.kernel", &json!({})).unwrap()["choice"].clone();
|
||||
let huge = "solidcore".repeat(100_000);
|
||||
for bad in [
|
||||
json!("truck"),
|
||||
json!("SMLIB"),
|
||||
json!(""),
|
||||
json!(huge),
|
||||
json!("routed"),
|
||||
json!("routed\0"),
|
||||
json!(5),
|
||||
json!(true),
|
||||
json!(["smlib"]),
|
||||
json!({"choice": "smlib"}),
|
||||
] {
|
||||
match s.execute("diagnostics.kernel", &json!({ "choice": bad })) {
|
||||
Err(crate::EngineError::BadParams { .. }) => {}
|
||||
other => panic!("`{}` was not refused: {:?}", bad.as_str().map_or(0, str::len), other.map_err(|e| e.to_string())),
|
||||
}
|
||||
}
|
||||
for v in crate::tests::hostile_values() {
|
||||
for p in [json!({ "choice": v.clone() }), v] {
|
||||
if let Err(crate::EngineError::Internal(_, msg)) = s.execute("diagnostics.kernel", &p) {
|
||||
panic!("diagnostics.kernel {p}: {msg}");
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(s.execute("diagnostics.kernel", &json!({})).unwrap()["choice"], before);
|
||||
}
|
||||
|
||||
/// Features are checked once each by default; the command reads and sets the mode, and the mode
|
||||
/// is the user's: it stays when another design is started and when everything is computed again.
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user