diff --git a/README.md b/README.md index 8102114..fa5337f 100644 --- a/README.md +++ b/README.md @@ -352,6 +352,34 @@ The simulation is a bounded model, not a production digital twin. Real payment providers, adversarial security coverage, database transactions, model changes, and live network failure behavior have not been qualified. +### Planner request schemas + +`shadow-plan` accepts schema 1 with its existing string keys and response fields. +Schema 2 keeps the same request shape and adds explicit keys in `symbols` and +test `dependencies`. Use `function:`, `file:`, `directory:`, +`closure:`, `module:`, `session`, or `unobserved`. `directory:` +represents the repository root. Use unique map keys and nonblank fingerprints +in both inventories, including the shared fingerprint. Unknown key kinds or +blank fingerprints reject a schema 2 request. + +Schema 2 can reuse existing evidence when a function key is added. Changes to +the values of existing keys and removals of function, file or directory keys +select the tests that depended on those keys. A removed module, other key-set +changes, missing or empty evidence, or a changed shared fingerprint expand +the plan. A failed test or a receipt with empty or unknown dependencies is +always selected. Collectors must fingerprint binding, discovery and runtime +changes that can affect previous tests, even when a function addition itself +is harmless. To detect unobserved module removals, include the full module +inventory independently of observed test dependencies. + +An expanded schema 2 result includes one `expand_reason` code in priority +order: `no_baseline`, `shared_input_changed`, `removed_module`, +`inventory_changed`, or `empty_baseline`. Successful bounded plans omit +`expand_reason`. Callers must run the full current inventory on expansion, +including tests absent from the baseline. They must check current test +collection before using any bounded plan. The bundled shadow adapter still +uses schema 1. + ### Large shadow plans The Python adapter automatically partitions baseline test receipts by encoded byte diff --git a/src/shadow.rs b/src/shadow.rs index df127eb..242de2b 100644 --- a/src/shadow.rs +++ b/src/shadow.rs @@ -30,31 +30,131 @@ pub struct Request { #[derive(Debug, Serialize)] pub struct Plan { pub expand: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub expand_reason: Option, pub selected: Vec, pub reasons: BTreeMap, } +#[derive(Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum ExpandReason { + NoBaseline, + EmptyBaseline, + SharedInputChanged, + RemovedModule, + InventoryChanged, +} + +#[derive(PartialEq, Eq)] +enum InputKind { + Function, + File, + Directory, + Closure, + Module, + Session, + Unobserved, +} + +fn input_kind(key: &str) -> Option { + use InputKind::*; + match key.split_once(':') { + Some(("function", name)) if !name.is_empty() => Some(Function), + Some(("file", path)) if !path.is_empty() => Some(File), + Some(("directory", _)) => Some(Directory), + Some(("closure", name)) if !name.is_empty() => Some(Closure), + Some(("module", path)) if !path.is_empty() => Some(Module), + None if key == "session" => Some(Session), + None if key == "unobserved" => Some(Unobserved), + _ => None, + } +} + +fn inventory_expansion(request: &Request, old: &Baseline) -> Option { + use ExpandReason::*; + if request.schema == 1 { + return old + .symbols + .keys() + .ne(request.symbols.keys()) + .then_some(InventoryChanged); + } + + let mut inventory_changed = old.symbols.is_empty() || request.symbols.is_empty(); + for key in old + .symbols + .keys() + .filter(|key| !request.symbols.contains_key(*key)) + { + match input_kind(key) { + Some(InputKind::Module) => return Some(RemovedModule), + Some(InputKind::Function | InputKind::File | InputKind::Directory) => {} + _ => inventory_changed = true, + } + } + if inventory_changed + || request.symbols.keys().any(|key| { + input_kind(key) != Some(InputKind::Function) && !old.symbols.contains_key(key) + }) + { + return Some(InventoryChanged); + } + None +} + pub fn plan(request: Request) -> Result { - if request.schema != 1 || request.symbols.is_empty() { + if !matches!(request.schema, 1 | 2) || (request.schema == 1 && request.symbols.is_empty()) { return Err("invalid shadow request schema or empty symbol inventory".into()); } + if request.schema == 2 { + if request.shared.trim().is_empty() + || request + .baseline + .iter() + .any(|old| old.shared.trim().is_empty()) + { + return Err("missing shared fingerprint in shadow request".into()); + } + for (key, fingerprint) in request + .symbols + .iter() + .chain(request.baseline.iter().flat_map(|old| old.symbols.iter())) + { + if input_kind(key).is_none() { + return Err("invalid typed input key in shadow request".into()); + } + if fingerprint.trim().is_empty() { + return Err("missing typed input fingerprint in shadow request".into()); + } + } + } + + use ExpandReason::*; + let expansion = match &request.baseline { + None => Some(NoBaseline), + Some(old) if old.shared != request.shared => Some(SharedInputChanged), + Some(old) => inventory_expansion(&request, old) + .or_else(|| old.tests.is_empty().then_some(EmptyBaseline)), + }; let mut result = Plan { - expand: true, + expand: expansion.is_some(), + expand_reason: if request.schema == 2 { expansion } else { None }, selected: Vec::new(), reasons: BTreeMap::new(), }; let Some(old) = request.baseline else { return Ok(result); }; - result.expand = old.shared != request.shared - || old.symbols.keys().ne(request.symbols.keys()) - || old.tests.is_empty(); - let changed: BTreeSet<_> = request - .symbols - .iter() - .filter(|(key, value)| old.symbols.get(*key) != Some(value)) - .map(|(key, _)| key) - .collect(); + let changed: BTreeSet<_> = if result.expand { + BTreeSet::new() + } else { + old.symbols + .iter() + .filter(|(key, value)| request.symbols.get(*key) != Some(value)) + .map(|(key, _)| key) + .collect() + }; for (id, evidence) in old.tests { let reason = if result.expand { Some("shared input or inventory changed") @@ -63,11 +163,15 @@ pub fn plan(request: Request) -> Result { || evidence .dependencies .iter() - .any(|d| !request.symbols.contains_key(d)) + .any(|d| !old.symbols.contains_key(d)) { Some("failed or incomplete dependency evidence") } else if evidence.dependencies.iter().any(|d| changed.contains(d)) { - Some("called function changed") + Some(if request.schema == 1 { + "called function changed" + } else { + "tracked input changed" + }) } else { None }; diff --git a/tests/shadow.rs b/tests/shadow.rs index beba060..c1fa75d 100644 --- a/tests/shadow.rs +++ b/tests/shadow.rs @@ -1,4 +1,4 @@ -use panthera::shadow::{Baseline, Request, TestEvidence, plan}; +use panthera::shadow::{Baseline, ExpandReason, Request, TestEvidence, plan}; use std::collections::{BTreeMap, BTreeSet}; fn request() -> Request { @@ -81,13 +81,216 @@ fn failed_empty_and_unknown_dependencies_cannot_be_reused() { #[test] fn rejects_unknown_schema_and_empty_inventory() { let mut input = request(); - input.schema = 2; + input.schema = 3; assert!(plan(input).is_err()); let mut input = request(); input.symbols.clear(); assert!(plan(input).is_err()); } +#[test] +fn legacy_expansion_keeps_the_schema_one_wire_format() { + let mut input = request(); + input.symbols.insert("new_function".into(), "v1".into()); + assert_eq!( + serde_json::to_value(plan(input).unwrap()).unwrap(), + serde_json::json!({ + "expand": true, + "selected": ["cancel", "refresh"], + "reasons": { + "cancel": "shared input or inventory changed", + "refresh": "shared input or inventory changed" + } + }) + ); +} + +fn typed_request() -> Request { + serde_json::from_value(serde_json::json!({ + "schema": 2, + "shared": "same", + "symbols": { + "function:billing.py:cancel": "v1", + "module:billing.py": "bindings-v1", + "file:static/landing.html": "v1", + "directory:": "v1", + "closure:tests/test_landing.py": "v1", + "session": "v1", + "unobserved": "v1" + }, + "baseline": { + "shared": "same", + "symbols": { + "function:billing.py:cancel": "v1", + "module:billing.py": "bindings-v1", + "file:static/landing.html": "v1", + "directory:": "v1", + "closure:tests/test_landing.py": "v1", + "session": "v1", + "unobserved": "v1" + }, + "tests": { + "cancel": {"passed": true, "dependencies": ["function:billing.py:cancel", "session"]}, + "landing": {"passed": true, "dependencies": ["file:static/landing.html", "directory:", "closure:tests/test_landing.py", "session"]}, + "subprocess": {"passed": true, "dependencies": ["unobserved"]} + } + } + })) + .unwrap() +} + +#[test] +fn typed_function_addition_keeps_valid_evidence_and_honors_other_changes() { + let mut input = typed_request(); + input + .symbols + .insert("function:billing.py:refund".into(), "v1".into()); + let result = plan(input).unwrap(); + assert!(!result.expand); + assert_eq!(result.expand_reason, None); + assert!(result.selected.is_empty()); + + let mut input = typed_request(); + input + .symbols + .insert("function:billing.py:refund".into(), "v1".into()); + input + .symbols + .insert("closure:tests/test_landing.py".into(), "v2".into()); + let result = plan(input).unwrap(); + assert!(!result.expand); + assert_eq!(result.selected, ["landing"]); + assert_eq!(result.reasons["landing"], "tracked input changed"); +} + +#[test] +fn typed_input_changes_and_trackable_removals_select_consumers() { + for (key, expected) in [ + ("function:billing.py:cancel", vec!["cancel"]), + ("file:static/landing.html", vec!["landing"]), + ("directory:", vec!["landing"]), + ("closure:tests/test_landing.py", vec!["landing"]), + ("session", vec!["cancel", "landing"]), + ("unobserved", vec!["subprocess"]), + ] { + let mut input = typed_request(); + input.symbols.insert(key.into(), "v2".into()); + let result = plan(input).unwrap(); + assert!(!result.expand, "{key}"); + assert_eq!(result.selected, expected, "{key}"); + } + for (key, test) in [ + ("function:billing.py:cancel", "cancel"), + ("file:static/landing.html", "landing"), + ("directory:", "landing"), + ] { + let mut input = typed_request(); + input.symbols.remove(key); + let result = plan(input).unwrap(); + assert!(!result.expand, "{key}"); + assert_eq!(result.selected, [test]); + assert_eq!(result.reasons[test], "tracked input changed"); + } +} + +#[test] +fn typed_expansion_reasons_are_stable_and_select_the_baseline_inventory() { + for (reason, code) in [ + (ExpandReason::NoBaseline, "no_baseline"), + (ExpandReason::EmptyBaseline, "empty_baseline"), + (ExpandReason::SharedInputChanged, "shared_input_changed"), + (ExpandReason::RemovedModule, "removed_module"), + (ExpandReason::InventoryChanged, "inventory_changed"), + ] { + let mut input = typed_request(); + let expected = match reason { + ExpandReason::NoBaseline => { + input.baseline = None; + vec![] + } + ExpandReason::EmptyBaseline => { + input.baseline.as_mut().unwrap().tests.clear(); + vec![] + } + ExpandReason::SharedInputChanged => { + input.shared = "v2".into(); + vec!["cancel", "landing", "subprocess"] + } + ExpandReason::RemovedModule => { + // Removed modules take precedence over other inventory changes. + input.symbols.remove("module:billing.py"); + input.symbols.remove("closure:tests/test_landing.py"); + vec!["cancel", "landing", "subprocess"] + } + ExpandReason::InventoryChanged => { + input.symbols.insert("module:new.py".into(), "v1".into()); + vec!["cancel", "landing", "subprocess"] + } + }; + let result = plan(input).unwrap(); + assert!(result.expand); + assert_eq!(result.expand_reason, Some(reason)); + assert_eq!(result.selected, expected); + assert_eq!(serde_json::to_value(result).unwrap()["expand_reason"], code); + } +} + +#[test] +fn typed_plans_cannot_reuse_unknown_dependencies_or_invalid_inventories() { + let mut input = typed_request(); + input + .baseline + .as_mut() + .unwrap() + .tests + .get_mut("cancel") + .unwrap() + .dependencies + .insert("function:billing.py:unknown".into()); + let result = plan(input).unwrap(); + assert!(!result.expand); + assert_eq!(result.selected, ["cancel"]); + assert_eq!( + result.reasons["cancel"], + "failed or incomplete dependency evidence" + ); + + for key in ["untagged", "plugin:unknown", "module:", "session:other"] { + let mut input = typed_request(); + input.symbols.insert(key.into(), "v1".into()); + assert!(plan(input).is_err(), "{key}"); + let mut input = typed_request(); + input + .baseline + .as_mut() + .unwrap() + .symbols + .insert(key.into(), "v1".into()); + assert!(plan(input).is_err(), "{key}"); + } +} + +#[test] +fn matching_blank_fingerprints_cannot_authorize_reuse() { + for missing in ["", " \t"] { + let mut input = typed_request(); + input.shared = missing.into(); + input.baseline.as_mut().unwrap().shared = missing.into(); + assert!(plan(input).is_err()); + + let mut input = typed_request(); + let key = "function:billing.py:cancel"; + input.symbols.insert(key.into(), missing.into()); + input + .baseline + .as_mut() + .unwrap() + .symbols + .insert(key.into(), missing.into()); + assert!(plan(input).is_err()); + } +} + #[test] fn cli_reports_the_build_version() { for flag in ["--version", "-V"] {