Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions crates/stratum-lts/src/trace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,30 @@ impl Trace {
s.push_str("}\n");
s
}

/// The projection onto the events an agent can see: keep the events
/// satisfying `keep`, ordered by the **induced** causal order (`a ≤ b` in the
/// projection iff `a ≤ b` here). Two traces with the same projection are ones
/// the agent cannot tell apart — the raw material of knowledge.
#[must_use]
pub fn project(&self, keep: impl Fn(&EventKey) -> bool) -> Trace {
let reach = closure(self.events.len(), self.leq.iter().copied());
let kept: Vec<usize> = (0..self.events.len())
.filter(|&i| keep(&self.events[i]))
.collect();
let events: Vec<EventKey> = kept.iter().map(|&i| self.events[i].clone()).collect();
// The full induced order over the kept events, then reduce to covering.
let mut direct = BTreeSet::new();
for (na, &oa) in kept.iter().enumerate() {
for (nb, &ob) in kept.iter().enumerate() {
if na != nb && reach[oa][ob] {
direct.insert((na, nb));
}
}
}
let leq = covering_relation(events.len(), &direct);
Trace { events, leq }
}
}

/// The set of traces of `start` — its behaviour as a quotient of its runs.
Expand Down Expand Up @@ -517,6 +541,25 @@ mod tests {
assert_eq!(t.to_ascii(format_name), "(poset, 4 events)");
}

#[test]
fn projection_keeps_induced_order() {
// x ; a (a causal chain). Projecting onto {a} drops x and its edge;
// projecting onto both keeps the single covering edge.
let chain = par([
lift(ch(1), lift(ch(2), zero())),
input(ch(1), drop_),
input(ch(2), |_| zero()),
]);
let (evs, _) = run_events(&chain, 10);
let t = Trace::from_run(&evs);
let onto_a = t.project(|e| stratum_core::name_equiv(&e.channel, &ch(2)));
assert_eq!(onto_a.len(), 1);
assert_eq!(onto_a.covering().len(), 0);
let both = t.project(|_| true);
assert_eq!(both.len(), 2);
assert_eq!(both.covering().len(), 1);
}

// --- traces() enumeration ---

type LabelRun = Vec<(Name, Name)>;
Expand Down
141 changes: 131 additions & 10 deletions crates/stratum-notebook/src/eval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,17 @@
//! toolkit logic (parse, explore, check, bisim, typecheck) is invoked here and
//! immediately rendered; nothing panics on bad input.

use stratum::core::{canonicalize, step_labeled, Name, Proc};
use stratum::core::{canonicalize, name_equiv, step_labeled, Name, Proc};
use stratum::equiv::{strong_barbed_bisimilar, weak_barbed_bisimilar};
use stratum::logic::{counterexample, holds_checked, witness};
use stratum::lts::{format_name, Lts};
use stratum::lts::{format_name, traces, EventKey, Lts, Trace};
use stratum::syntax::{name_to_latex, parse_with_aliases, to_latex, to_source, ParseError};
use stratum::types::{check as typecheck, Env, Ty};

use crate::formula::parse_formula;
use crate::render::{
display_math, render_checked, render_core, render_lts, render_proc, render_run,
render_typecheck, render_verdict, MimeBundle,
display_math, render_checked, render_core, render_lts, render_proc, render_run, render_trace,
render_traces, render_typecheck, render_verdict, MimeBundle,
};
use crate::{default_observations, CellError, CellOutcome, Namespace, Obj, Reduction, Repr};

Expand Down Expand Up @@ -126,7 +126,10 @@ fn run_meta(rest: &str, ns: &mut Namespace) -> Result<Vec<MimeBundle>, CellError
"counterexample" => dir_counterexample(after.trim(), ns),
"bisim" => dir_bisim(after.trim(), ns),
"step" => dir_step(after.trim(), ns),
"traces" => dir_traces(after.trim(), ns),
"trace" => dir_trace(after.trim(), ns),
"lin" => dir_lin(after.trim(), ns),
"project" => dir_project(after.trim(), ns),
"typecheck" => dir_typecheck(after.trim(), ns),
"ascii" => dir_repr(Some(Repr::Ascii), ns),
"latex" => dir_repr(Some(Repr::Latex), ns),
Expand Down Expand Up @@ -366,13 +369,19 @@ fn dir_step(rest: &str, ns: &mut Namespace) -> Result<Vec<MimeBundle>, CellError
}])
}

/// `#trace <ltsname>` — a sample run from the initial state.
/// `#trace <ltsname>` samples a run from an LTS; `#trace <tracesname>[i]` shows
/// one enumerated trace's partial order.
fn dir_trace(rest: &str, ns: &mut Namespace) -> Result<Vec<MimeBundle>, CellError> {
let name = rest.trim();
if name.is_empty() {
return arity_err("trace", "#trace <ltsname>");
let arg = rest.trim();
if arg.is_empty() {
return arity_err("trace", "#trace <ltsname> | <tracesname>[i]");
}
let lts = lookup_lts(name, ns)?;
// A `name[i]` handle selects one trace from a `#traces` set.
if parse_index(arg).is_some() {
let t = resolve_trace(arg, ns)?;
return Ok(vec![render_trace(&t, ns.aliases(), ns.repr())]);
}
let lts = lookup_lts(arg, ns)?;
// Follow the first outgoing transition from each state until a terminal
// state or a repeat (guarding against cycles), bounded for safety.
let mut run: Vec<(Name, usize)> = Vec::new();
Expand Down Expand Up @@ -402,6 +411,115 @@ fn dir_trace(rest: &str, ns: &mut Namespace) -> Result<Vec<MimeBundle>, CellErro
)])
}

/// `#traces <procname|inline DSL> [bound=N] -> name` — the trace-set.
fn dir_traces(rest: &str, ns: &mut Namespace) -> Result<Vec<MimeBundle>, CellError> {
let (pre, bind) = split_arrow(rest);
let opts = Opts::parse(pre);
let target = opts.target.trim();
if target.is_empty() {
return arity_err("traces", "#traces <procname|DSL> [bound=N] -> name");
}
let proc = resolve_proc(target, ns)?;
let bound = opts.bound.unwrap_or(DEFAULT_BOUND);
let (ts, truncated) = traces(&proc, bound, bound);
let bundle = render_traces(&ts, truncated, ns.aliases(), ns.repr());
if let Some(name) = bind {
ns.insert(
name,
Obj::Traces {
traces: ts,
truncated,
},
);
}
Ok(vec![bundle])
}

/// `#lin <tracesname>[i]` — the linearizations of one trace, as label words.
fn dir_lin(rest: &str, ns: &mut Namespace) -> Result<Vec<MimeBundle>, CellError> {
let t = resolve_trace(rest.trim(), ns)?;
let lins: Vec<Vec<EventKey>> = t.linearizations().collect();
let mut plain = format!("{} linearization(s):\n", lins.len());
for (i, lin) in lins.iter().enumerate() {
let word: Vec<String> = lin.iter().map(|e| fold_channel(&e.channel, ns)).collect();
plain.push_str(&format!(" [{i}] {}\n", word.join(" · ")));
}
Ok(vec![MimeBundle::plain(plain)])
}

/// `#project <tracesname>[i] <channel[,channel]>` — one agent's view of a trace:
/// the events on the named channels, under the induced causal order.
fn dir_project(rest: &str, ns: &mut Namespace) -> Result<Vec<MimeBundle>, CellError> {
let (spec, chans) = rest.trim().split_once(char::is_whitespace).ok_or_else(|| {
CellError::new(
"DirectiveError",
"usage: #project <tracesname>[i] <channel[,channel]>",
)
})?;
let t = resolve_trace(spec.trim(), ns)?;
let names = resolve_names(&split_list(chans), ns)?;
if names.is_empty() {
return Err(CellError::new(
"DirectiveError",
"usage: #project <tracesname>[i] <channel[,channel]> — name at least one channel",
));
}
let projected = t.project(|e| names.iter().any(|n| name_equiv(&e.channel, n)));
Ok(vec![render_trace(&projected, ns.aliases(), ns.repr())])
}

/// Fold a channel to its source alias for a listing, else its compact form.
fn fold_channel(name: &Name, ns: &Namespace) -> String {
ns.aliases()
.get(name)
.map_or_else(|| format_name(name), str::to_string)
}

/// Parse a `name[i]` handle into `(name, i)`, or `None` if it is not one.
fn parse_index(spec: &str) -> Option<(&str, usize)> {
let open = spec.find('[')?;
let close = spec.find(']')?;
if close != spec.len() - 1 || close < open {
return None;
}
let name = spec[..open].trim();
if !is_ident(name) {
return None;
}
let idx: usize = spec[open + 1..close].trim().parse().ok()?;
Some((name, idx))
}

/// Resolve a `name[i]` handle to the `i`-th trace of a `#traces` binding.
fn resolve_trace(spec: &str, ns: &Namespace) -> Result<Trace, CellError> {
let spec = spec.trim();
let (name, idx) = parse_index(spec).ok_or_else(|| {
CellError::new(
"TraceError",
format!("expected a trace handle `name[i]`, got `{spec}`"),
)
})?;
match ns.get(name) {
Some(Obj::Traces { traces, .. }) => traces.get(idx).cloned().ok_or_else(|| {
CellError::new(
"IndexError",
format!(
"`{name}` has {} trace(s); index {idx} is out of range",
traces.len()
),
)
}),
Some(other) => Err(CellError::new(
"NameError",
format!("`{name}` is a {}, not a trace-set", other.kind()),
)),
None => Err(CellError::new(
"NameError",
format!("no trace-set named `{name}` (bind one with `#traces ... -> {name}`)"),
)),
}
}

/// `#typecheck <procname|inline DSL> [with a:Ty, b:Ty, ...]`
fn dir_typecheck(rest: &str, ns: &mut Namespace) -> Result<Vec<MimeBundle>, CellError> {
let (target_src, env_src) = match split_on(rest, " with ") {
Expand Down Expand Up @@ -706,7 +824,10 @@ Stratum notebook cells:
#counterexample <invariant> on <lts> a run violating the invariant
#bisim <p> <q> [weak] [obs=a,b] barbed (bi)simulation verdict
#step <p> one-step reducts
#trace <lts> a sample run
#traces <p> [bound=N] -> tr the trace-set (partial orders)
#trace <lts> | tr[i] a sample run, or trace tr[i]
#lin tr[i] linearizations of trace tr[i]
#project tr[i] <a,b> one agent's view of trace tr[i]
#typecheck <p> [with a:Ty, b:Ty] channel-sort typecheck
#rune <newline> <script> run an embedded Rune script
#ascii / #latex output representation (`#repr` shows current)
Expand Down
11 changes: 10 additions & 1 deletion crates/stratum-notebook/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ use std::collections::HashMap;
use stratum::core::{canonicalize_name, Name, Proc};
use stratum::equiv::Verdict;
use stratum::logic::Checked;
use stratum::lts::Lts;
use stratum::lts::{Lts, Trace};
use stratum::syntax::Aliases;

pub use eval::evaluate;
Expand Down Expand Up @@ -116,6 +116,14 @@ pub enum Obj {
/// The reduction applied during exploration.
reduction: Reduction,
},
/// The set of traces produced by `#traces`, with a truncation flag; its
/// elements are addressed as `tr[i]`.
Traces {
/// The enumerated traces.
traces: Vec<Trace>,
/// Whether the enumeration hit a bound.
truncated: bool,
},
/// An equivalence verdict produced by `#bisim`.
Verdict(Verdict),
/// A model-checking result produced by `#check`.
Expand All @@ -135,6 +143,7 @@ impl Obj {
match self {
Obj::Proc(_) => "proc",
Obj::Lts { .. } => "lts",
Obj::Traces { .. } => "traces",
Obj::Verdict(_) => "verdict",
Obj::Checked(_) => "checked",
Obj::Bool(_) => "bool",
Expand Down
2 changes: 2 additions & 0 deletions crates/stratum-notebook/src/script.rs
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,8 @@ fn fn_get(ns: &SharedNs, name: &str) -> VmResult<Value> {
Obj::Bool(b) => rune::to_value(*b),
Obj::Int(i) => rune::to_value(*i),
Obj::Text(t) => rune::to_value(t.clone()),
// A trace-set has no first-class Rune type yet; expose its size.
Obj::Traces { traces, .. } => rune::to_value(traces.len() as i64),
};
match converted {
Ok(v) => VmResult::Ok(v),
Expand Down
7 changes: 7 additions & 0 deletions crates/stratum-notebook/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -532,6 +532,13 @@ fn inspect_obj(name: &str, obj: &Obj, ns: &Namespace) -> Inspection {
Obj::Bool(b) => format!("bool `{name}`\n {b}"),
Obj::Int(i) => format!("int `{name}`\n {i}"),
Obj::Text(t) => format!("text `{name}`\n {t}"),
Obj::Traces { traces, truncated } => {
let bound = if *truncated { " (truncated)" } else { "" };
format!(
"traces `{name}`\n {} trace(s){bound}; address one as `{name}[i]`",
traces.len(),
)
}
};
Inspection {
text_html: Some(format!(
Expand Down
75 changes: 75 additions & 0 deletions crates/stratum-notebook/tests/eval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -533,3 +533,78 @@ fn repr_reports_current_mode() {
let out = eval("#repr", &mut ns);
assert!(ok_display(&out).text_plain.contains("LaTeX"));
}

// ---------------------------------------------------------------------------
// #traces / tr[i] / #trace / #lin / #project
// ---------------------------------------------------------------------------

/// A diamond (two independent reactions) is one trace; a race is two.
#[test]
fn traces_binds_and_lists() {
let mut ns = Namespace::new();
let out = eval(
"#traces new a, b\na!(0) | a(x).0 | b!(0) | b(y).0 -> tr",
&mut ns,
);
let b = ok_display(&out);
assert!(
b.text_plain.contains("Traces: 1 traces"),
"{}",
b.text_plain
);
assert!(b.text_plain.contains("tr[0]"), "{}", b.text_plain);
// The binding is a trace-set.
assert!(matches!(ns.get("tr"), Some(Obj::Traces { .. })));
}

#[test]
fn trace_handle_selects_and_renders() {
let mut ns = Namespace::new();
eval(
"#traces new a, b\na!(0) | a(x).0 | b!(0) | b(y).0 -> tr",
&mut ns,
);
// `#trace tr[0]` shows the partial order; the diamond is a parallel form.
let out = eval("#trace tr[0]", &mut ns);
let b = ok_display(&out);
assert!(b.text_plain.contains("Trace: 2 events"), "{}", b.text_plain);
assert!(b.text_plain.contains(" ∥ "), "{}", b.text_plain);
}

#[test]
fn lin_lists_linearizations() {
let mut ns = Namespace::new();
eval(
"#traces new a, b\na!(0) | a(x).0 | b!(0) | b(y).0 -> tr",
&mut ns,
);
// Two concurrent events -> two linearizations.
let out = eval("#lin tr[0]", &mut ns);
let b = ok_display(&out);
assert!(b.text_plain.contains("2 linearization"), "{}", b.text_plain);
}

#[test]
fn project_restricts_to_an_agent() {
let mut ns = Namespace::new();
eval(
"#traces new a, b\na!(0) | a(x).0 | b!(0) | b(y).0 -> tr",
&mut ns,
);
// Projecting onto `a` keeps a single event.
let out = eval("#project tr[0] a", &mut ns);
let b = ok_display(&out);
assert!(b.text_plain.contains("Trace: 1 events"), "{}", b.text_plain);
}

#[test]
fn trace_handle_errors_are_clean() {
let mut ns = Namespace::new();
eval("#traces new a\na!(0) | a(x).0 -> tr", &mut ns);
// Out-of-range index.
let out = eval("#trace tr[9]", &mut ns);
assert!(out.error.is_some(), "expected an index error");
// Unknown trace-set.
let out = eval("#lin nope[0]", &mut ns);
assert!(out.error.is_some(), "expected a name error");
}
Loading
Loading