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