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
12 changes: 7 additions & 5 deletions crates/stratum-lts/src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,11 +94,11 @@ pub struct Event {
}

/// An active parallel component paired with its provenance tag.
type Tagged = (Proc, OccKey);
pub(crate) type Tagged = (Proc, OccKey);

/// The instrumented start state: the start term's active components, each tagged
/// with its [`OccKey::Initial`] flatten-index.
fn initial_state(start: &Proc) -> Vec<Tagged> {
pub(crate) fn initial_state(start: &Proc) -> Vec<Tagged> {
let mut comps = Vec::new();
flatten(start, &mut comps);
comps
Expand Down Expand Up @@ -216,12 +216,14 @@ mod tests {
use super::*;
use stratum_core::term::{drop_, input, lift, par, quote, zero};

/// A family of structurally-distinct channels: `ch(0) = ⌜0⌝`,
/// `ch(1) = ⌜*⌜0⌝⌝`, `ch(2) = ⌜*⌜*⌜0⌝⌝⌝`, … — pairwise `≢N`.
/// A family of genuinely `≡N`-distinct channels: `ch(0) = ⌜0⌝`,
/// `ch(1) = ⌜⌜0⌝⟨|0|⟩⌝`, `ch(2) = ⌜⌜0⌝⟨|⌜0⌝⟨|0|⟩|⟩⌝`, … Note `*⌜P⌝ ≡ P`, so
/// a drop/quote nesting would collapse to `⌜0⌝`; a (non-reducing, quoted)
/// lift nesting stays pairwise `≢N`.
fn ch(tag: u64) -> Name {
let mut p = zero();
for _ in 0..tag {
p = drop_(quote(p));
p = lift(quote(zero()), p);
}
quote(p)
}
Expand Down
2 changes: 1 addition & 1 deletion crates/stratum-lts/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ use stratum_core::{
mod event;
mod trace;
pub use event::{run_events, Event, EventKey, OccKey};
pub use trace::Trace;
pub use trace::{traces, Trace};

/// A labelled transition to another state.
#[derive(Clone, Debug, PartialEq, Eq)]
Expand Down
178 changes: 175 additions & 3 deletions crates/stratum-lts/src/trace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,11 @@
//! one-liner where possible (`a ; (b ∥ c) ; d`), else an honest poset marker;
//! and the Hasse diagram (covering edges only) as Graphviz.

use std::collections::{BTreeSet, HashMap};
use std::collections::{BTreeSet, HashMap, HashSet};

use stratum_core::Name;
use stratum_core::{Name, Proc};

use crate::event::{enabled_events, initial_state, Tagged};
use crate::{escape, Event, EventKey};

/// The trace of a run: a labelled partial order over events.
Expand Down Expand Up @@ -167,6 +168,71 @@ impl Trace {
}
}

/// The set of traces of `start` — its behaviour as a quotient of its runs.
///
/// Explores **every** branch of the reduction (all interleavings and all
/// choices), turns each maximal run into a [`Trace`], and deduplicates on
/// [`Trace::key`]. Interleavings collapse for free: two orderings of the same
/// independent events fire the same event *set*, so they share a key and count
/// once. Genuine branches (a race, a different receiver) fire different events,
/// so they stay distinct.
///
/// This is the *correctness* path: it materializes the `n!` interleavings before
/// the dedup folds them away. `max_events` bounds any single run and `max_traces`
/// the result; the boolean is `true` when either bound cut the exploration short
/// (as [`crate::Lts::is_truncated`]).
#[must_use]
pub fn traces(start: &Proc, max_events: usize, max_traces: usize) -> (Vec<Trace>, bool) {
let mut e = Enumerator {
seen: HashSet::new(),
out: Vec::new(),
truncated: false,
max_events,
max_traces,
};
let state = initial_state(start);
e.dfs(&state, &mut Vec::new());
(e.out, e.truncated)
}

/// Depth-first enumeration state for [`traces`].
struct Enumerator {
seen: HashSet<BTreeSet<EventKey>>,
out: Vec<Trace>,
truncated: bool,
max_events: usize,
max_traces: usize,
}

impl Enumerator {
/// Explore every event firable from `state`, extending `run`. On reaching a
/// terminal state, record the maximal run's trace (deduped on its key).
/// Recursion depth is bounded by `max_events`.
fn dfs(&mut self, state: &[Tagged], run: &mut Vec<Event>) {
let enabled = enabled_events(state);
if enabled.is_empty() {
let t = Trace::from_run(run);
if self.seen.insert(t.key()) {
if self.out.len() < self.max_traces {
self.out.push(t);
} else {
self.truncated = true; // a distinct trace we could not keep
}
}
return;
}
if run.len() >= self.max_events {
self.truncated = true; // a run longer than the bound was cut
return;
}
for (ev, next) in enabled {
run.push(ev);
self.dfs(&next, run);
run.pop();
}
}
}

/// Transitive closure of `edges` over `n` nodes, as a reachability matrix
/// (`r[i][j]` = a directed path `i → … → j` of length ≥ 1 exists).
#[allow(clippy::needless_range_loop)] // Floyd–Warshall reads across rows by index
Expand Down Expand Up @@ -305,10 +371,12 @@ mod tests {
use stratum_core::term::{drop_, input, lift, par, quote, zero};
use stratum_core::Name;

// Genuinely ≡N-distinct channels. Note `*⌜P⌝ ≡ P`, so a drop/quote nesting
// would collapse to `⌜0⌝`; nesting a (non-reducing) lift instead does not.
fn ch(tag: u64) -> Name {
let mut p = zero();
for _ in 0..tag {
p = drop_(quote(p));
p = lift(quote(zero()), p);
}
quote(p)
}
Expand Down Expand Up @@ -422,4 +490,108 @@ mod tests {
};
assert_eq!(t.to_ascii(format_name), "(poset, 4 events)");
}

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

type LabelRun = Vec<(Name, Name)>;

fn labels_of(lin: &[EventKey]) -> LabelRun {
lin.iter()
.map(|k| (k.channel.clone(), k.message.clone()))
.collect()
}

/// The set of label-sequences of every linearization of every trace.
fn trace_label_runs(ts: &[Trace]) -> BTreeSet<LabelRun> {
ts.iter()
.flat_map(Trace::linearizations)
.map(|l| labels_of(&l))
.collect()
}

/// The set of maximal label-runs of the full LTS (DFS to terminal states).
/// Assumes an **acyclic** LTS (the round-trip inputs are replication-free); a
/// replicating term would need a visited guard to avoid looping.
fn lts_label_runs(lts: &crate::Lts) -> BTreeSet<LabelRun> {
fn go(lts: &crate::Lts, s: usize, path: &mut LabelRun, out: &mut BTreeSet<LabelRun>) {
let ts = lts.transitions(s);
if ts.is_empty() {
out.insert(path.clone());
return;
}
for t in ts {
path.push((t.label.clone(), t.message.clone()));
go(lts, t.target, path, out);
path.pop();
}
}
let mut out = BTreeSet::new();
go(lts, lts.initial(), &mut Vec::new(), &mut out);
out
}

#[test]
fn terminal_start_is_one_empty_trace() {
let (ts, truncated) = traces(&zero(), 10, 10);
assert!(!truncated);
assert_eq!(ts.len(), 1);
assert!(ts[0].is_empty());
}

#[test]
fn interleaving_absorbed_branching_kept() {
let a = ch(1);
let b = ch(2);
// Diamond: two independent reactions collapse to ONE trace (2 linearizations).
let diamond = par([
lift(a.clone(), zero()),
input(a.clone(), |_| zero()),
lift(b.clone(), zero()),
input(b.clone(), |_| zero()),
]);
let (ts, _) = traces(&diamond, 10, 100);
assert_eq!(ts.len(), 1);
assert_eq!(ts[0].linearizations().count(), 2);

// Chain: dependent reactions -> ONE trace, ONE linearization.
let chain = par([
lift(ch(1), lift(ch(2), zero())),
input(ch(1), drop_),
input(ch(2), |_| zero()),
]);
let (ts2, _) = traces(&chain, 10, 100);
assert_eq!(ts2.len(), 1);
assert_eq!(ts2[0].linearizations().count(), 1);

// Race: one output, two receivers -> TWO distinct traces (conflict).
let a2 = ch(2);
let b2 = ch(3);
let race = par([
lift(ch(1), zero()),
input(ch(1), move |_| lift(a2.clone(), zero())),
input(ch(1), move |_| lift(b2.clone(), zero())),
]);
let (ts3, _) = traces(&race, 10, 100);
assert_eq!(ts3.len(), 2);
}

#[test]
fn unfolding_round_trip_matches_full_lts() {
// A causal chain (x ; a) concurrent with an independent reaction (b):
// exercises both concurrency and causality. Every linearization of every
// trace must equal, as a label sequence, a maximal run of the full LTS.
let mk = || {
par([
lift(ch(1), lift(ch(2), zero())), // x!(a!0)
input(ch(1), drop_), // x(y).*y
input(ch(2), |_| zero()), // a(z).0
lift(ch(3), zero()), // b!0
input(ch(3), |_| zero()), // b(y).0
])
};
let (ts, truncated) = traces(&mk(), 20, 1000);
assert!(!truncated);
let lts = crate::Lts::explore(&mk(), 1000);
assert_eq!(trace_label_runs(&ts), lts_label_runs(&lts));
}
}
Loading