Skip to main content

sva_engine/render/
stream.rs

1// Concern: opens a target as a stream over a store, editing it and its terms live | Non-concern: pulling its blocks, what an edit carries on | IO: (Graph, target) -> Stream; (Change) -> Changed
2
3use std::cell::RefCell;
4use std::collections::{BTreeMap, BTreeSet};
5use std::sync::Arc;
6
7use sva_ast::{Expr, Graph};
8use sva_formula::{Hash, NodeId};
9use sva_samples::{Buffer, Extent};
10
11use super::drive::{Block, Driver};
12use super::frontier::{Frontier, Known};
13use super::table::support::Supports;
14use super::table::{Table, edit};
15use super::terms::{Handle, NOTES, Terms, placed};
16use super::{Ends, Render, RenderConfig, range_of, through};
17use crate::cache::{Cache, CacheStats, Lookup, Outcome, Recording, Stored, Through};
18use crate::error::{Diagnostic, EngineError, Located};
19use crate::flops::Work;
20use crate::instantiate;
21use crate::recent::Recent;
22use crate::schedule;
23use crate::typing;
24
25pub const STREAMED: &str = "streamed";
26
27/// The lookups, and the names started silent, a stream keeps of all it made.
28pub const LATEST: usize = 256;
29
30#[derive(Clone, Debug, PartialEq)]
31pub struct StreamConfig {
32    pub block: usize,
33    pub render: RenderConfig,
34}
35
36/// A target rendered block by block off one table. The target may read `@notes`, the sum of
37/// the terms added under handles. A node the store answers plays from its samples. A hit is
38/// looked up once; a node reading the stream's own note sum never, as no store holds one.
39pub struct Stream {
40    config: StreamConfig,
41    shell: Render,
42    driver: Driver,
43    graph: Graph,
44    expr: Expr,
45    terms: Terms,
46    ends: BTreeMap<Handle, i64>,
47    met: Met,
48    generation: u64,
49    live: bool,
50    dropped: Recent<String>,
51    late: usize,
52}
53
54#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
55pub struct Counts {
56    pub dropped: usize,
57    /// Edits that landed past the sample they were issued at.
58    pub late: usize,
59    pub terms: usize,
60}
61
62/// Each hit met: a header holds until its store moves the samples; any holder may fill a miss.
63#[derive(Default)]
64struct Met {
65    epoch: u64,
66    known: Known,
67}
68
69impl Met {
70    fn over(&mut self, store: &impl Through) -> &Known {
71        if store.epoch() != self.epoch {
72            self.known.clear();
73            self.epoch = store.epoch();
74        }
75        &self.known
76    }
77
78    /// Kept where the store has not changed since `epoch`.
79    fn noted(&mut self, key: Hash, found: &Option<Arc<Stored>>, epoch: u64, store: &impl Through) {
80        self.over(store);
81        if epoch == self.epoch {
82            self.known.insert(key, found.clone());
83        }
84    }
85
86    fn hits(&mut self, store: &impl Through) -> Vec<(Hash, Option<Arc<Stored>>)> {
87        let hits = self.over(store).iter().filter(|(_, found)| found.is_some());
88        hits.map(|(key, found)| (*key, found.clone())).collect()
89    }
90}
91
92struct Shelled {
93    shell: Render,
94    range: Extent,
95    table: Table,
96    hits: Vec<Lookup>,
97}
98
99impl Stream {
100    pub async fn open(
101        graph: &Graph,
102        target: &Expr,
103        config: StreamConfig,
104        cache: Option<&Cache>,
105        store: &impl Through,
106    ) -> Result<Stream, EngineError> {
107        let terms = Terms::default();
108        let (mut known, epoch) = (Known::new(), store.epoch());
109        let render = &blocked(&config)?.render;
110        let walk = async |found: &mut Frontier<'_>| found.walked(&mut known, store).await;
111        let mut found = shelled(graph, target, &terms, render, walk).await?;
112        let mut met = Met::default();
113        for (key, hit) in known.into_iter().filter(|(_, found)| found.is_some()) {
114            met.noted(key, &hit, epoch, store);
115        }
116        let next = ahead(found.range.start, render.rate);
117        through::load(&mut found.table, store, next, &BTreeSet::new()).await;
118        let mut recording = Recording::over(cache, config.render.cache_policy).latest(LATEST);
119        recording.found(found.hits);
120        let driver = Driver::new(
121            found.table,
122            found.range,
123            config.block,
124            &config.render,
125            recording,
126        );
127        Ok(Stream {
128            graph: graph.clone(),
129            expr: target.clone(),
130            terms,
131            ends: BTreeMap::new(),
132            met,
133            generation: 0,
134            live: false,
135            dropped: Recent::keeping(LATEST),
136            late: 0,
137            driver,
138            config,
139            shell: found.shell,
140        })
141    }
142
143    pub fn exprs(&self) -> impl Iterator<Item = &Expr> {
144        std::iter::once(&self.expr).chain(self.terms.exprs())
145    }
146
147    fn prospect(&self, change: Change) -> Result<Prospect, Changed> {
148        let mut render = self.config.render.clone();
149        render.range.start = Some(self.driver.start);
150        let mut landing = None;
151        let (graph, target, terms, answer) = match change {
152            Change::Target(graph, target) => (graph, target, self.terms.clone(), Changed::Edited),
153            Change::Add(graph, term, at) => {
154                let term = match at {
155                    Placed::Written => term,
156                    Placed::Landing => placed(&term, *landing.insert(self.driver.at)),
157                };
158                let (terms, handle) = self.terms.added(term);
159                (graph, self.expr.clone(), terms, Changed::Added(handle))
160            }
161            Change::Replace(handle, graph, term, at) => {
162                let terms = self.terms.replaced(handle, |landed| match at {
163                    Placed::Written => term,
164                    Placed::Landing => placed(&term, landed),
165                });
166                let terms = terms.ok_or(Changed::Held(false))?;
167                (graph, self.expr.clone(), terms, Changed::Held(true))
168            }
169            Change::Remove(handle) => {
170                let at = self.driver.at as f64 / f64::from(self.shell.rate());
171                let terms = self.terms.removed(handle, at);
172                let terms = terms.ok_or(Changed::Held(false))?;
173                (
174                    self.graph.clone(),
175                    self.expr.clone(),
176                    terms,
177                    Changed::Held(true),
178                )
179            }
180        };
181        Ok(Prospect {
182            graph,
183            target,
184            terms,
185            answer,
186            render,
187            generation: self.generation,
188            landing,
189        })
190    }
191
192    /// The stored samples `table` asks over the next second that it brings in and nothing
193    /// holds; `None` where the stream changed since `generation` or left `landing`.
194    fn wanting(
195        &self,
196        (generation, landing): (u64, Option<i64>),
197        table: &Table,
198        unread: &BTreeSet<Hash>,
199    ) -> Option<Vec<(Arc<Stored>, Extent)>> {
200        if generation != self.generation || landing.is_some_and(|at| at != self.driver.at) {
201            return None;
202        }
203        let sounding = self.driver.table.stored_keys();
204        let wants = table.wants(ahead(self.driver.at, self.config.render.rate));
205        let brought = wants.into_iter();
206        let brought =
207            brought.filter(|(s, _)| !sounding.contains(&s.key) && !unread.contains(&s.key));
208        Some(brought.collect())
209    }
210
211    /// Values of the same identity carry on; a changed stateful one takes its predecessor's
212    /// state; the rest start now.
213    fn apply(
214        &mut self,
215        (prospect, issued): (Prospect, i64),
216        shelled: Shelled,
217        fetched: &[(Hash, Vec<Buffer>)],
218    ) {
219        let Shelled {
220            shell,
221            range,
222            mut table,
223            hits,
224        } = shelled;
225        let old = std::mem::replace(&mut self.driver.table, Table::empty());
226        let dropped = edit::carried(&mut table, old, self.driver.at, self.live);
227        for (key, samples) in fetched {
228            table.took(*key, samples);
229        }
230        for at in dropped {
231            self.dropped.push(table.values[at].name.clone());
232        }
233        self.late += usize::from(self.driver.at > issued);
234        self.driver.replace(table, range.end);
235        self.driver.recording.found(hits);
236        self.shell = shell;
237        self.graph = prospect.graph;
238        self.expr = prospect.target;
239        self.terms = prospect.terms;
240        if let Changed::Added(handle) = prospect.answer {
241            self.terms.land(handle, self.driver.at);
242        }
243        let supports = Supports::new(&self.shell.tys, &self.shell.config.profile);
244        let tys = &self.shell.tys;
245        let end = |handle: Handle| Some((handle, supports.of(tys.id(&handle.node())?).end));
246        self.ends = self.terms.handles().filter_map(end).collect();
247        self.generation += 1;
248        self.prune();
249    }
250
251    /// Loads the stored samples the next second reads; a block reading one not loaded has it
252    /// computed, or, live, started silent where not ready.
253    pub async fn fetch(&mut self, store: &impl Through) {
254        let next = ahead(self.driver.at, self.config.render.rate);
255        through::load(&mut self.driver.table, store, next, &BTreeSet::new()).await;
256    }
257
258    /// What `fetch` reads, for a caller reading it as the stream plays.
259    pub fn wanted(&self) -> Vec<(Arc<Stored>, Extent)> {
260        let next = ahead(self.driver.at, self.config.render.rate);
261        self.driver.table.wants(next)
262    }
263
264    pub fn took(&mut self, key: Hash, samples: &[Buffer]) {
265        self.driver.table.took(key, samples);
266    }
267
268    /// The next block, cut where the stream ends; `None` from there on.
269    pub fn next_block(&mut self) -> Result<Option<Block>, EngineError> {
270        let block = self.driver.next_block()?;
271        self.prune();
272        Ok(block)
273    }
274
275    /// An edited node with no state there starts silent, never computing its past.
276    pub fn go_live(&mut self) {
277        self.live = true;
278    }
279
280    /// The latest nodes a live edit started silent, of `counts().dropped`.
281    pub fn dropped(&self) -> Vec<&str> {
282        self.dropped.iter().map(String::as_str).collect()
283    }
284
285    pub fn counts(&self) -> Counts {
286        Counts {
287            dropped: self.dropped.made(),
288            late: self.late,
289            terms: self.terms.count(),
290        }
291    }
292
293    /// Retires every term whose support, pruned as a render prunes it, lies wholly before the
294    /// first sample of `notes` the root's window from now on asks, as a render's demand finds it.
295    fn prune(&mut self) {
296        let (table, tys) = (&self.driver.table, &self.shell.tys);
297        let (now, last) = (self.driver.at, self.driver.last());
298        let asked = match tys.id(NOTES).and_then(|notes| table.of(notes)) {
299            Some(notes) if now < last => {
300                let needs = table.demand(Extent::new(now, last));
301                needs[notes].hold.iter().next().map(|asked| asked.start)
302            }
303            Some(_) => None,
304            None => Some(i64::MIN),
305        };
306        let ends = &self.ends;
307        let gone = |handle: Handle| {
308            let end = ends.get(&handle);
309            end.is_some_and(|end| asked.is_none_or(|from| *end <= from))
310        };
311        let named = |handle: Handle| {
312            let id = tys.id(&handle.node())?;
313            crate::refs::identity(tys, id).ok()
314        };
315        if self.terms.prune(&gone, &named) {
316            self.generation += 1;
317        }
318    }
319
320    /// Every segment of its own clock the stream computed of `node`'s value, in order.
321    pub fn evaluated(&self, node: &str) -> Vec<sva_samples::Extent> {
322        let table = &self.driver.table;
323        self.shell
324            .tys
325            .id(node)
326            .and_then(|id| table.of(id))
327            .map_or(Vec::new(), |at| table.values[at].evaluated.clone())
328    }
329
330    pub fn pruned(&self) -> sva_samples::Pruned {
331        self.driver.table.pruned()
332    }
333
334    pub fn landed(&self, handle: Handle) -> Option<i64> {
335        self.terms.landed(handle)
336    }
337
338    pub fn position(&self) -> i64 {
339        self.driver.at
340    }
341
342    pub fn work(&self) -> Work {
343        self.driver.work
344    }
345
346    pub fn stats(&self) -> CacheStats {
347        self.driver.recording.stats()
348    }
349
350    /// The bytes its values hold, samples and state.
351    pub fn held_bytes(&self) -> usize {
352        self.driver.table.bytes()
353    }
354
355    pub fn end(&self) -> Option<i64> {
356        self.driver.end()
357    }
358
359    pub fn width(&self) -> usize {
360        self.driver.table.values[self.driver.table.root].width
361    }
362
363    pub fn config(&self) -> &StreamConfig {
364        &self.config
365    }
366}
367
368/// An edit, each with the graph that reaches it and all the stream plays.
369pub enum Change {
370    Target(Graph, Expr),
371    Add(Graph, Expr, Placed),
372    Replace(Handle, Graph, Expr, Placed),
373    /// A sounding term is cut where the stream stands as the edit is built; what played stays.
374    Remove(Handle),
375}
376
377/// Where a term's sample 0 sits: the stream's own, or the sample its add lands at.
378#[derive(Clone, Copy, Debug, PartialEq, Eq)]
379pub enum Placed {
380    Written,
381    Landing,
382}
383
384/// A replace or remove answers whether the stream still held its handle.
385#[derive(Clone, Copy, Debug, PartialEq, Eq)]
386pub enum Changed {
387    Edited,
388    Added(Handle),
389    Held(bool),
390}
391
392struct Prospect {
393    graph: Graph,
394    target: Expr,
395    terms: Terms,
396    answer: Changed,
397    render: RenderConfig,
398    generation: u64,
399    landing: Option<i64>,
400}
401
402/// `build`'s change, holding the stream only to apply it, between two blocks, once the store
403/// answered what it brings in: an exact stream pulled only once its edit is done plays it where
404/// it was issued. `build` runs again whenever the stream changed under it.
405pub async fn change<E: From<EngineError>>(
406    stream: &RefCell<Stream>,
407    mut build: impl FnMut(&Stream) -> Result<Change, E>,
408    store: &impl Through,
409) -> Result<Changed, E> {
410    let mut local = Met::default();
411    let mut fetched: Vec<(Hash, Vec<Buffer>)> = Vec::new();
412    let (mut unread, mut asked) = (BTreeSet::new(), Vec::<(Hash, Extent)>::new());
413    let issued = stream.borrow().driver.at;
414    loop {
415        let change = build(&stream.borrow())?;
416        let prospect = match stream.borrow().prospect(change) {
417            Ok(prospect) => prospect,
418            Err(answer) => return Ok(answer),
419        };
420        for (key, hit) in stream.borrow_mut().met.hits(store) {
421            local.noted(key, &hit, store.epoch(), store);
422        }
423        let walk = async |found: &mut Frontier<'_>| {
424            while let Some(key) = found.walk(local.over(store)) {
425                let epoch = store.epoch();
426                let found = store.lookup(key).await.map(Arc::new);
427                if found.is_some() {
428                    stream.borrow_mut().met.noted(key, &found, epoch, store);
429                }
430                local.noted(key, &found, epoch, store);
431            }
432        };
433        let (graph, target) = (&prospect.graph, &prospect.target);
434        let config = &prospect.render;
435        let mut shelled = shelled(graph, target, &prospect.terms, config, walk).await?;
436        let standing = (prospect.generation, prospect.landing);
437        loop {
438            for (key, samples) in &fetched {
439                shelled.table.took(*key, samples);
440            }
441            let wants = stream.borrow().wanting(standing, &shelled.table, &unread);
442            let Some(wants) = wants else {
443                break;
444            };
445            if wants.is_empty() {
446                let answer = prospect.answer;
447                stream
448                    .borrow_mut()
449                    .apply((prospect, issued), shelled, &fetched);
450                return Ok(answer);
451            }
452            for (stored, over) in wants {
453                let again = asked
454                    .iter()
455                    .any(|(key, e)| *key == stored.key && !e.intersect(over).is_empty());
456                asked.push((stored.key, over));
457                let read = match again {
458                    false => store.read(&stored, over).await,
459                    true => None,
460                };
461                match read {
462                    Some(samples) => fetched.push((stored.key, samples)),
463                    None => {
464                        unread.insert(stored.key);
465                    }
466                }
467            }
468        }
469    }
470}
471
472fn ahead(at: i64, rate: u32) -> Extent {
473    Extent::new(at, at.saturating_add(i64::from(rate)))
474}
475
476fn blocked(config: &StreamConfig) -> Result<&StreamConfig, EngineError> {
477    match config.block {
478        0 => Err(refusal("a block of no samples".to_string())),
479        _ => Ok(config),
480    }
481}
482
483/// The graph with `streamed` defined as `target` and `notes` as `terms`. A composition's own
484/// `notes` stands while there is no term.
485fn wrapped(graph: &Graph, target: &Expr, terms: &Terms) -> Result<Graph, EngineError> {
486    let mut wrapped = graph.clone();
487    if !terms.is_empty() && graph.defines(NOTES) {
488        return Err(EngineError::refused(Diagnostic {
489            code: "engine.no_stream".to_string(),
490            message: format!(
491                "a term is added to `@{NOTES}`, and this composition defines its own `{NOTES}`"
492            ),
493            location: Located::at(NOTES, None),
494            help: format!("rename the composition's `{NOTES}`, or play it without adding terms"),
495        }));
496    }
497    let own = terms.is_empty() && graph.defines(NOTES);
498    let sum = (!own).then(|| (NOTES.to_string(), terms.sum()));
499    let defined = std::iter::once((STREAMED.to_string(), target.clone()));
500    for (name, body) in defined.chain(sum).chain(terms.nodes()) {
501        if !wrapped.define(&name, body) {
502            return Err(refusal(format!(
503                "this composition already has a node named `{name}`"
504            )));
505        }
506    }
507    Ok(wrapped)
508}
509
510/// The wrapped graph typed whole, each node the store answers standing on its samples.
511async fn shelled(
512    graph: &Graph,
513    target: &Expr,
514    terms: &Terms,
515    config: &RenderConfig,
516    walk: impl AsyncFnOnce(&mut Frontier<'_>),
517) -> Result<Shelled, EngineError> {
518    let wrapped = wrapped(graph, target, terms)?;
519    let instances = instantiate::instantiate(&wrapped, STREAMED, config.rate)?;
520    let root = instances.instance_of(STREAMED)?;
521    let order = schedule::schedule_from(&instances, std::slice::from_ref(&root))?;
522    let keys = through::keys(&wrapped, &instances, &order, config);
523    let mut found = Frontier::from((&instances, &order), &keys, &root, (config, true));
524    if !terms.is_empty() {
525        found.unstored(reading(&order, &instances.instance_of(NOTES)?));
526        found.unstored(terms.handles().map(Handle::node));
527    }
528    walk(&mut found).await;
529    let mut tys = typing::infer_over(&instances, &order.within(&found.visited), &BTreeMap::new())?;
530    let id = tys
531        .id(&root)
532        .ok_or_else(|| EngineError::UnknownNode(root.clone()))?;
533    terms.name(&mut tys);
534    let prefixes: BTreeMap<NodeId, Arc<Stored>> = std::mem::take(&mut found.stored)
535        .into_iter()
536        .map(|(path, stored)| (tys.id(&path).expect("a walked node is typed"), stored))
537        .collect();
538    let schedule = schedule::plan(&tys, id, &[]);
539    let shell = Render::shell(tys, id, config.clone(), schedule);
540    let range = range_of(&shell, Ends::Pulled)?;
541    let table = Table::prefixed(&shell.tys, shell.root, &shell.config.profile, &prefixes)?;
542    let hits = found.lookups.into_iter();
543    let hits = hits.filter(|l| l.outcome == Outcome::Hit).collect();
544    Ok(Shelled {
545        shell,
546        range,
547        table,
548        hits,
549    })
550}
551
552/// `path` and every node reading it, however far down.
553fn reading(order: &schedule::Order, path: &str) -> BTreeSet<String> {
554    let mut out = BTreeSet::from([path.to_string()]);
555    loop {
556        let more: Vec<String> = order
557            .groups
558            .iter()
559            .flatten()
560            .filter(|node| !out.contains(*node))
561            .filter(|node| order.deps(node).iter().any(|read| out.contains(read)))
562            .cloned()
563            .collect();
564        if more.is_empty() {
565            return out;
566        }
567        out.extend(more);
568    }
569}
570
571fn refusal(what: String) -> EngineError {
572    EngineError::refused(Diagnostic {
573        code: "engine.no_stream".to_string(),
574        message: format!("this target opens no stream: {what}"),
575        location: Located::at(STREAMED, None),
576        help: "stream an expression over the nodes the composition defines".to_string(),
577    })
578}