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    supports: BTreeMap<Handle, Extent>,
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            supports: 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 support = |handle: Handle| Some((handle, supports.of(tys.id(&handle.node())?)));
246        self.supports = self.terms.handles().filter_map(support).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    /// `n` samples from sample `at`, cut where the stream ends; `None` from there on. An `at`
269    /// behind the stream is refused; one past it skips there, computing through the span, or,
270    /// live, as `go_live` says.
271    pub fn read(&mut self, at: i64, n: usize) -> Result<Option<Block>, EngineError> {
272        let now = self.driver.at;
273        if at < now {
274            return Err(refused(
275                "engine.stream_behind",
276                format!("sample {at} is before sample {now}, where the stream stands"),
277                "read from the stream's position or later",
278            ));
279        }
280        if n == 0 {
281            return Err(refused(
282                "engine.empty_read",
283                format!("a read of no samples at sample {at}"),
284                "read one sample or more",
285            ));
286        }
287        match self.live {
288            true if at > now => {
289                for silenced in self.driver.skip(at)? {
290                    self.dropped
291                        .push(self.driver.table.values[silenced].name.clone());
292                }
293            }
294            _ => {
295                let block = self.config.block;
296                while self.driver.at < at {
297                    let step = block.min((at - self.driver.at) as usize);
298                    if !self.driver.pulled(step)? {
299                        return Ok(None);
300                    }
301                    self.prune();
302                }
303            }
304        }
305        let block = self.driver.read(n)?;
306        self.prune();
307        Ok(block)
308    }
309
310    /// An edited node with no state there, or one a read skips past, starts silent there,
311    /// never computing its past, and is named in `dropped`; a formula reads on exactly.
312    pub fn go_live(&mut self) {
313        self.live = true;
314    }
315
316    /// The latest nodes a live edit started silent, of `counts().dropped`.
317    pub fn dropped(&self) -> Vec<&str> {
318        self.dropped.iter().map(String::as_str).collect()
319    }
320
321    pub fn counts(&self) -> Counts {
322        Counts {
323            dropped: self.dropped.made(),
324            late: self.late,
325            terms: self.terms.count(),
326        }
327    }
328
329    /// Retires every term whose support, pruned as a render prunes it, lies wholly before the
330    /// first sample of `notes` the root's window from now on asks, as a render's demand finds it.
331    fn prune(&mut self) {
332        let (table, tys) = (&self.driver.table, &self.shell.tys);
333        let (now, last) = (self.driver.at, self.driver.last());
334        let asked = match tys.id(NOTES).and_then(|notes| table.of(notes)) {
335            Some(notes) if now < last => {
336                let needs = table.demand(Extent::new(now, last));
337                needs[notes].hold.iter().next().map(|asked| asked.start)
338            }
339            Some(_) => None,
340            None => Some(i64::MIN),
341        };
342        let supports = &self.supports;
343        let gone = |handle: Handle| {
344            let support = supports.get(&handle);
345            support.is_some_and(|s| asked.is_none_or(|from| s.end <= from))
346        };
347        let named = |handle: Handle| {
348            let id = tys.id(&handle.node())?;
349            Some((
350                crate::refs::identity(tys, id).ok()?,
351                *supports.get(&handle)?,
352            ))
353        };
354        if self.terms.prune(&gone, &named) {
355            self.generation += 1;
356        }
357    }
358
359    /// Every segment of its own clock the stream computed of `node`'s value, in order.
360    pub fn evaluated(&self, node: &str) -> Vec<sva_samples::Extent> {
361        let table = &self.driver.table;
362        self.shell
363            .tys
364            .id(node)
365            .and_then(|id| table.of(id))
366            .map_or(Vec::new(), |at| table.values[at].evaluated.clone())
367    }
368
369    pub fn pruned(&self) -> sva_samples::Pruned {
370        self.driver.table.pruned()
371    }
372
373    pub fn landed(&self, handle: Handle) -> Option<i64> {
374        self.terms.landed(handle)
375    }
376
377    pub fn position(&self) -> i64 {
378        self.driver.at
379    }
380
381    pub fn work(&self) -> Work {
382        self.driver.work
383    }
384
385    pub fn stats(&self) -> CacheStats {
386        self.driver.recording.stats()
387    }
388
389    /// The bytes its values hold, samples and state.
390    pub fn held_bytes(&self) -> usize {
391        self.driver.table.bytes()
392    }
393
394    pub fn end(&self) -> Option<i64> {
395        self.driver.end()
396    }
397
398    pub fn width(&self) -> usize {
399        self.driver.table.values[self.driver.table.root].width
400    }
401
402    pub fn config(&self) -> &StreamConfig {
403        &self.config
404    }
405}
406
407/// An edit, each with the graph that reaches it and all the stream plays.
408pub enum Change {
409    Target(Graph, Expr),
410    Add(Graph, Expr, Placed),
411    Replace(Handle, Graph, Expr, Placed),
412    /// A sounding term is cut where the stream stands as the edit is built; what played stays.
413    Remove(Handle),
414}
415
416/// Where a term's sample 0 sits: the stream's own, or the sample its add lands at.
417#[derive(Clone, Copy, Debug, PartialEq, Eq)]
418pub enum Placed {
419    Written,
420    Landing,
421}
422
423/// A replace or remove answers whether the stream still held its handle.
424#[derive(Clone, Copy, Debug, PartialEq, Eq)]
425pub enum Changed {
426    Edited,
427    Added(Handle),
428    Held(bool),
429}
430
431struct Prospect {
432    graph: Graph,
433    target: Expr,
434    terms: Terms,
435    answer: Changed,
436    render: RenderConfig,
437    generation: u64,
438    landing: Option<i64>,
439}
440
441/// `build`'s change, holding the stream only to apply it, between two blocks, once the store
442/// answered what it brings in: an exact stream pulled only once its edit is done plays it where
443/// it was issued. `build` runs again whenever the stream changed under it.
444pub async fn change<E: From<EngineError>>(
445    stream: &RefCell<Stream>,
446    mut build: impl FnMut(&Stream) -> Result<Change, E>,
447    store: &impl Through,
448) -> Result<Changed, E> {
449    let mut local = Met::default();
450    let mut fetched: Vec<(Hash, Vec<Buffer>)> = Vec::new();
451    let (mut unread, mut asked) = (BTreeSet::new(), Vec::<(Hash, Extent)>::new());
452    let issued = stream.borrow().driver.at;
453    loop {
454        let change = build(&stream.borrow())?;
455        let prospect = match stream.borrow().prospect(change) {
456            Ok(prospect) => prospect,
457            Err(answer) => return Ok(answer),
458        };
459        for (key, hit) in stream.borrow_mut().met.hits(store) {
460            local.noted(key, &hit, store.epoch(), store);
461        }
462        let walk = async |found: &mut Frontier<'_>| {
463            while let Some(key) = found.walk(local.over(store)) {
464                let epoch = store.epoch();
465                let found = store.lookup(key).await.map(Arc::new);
466                if found.is_some() {
467                    stream.borrow_mut().met.noted(key, &found, epoch, store);
468                }
469                local.noted(key, &found, epoch, store);
470            }
471        };
472        let (graph, target) = (&prospect.graph, &prospect.target);
473        let config = &prospect.render;
474        let mut shelled = shelled(graph, target, &prospect.terms, config, walk).await?;
475        let standing = (prospect.generation, prospect.landing);
476        loop {
477            for (key, samples) in &fetched {
478                shelled.table.took(*key, samples);
479            }
480            let wants = stream.borrow().wanting(standing, &shelled.table, &unread);
481            let Some(wants) = wants else {
482                break;
483            };
484            if wants.is_empty() {
485                let answer = prospect.answer;
486                stream
487                    .borrow_mut()
488                    .apply((prospect, issued), shelled, &fetched);
489                return Ok(answer);
490            }
491            for (stored, over) in wants {
492                let again = asked
493                    .iter()
494                    .any(|(key, e)| *key == stored.key && !e.intersect(over).is_empty());
495                asked.push((stored.key, over));
496                let read = match again {
497                    false => store.read(&stored, over).await,
498                    true => None,
499                };
500                match read {
501                    Some(samples) => fetched.push((stored.key, samples)),
502                    None => {
503                        unread.insert(stored.key);
504                    }
505                }
506            }
507        }
508    }
509}
510
511fn ahead(at: i64, rate: u32) -> Extent {
512    Extent::new(at, at.saturating_add(i64::from(rate)))
513}
514
515fn blocked(config: &StreamConfig) -> Result<&StreamConfig, EngineError> {
516    match config.block {
517        0 => Err(refusal("a block of no samples".to_string())),
518        _ => Ok(config),
519    }
520}
521
522/// The graph with `streamed` defined as `target` and `notes` as `terms`. A composition's own
523/// `notes` stands while there is no term.
524fn wrapped(graph: &Graph, target: &Expr, terms: &Terms) -> Result<Graph, EngineError> {
525    let mut wrapped = graph.clone();
526    if !terms.is_empty() && graph.defines(NOTES) {
527        return Err(EngineError::refused(Diagnostic {
528            code: "engine.no_stream".to_string(),
529            message: format!(
530                "a term is added to `@{NOTES}`, and this composition defines its own `{NOTES}`"
531            ),
532            location: Located::at(NOTES, None),
533            help: format!("rename the composition's `{NOTES}`, or play it without adding terms"),
534        }));
535    }
536    let own = terms.is_empty() && graph.defines(NOTES);
537    let sum = (!own).then(|| (NOTES.to_string(), terms.sum()));
538    let defined = std::iter::once((STREAMED.to_string(), target.clone()));
539    for (name, body) in defined.chain(sum).chain(terms.nodes()) {
540        if !wrapped.define(&name, body) {
541            return Err(refusal(format!(
542                "this composition already has a node named `{name}`"
543            )));
544        }
545    }
546    Ok(wrapped)
547}
548
549/// The wrapped graph typed whole, each node the store answers standing on its samples.
550async fn shelled(
551    graph: &Graph,
552    target: &Expr,
553    terms: &Terms,
554    config: &RenderConfig,
555    walk: impl AsyncFnOnce(&mut Frontier<'_>),
556) -> Result<Shelled, EngineError> {
557    let wrapped = wrapped(graph, target, terms)?;
558    let instances = instantiate::instantiate(&wrapped, STREAMED, config.rate)?;
559    let root = instances.instance_of(STREAMED)?;
560    let order = schedule::schedule_from(&instances, std::slice::from_ref(&root))?;
561    let keys = through::keys(&wrapped, &instances, &order, config);
562    let mut found = Frontier::from((&instances, &order), &keys, &root, (config, true));
563    if !terms.is_empty() {
564        found.unstored(reading(&order, &instances.instance_of(NOTES)?));
565        found.unstored(terms.handles().map(Handle::node));
566    }
567    walk(&mut found).await;
568    let mut tys = typing::infer_over(&instances, &order.within(&found.visited), &BTreeMap::new())?;
569    let id = tys
570        .id(&root)
571        .ok_or_else(|| EngineError::UnknownNode(root.clone()))?;
572    terms.name(&mut tys);
573    let prefixes: BTreeMap<NodeId, Arc<Stored>> = std::mem::take(&mut found.stored)
574        .into_iter()
575        .map(|(path, stored)| (tys.id(&path).expect("a walked node is typed"), stored))
576        .collect();
577    let schedule = schedule::plan(&tys, id, &[]);
578    let shell = Render::shell(tys, id, config.clone(), schedule);
579    let range = range_of(&shell, Ends::Pulled)?;
580    let table = Table::prefixed(&shell.tys, shell.root, &shell.config.profile, &prefixes)?;
581    let hits = found.lookups.into_iter();
582    let hits = hits.filter(|l| l.outcome == Outcome::Hit).collect();
583    Ok(Shelled {
584        shell,
585        range,
586        table,
587        hits,
588    })
589}
590
591/// `path` and every node reading it, however far down.
592fn reading(order: &schedule::Order, path: &str) -> BTreeSet<String> {
593    let mut out = BTreeSet::from([path.to_string()]);
594    loop {
595        let more: Vec<String> = order
596            .groups
597            .iter()
598            .flatten()
599            .filter(|node| !out.contains(*node))
600            .filter(|node| order.deps(node).iter().any(|read| out.contains(read)))
601            .cloned()
602            .collect();
603        if more.is_empty() {
604            return out;
605        }
606        out.extend(more);
607    }
608}
609
610fn refusal(what: String) -> EngineError {
611    refused(
612        "engine.no_stream",
613        format!("this target opens no stream: {what}"),
614        "stream an expression over the nodes the composition defines",
615    )
616}
617
618fn refused(code: &str, message: String, help: &str) -> EngineError {
619    EngineError::refused(Diagnostic {
620        code: code.to_string(),
621        message,
622        location: Located::at(STREAMED, None),
623        help: help.to_string(),
624    })
625}