relate_executor/exec/read.rs
1//! The read-path statement entries (ADR-0094's pinned admission, ADR-0682's
2//! batch consumer): [`execute_read_at`] runs a read-only plan at the
3//! caller-pinned timestamp; [`execute_read_streaming_at`] is the same run
4//! with the statement's batch consumer attached.
5
6use relate_core::{Error, Result, Value};
7use relate_ir::Clause;
8
9use crate::consumer::{BatchFlow, StreamSink, BATCH_ROWS};
10use crate::graph::QueryStats;
11use crate::metrics::PlanMetricsSite;
12use crate::overlay::ExecGraph;
13use crate::row::Row;
14
15use super::dispatch::{execute_part_read_seeded, execute_part_read_streamed, streamable_part};
16use super::{begin_statement_entry, finish_statement, walk_statement, QueryResult, ReadAdmission};
17
18/// Execute a read-only plan at the caller-pinned timestamp in `admission`
19/// without repinning. The caller must keep its `Graph::pin_now()` guard alive
20/// through this call so version GC cannot discard rows visible at
21/// `snapshot_ts`, and must capture `schema` alongside that pin while
22/// serializing with graph publication.
23///
24/// There is deliberately no graph-only wrapper that acquires both itself: the
25/// publication read guard lives on the embedded database's `Shared` state, not
26/// on a bare `Graph`, so such a wrapper could not capture the pin and schema
27/// atomically. Admission must happen under that guard at the caller.
28pub fn execute_read_at(admission: &ReadAdmission<'_>) -> Result<QueryResult> {
29 execute_read_inner(admission, None)
30}
31
32/// [`execute_read_at`] with the statement's batch consumer attached
33/// (ADR-0682): a streaming statement's terminal `RETURN` hands each bounded
34/// batch to the sink as it is produced (see [`streamable_part`]); every
35/// other read shape runs materialized as ever and its result replays
36/// through the same sink — columns once, then bounded batches — before the
37/// call returns. Either way the returned [`QueryResult`] carries the
38/// statement's columns, stats and effect but no rows: the consumer has
39/// them. A consumer answering [`BatchFlow::Stop`](crate::BatchFlow) ends
40/// the walk and cancels the statement (`Error::Cancelled`).
41///
42/// A `PROFILE` statement (a plan-metrics sink on the request) never
43/// engages the consumer: its rows land in the result as ever, so the
44/// profiled run's answer is unchanged.
45pub fn execute_read_streaming_at(
46 admission: &ReadAdmission<'_>,
47 sink: &mut StreamSink<'_>,
48) -> Result<QueryResult> {
49 execute_read_inner(admission, Some(sink))
50}
51
52fn execute_read_inner(
53 admission: &ReadAdmission<'_>,
54 sink: Option<&mut StreamSink<'_>>,
55) -> Result<QueryResult> {
56 let view = ExecGraph::read_at(admission.graph, admission.snapshot_ts)
57 .with_schema(admission.schema)
58 .with_cancel(admission.cancel)
59 .with_ontology_document(admission.ontology_document);
60 // A read view carries no scratch, so the resets are vacuous and this
61 // prelude is the declared-name seeding — the same one every write entry
62 // takes, never a second spelling of it. The write-attempt fact comes from
63 // the same canonical plan walk as every write entry, never a hardcoded "a
64 // read cannot write": a mutation operator reaching this route is still an
65 // attempt (the read-only scratch refuses to apply it), and a read view
66 // applies nothing, so its applied count is the zero the admission starts
67 // with. ADR-0395: the freshly constructed view carries a zeroed counter,
68 // so the read admission's statement gets its own budget. The cancellation
69 // check is the prelude's, in every entry's order — a cancelled statement
70 // bails before any row flows, and the view it reset is dropped. The
71 // admission's request carries no batch-commit sink (a read commits no
72 // batches) and the read view carries no transaction clock, so the prelude
73 // reads both absences off the request and the graph it already takes.
74 let entry = begin_statement_entry(&view, &admission.request)?;
75 let plan = admission.request.plan;
76 let params = admission.request.params;
77 // One terminal decision, before the walk: a PROFILE statement keeps the
78 // materialized terminal end to end — its result rows feed the epilogue's
79 // plan enrichment — so a consumer stays disengaged and the caller replays
80 // the rows itself. Every other attached consumer streams.
81 let mut stream = sink.filter(|_| admission.request.plan_metrics.is_none());
82 let run_part =
83 |part_clauses: &[Clause], part_seeds: Vec<Row>, site: Option<PlanMetricsSite<'_>>| {
84 execute_part_read_seeded(&view, part_clauses, params, part_seeds, entry.ctx, site)
85 };
86 let mut result = match stream.as_deref_mut() {
87 Some(sink) => match streamable_part(plan)? {
88 Some(part) => {
89 execute_part_read_streamed(&view, part, params, vec![entry.root], entry.ctx, sink)?
90 }
91 None => walk_statement(
92 &view,
93 plan,
94 vec![entry.root],
95 admission.request.plan_metrics,
96 run_part,
97 )?,
98 },
99 None => walk_statement(
100 &view,
101 plan,
102 vec![entry.root],
103 admission.request.plan_metrics,
104 run_part,
105 )?,
106 };
107 result.stats = QueryStats::default();
108 let mut result = finish_statement(result, &view, entry.attempted)?;
109 if let Some(sink) = stream {
110 // A shape that did not stream (or a streamed part whose RETURN input
111 // could not take the per-batch form) replays its rows.
112 if !sink.engaged() {
113 replay_result(sink, &mut result)?;
114 }
115 }
116 Ok(result)
117}
118
119/// The materialized terminal's consumer delivery (ADR-0682): a statement
120/// whose shape does not stream (a `UNION` fold, a breaker, a catalog
121/// command) still answers its consumer — the columns once, then the result
122/// rows in bounded batches — and the result keeps no second copy. A
123/// consumer answering `Stop` cancels the finished statement, the same
124/// answer the streaming terminal gives.
125fn replay_result(sink: &mut StreamSink<'_>, result: &mut QueryResult) -> Result<()> {
126 sink.columns(&result.columns)?;
127 let rows = std::mem::take(&mut result.rows);
128 let mut rows = rows.into_iter();
129 loop {
130 let batch: Vec<Vec<Value>> = rows.by_ref().take(BATCH_ROWS).collect();
131 if batch.is_empty() {
132 break;
133 }
134 if matches!(sink.batch(batch)?, BatchFlow::Stop) {
135 return Err(Error::cancelled());
136 }
137 }
138 Ok(())
139}