sim-lib-topology 0.1.1

Data-driven topology engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! Topology run-state and sequential core scheduler.

use std::collections::VecDeque;

use sim_kernel::{CapabilityName, Cx, Error, Expr, Result, Symbol};

use crate::{
    Budget, CompiledGraph, Edge, Graph,
    adapter::{call_target_expr, resolve_target},
    capability::topology_run_capability,
    verb::{VerbAction, run_core_node},
};

pub use crate::{
    run_cells::TopologyCells, run_nonlinear::TopologyNonlinearState,
    run_predicate::predicate_accepts,
};

/// Packet emitted from one node output port.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TopologyPacket {
    /// Source node index in the compiled graph.
    pub node_index: usize,
    /// Source output port.
    pub port: Symbol,
    /// Packet payload.
    pub expr: Expr,
}

/// Scheduled delivery to one node input port.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WorkItem {
    /// Destination node index in the compiled graph.
    pub node_index: usize,
    /// Destination input port.
    pub port: Symbol,
    /// Delivered payload.
    pub expr: Expr,
}

/// Basic event kind emitted by the sequential topology scheduler.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TopologyEventKind {
    /// A work item was queued.
    Enqueued,
    /// A node began executing.
    NodeStarted,
    /// A node emitted an output port packet.
    PortEmitted,
    /// An edge routed a packet.
    EdgeRouted,
    /// A public output was produced.
    OutputEmitted,
}

/// Compact execution event for inspection and later replay support.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TopologyEvent {
    /// Event kind.
    pub kind: TopologyEventKind,
    /// Node index associated with the event.
    pub node_index: usize,
    /// Optional port associated with the event.
    pub port: Option<Symbol>,
    /// Optional edge index associated with the event.
    pub edge_index: Option<usize>,
    /// Optional event payload.
    pub expr: Option<Expr>,
}

impl TopologyEvent {
    fn node(kind: TopologyEventKind, node_index: usize) -> Self {
        Self {
            kind,
            node_index,
            port: None,
            edge_index: None,
            expr: None,
        }
    }

    fn node_expr(kind: TopologyEventKind, node_index: usize, expr: Expr) -> Self {
        Self {
            kind,
            node_index,
            port: None,
            edge_index: None,
            expr: Some(expr),
        }
    }

    fn port(kind: TopologyEventKind, node_index: usize, port: Symbol, expr: Expr) -> Self {
        Self {
            kind,
            node_index,
            port: Some(port),
            edge_index: None,
            expr: Some(expr),
        }
    }

    fn edge(node_index: usize, port: Symbol, edge_index: usize, expr: Expr) -> Self {
        Self {
            kind: TopologyEventKind::EdgeRouted,
            node_index,
            port: Some(port),
            edge_index: Some(edge_index),
            expr: Some(expr),
        }
    }
}

/// Structured budget exhaustion details for a topology run.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TopologyBudgetError {
    /// Exhausted budget resource.
    pub resource: Symbol,
    /// Configured resource limit.
    pub limit: u32,
    /// Observed resource count.
    pub actual: u32,
}

impl TopologyBudgetError {
    /// Converts the budget error into a stable expression value.
    pub fn as_expr(&self) -> Expr {
        Expr::Map(vec![
            (
                Expr::Symbol(Symbol::new("kind")),
                Expr::Symbol(Symbol::new("topology-budget-exhausted")),
            ),
            (
                Expr::Symbol(Symbol::new("resource")),
                Expr::Symbol(self.resource.clone()),
            ),
            (
                Expr::Symbol(Symbol::new("limit")),
                Expr::String(self.limit.to_string()),
            ),
            (
                Expr::Symbol(Symbol::new("actual")),
                Expr::String(self.actual.to_string()),
            ),
        ])
    }

    fn into_error(self) -> Error {
        let value = self.as_expr();
        Error::Eval(format!(
            "topology budget exhausted: resource={} limit={} actual={} value={value:?}",
            self.resource, self.limit, self.actual,
        ))
    }
}

/// Runtime budget counters for one topology run.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BudgetLedger {
    limits: Budget,
    /// Scheduler steps consumed.
    pub steps: u32,
    /// Per-node visit counts.
    pub node_visits: Vec<u32>,
    /// Per-edge route counts.
    pub edge_visits: Vec<u32>,
    /// Public outputs emitted.
    pub outputs: u32,
    /// Nested eval-fabric calls.
    pub child_runs: u32,
}

impl BudgetLedger {
    /// Creates a zeroed budget ledger for a compiled graph.
    pub fn new(limits: Budget, node_count: usize, edge_count: usize) -> Self {
        Self {
            limits,
            steps: 0,
            node_visits: vec![0; node_count],
            edge_visits: vec![0; edge_count],
            outputs: 0,
            child_runs: 0,
        }
    }

    /// Records one scheduler step.
    pub fn record_step(&mut self) -> Result<()> {
        self.steps = self.steps.saturating_add(1);
        self.require_at_most(self.steps, self.limits.max_steps, "max-steps")
    }

    /// Records one node visit.
    pub fn record_node_visit(&mut self, node_index: usize) -> Result<()> {
        self.node_visits[node_index] = self.node_visits[node_index].saturating_add(1);
        self.require_at_most(
            self.node_visits[node_index],
            self.limits.max_node_visits,
            "max-node-visits",
        )
    }

    /// Records one edge traversal.
    pub fn record_edge_visit(&mut self, edge_index: usize, edge_limit: Option<u32>) -> Result<()> {
        self.edge_visits[edge_index] = self.edge_visits[edge_index].saturating_add(1);
        let limit = edge_limit
            .unwrap_or(self.limits.max_edge_visits)
            .min(self.limits.max_edge_visits);
        let resource = if edge_limit.is_some() {
            "edge-max-visits"
        } else {
            "max-edge-visits"
        };
        self.require_at_most(self.edge_visits[edge_index], limit, resource)
    }

    /// Records one public output.
    pub fn record_output(&mut self) -> Result<()> {
        self.outputs = self.outputs.saturating_add(1);
        self.require_at_most(self.outputs, self.limits.max_outputs, "max-outputs")
    }

    /// Records one nested eval-fabric call.
    pub fn record_child_run(&mut self) -> Result<()> {
        self.child_runs = self.child_runs.saturating_add(1);
        self.require_at_most(
            self.child_runs,
            self.limits.max_child_runs,
            "max-child-runs",
        )
    }

    /// Checks one buffered merge node against the run budget.
    pub fn check_merge_buffer(&self, buffered: usize) -> Result<()> {
        let actual = u32::try_from(buffered).unwrap_or(u32::MAX);
        self.require_at_most(actual, self.limits.max_steps, "merge-buffer")
    }

    fn require_at_most(&self, actual: u32, limit: u32, resource: &str) -> Result<()> {
        if actual <= limit {
            Ok(())
        } else {
            Err(TopologyBudgetError {
                resource: Symbol::new(resource),
                limit,
                actual,
            }
            .into_error())
        }
    }
}

/// Live state for a sequential topology run.
pub struct TopologyRun<'a> {
    graph: &'a Graph,
    plan: &'a CompiledGraph,
    queue: VecDeque<WorkItem>,
    outputs: Vec<Expr>,
    cells: TopologyCells,
    nonlinear: TopologyNonlinearState,
    /// Budget counters for this run.
    pub budget: BudgetLedger,
    events: Vec<TopologyEvent>,
}

impl<'a> TopologyRun<'a> {
    /// Creates a run with one boundary input expression.
    pub fn new(graph: &'a Graph, plan: &'a CompiledGraph, input: Expr) -> Result<Self> {
        let mut run = Self {
            graph,
            plan,
            queue: VecDeque::new(),
            outputs: Vec::new(),
            cells: TopologyCells::new(graph)?,
            nonlinear: TopologyNonlinearState::new(plan.nodes.len()),
            budget: BudgetLedger::new(graph.budget.clone(), plan.nodes.len(), plan.edges.len()),
            events: Vec::new(),
        };
        for input_node in &plan.input_nodes {
            run.enqueue(WorkItem {
                node_index: *input_node,
                port: Symbol::new("in"),
                expr: input.clone(),
            });
        }
        Ok(run)
    }

    /// Runs until the queue is exhausted.
    pub fn run(&mut self, cx: &mut Cx) -> Result<()> {
        while let Some(item) = self.queue.pop_front() {
            self.budget.record_step()?;
            self.budget.record_node_visit(item.node_index)?;
            self.events.push(TopologyEvent::node(
                TopologyEventKind::NodeStarted,
                item.node_index,
            ));

            let actions = run_core_node(
                cx,
                self.graph,
                self.plan,
                &mut self.budget,
                &mut self.cells,
                &mut self.nonlinear,
                &item,
            )?;
            for action in actions {
                match action {
                    VerbAction::Emit(packet) => {
                        self.events.push(TopologyEvent::port(
                            TopologyEventKind::PortEmitted,
                            packet.node_index,
                            packet.port.clone(),
                            packet.expr.clone(),
                        ));
                        self.route_packet(cx, packet)?;
                    }
                    VerbAction::Complete { node_index, expr } => {
                        self.push_output(node_index, expr)?
                    }
                }
            }
        }
        Ok(())
    }

    /// Returns public outputs in emission order.
    pub fn outputs(&self) -> &[Expr] {
        &self.outputs
    }

    /// Returns emitted execution events.
    pub fn events(&self) -> &[TopologyEvent] {
        &self.events
    }

    /// Returns run-local cell state.
    pub fn cells(&self) -> &TopologyCells {
        &self.cells
    }

    /// Converts outputs to the P6 graph return expression.
    pub fn output_expr(&self) -> Expr {
        match self.outputs.as_slice() {
            [] => Expr::Nil,
            [single] => single.clone(),
            many => Expr::List(many.to_vec()),
        }
    }

    fn enqueue(&mut self, item: WorkItem) {
        self.events.push(TopologyEvent::port(
            TopologyEventKind::Enqueued,
            item.node_index,
            item.port.clone(),
            item.expr.clone(),
        ));
        self.queue.push_back(item);
    }

    fn push_output(&mut self, node_index: usize, expr: Expr) -> Result<()> {
        self.budget.record_output()?;
        self.events.push(TopologyEvent::node_expr(
            TopologyEventKind::OutputEmitted,
            node_index,
            expr.clone(),
        ));
        self.outputs.push(expr);
        Ok(())
    }

    fn route_packet(&mut self, cx: &mut Cx, packet: TopologyPacket) -> Result<()> {
        let edge_indices = self.plan.outgoing_edges[packet.node_index].clone();
        for edge_index in edge_indices {
            let compiled = &self.plan.edges[edge_index];
            if compiled.from.port != packet.port {
                continue;
            }
            let edge = &self.graph.edges[compiled.source_index];
            if !edge_allows(cx, edge, &packet.expr)? {
                continue;
            }
            self.budget.record_edge_visit(edge_index, edge.max_visits)?;
            let routed = route_edge_expr(cx, edge, packet.expr.clone())?;
            self.events.push(TopologyEvent::edge(
                packet.node_index,
                packet.port.clone(),
                edge_index,
                routed.clone(),
            ));
            self.enqueue(WorkItem {
                node_index: compiled.to_node,
                port: compiled.to.port.clone(),
                expr: routed,
            });
        }
        Ok(())
    }
}

/// Runs a compiled graph with one input expression.
pub fn run_graph(cx: &mut Cx, graph: &Graph, plan: &CompiledGraph, input: Expr) -> Result<Expr> {
    cx.require(&topology_run_capability())?;
    for capability in &graph.capabilities {
        cx.require(&CapabilityName::new(capability.to_string()))?;
    }
    let mut run = TopologyRun::new(graph, plan, input)?;
    run.run(cx)?;
    Ok(run.output_expr())
}

fn edge_allows(cx: &mut Cx, edge: &Edge, input: &Expr) -> Result<bool> {
    match &edge.when {
        Some(predicate) => predicate_accepts(cx, predicate, input),
        None => Ok(true),
    }
}

fn route_edge_expr(cx: &mut Cx, edge: &crate::Edge, input: Expr) -> Result<Expr> {
    let transformed = match &edge.transform {
        Some(transform) => {
            let target = resolve_target(cx, transform)?;
            call_target_expr(cx, target, input)?
        }
        None => input,
    };

    if let Some(name) = &edge.as_name {
        Ok(Expr::Map(vec![(Expr::Symbol(name.clone()), transformed)]))
    } else {
        Ok(transformed)
    }
}