Skip to main content

sqlload_python_host/crossing/
models.rs

1use sqlload::load_naming::models::Naming;
2use sqlload::row_batches::models::{Flatten, ProjectionRules};
3use std::sync::atomic::{AtomicU64, Ordering};
4use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, SyncSender};
5use std::sync::{Arc, Condvar, Mutex};
6use std::time::Duration;
7
8use arrow_array::RecordBatch;
9use arrow_array::ffi_stream::RecordBatchStreamReader;
10use arrow_schema::Schema;
11use pyo3::pybacked::PyBackedBytes;
12use sqlload::row_batches::main::merge_schema::merge_schema;
13use sqlload::row_batches::models::{JsonRead, RowColumns};
14
15use crate::crossing::errors::CrossError;
16
17/// How gathered dicts cross into Rust.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum DictCrossing {
20    /// Rust reads the dicts directly, holding the GIL.
21    Walk,
22    /// `orjson` writes the batch as JSON bytes, which Rust parses without the GIL; batches orjson cannot write are walked.
23    Serialise,
24}
25
26/// How a table generator is read.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub struct CrossingOptions {
29    /// Rows gathered from dict yields before they cross; also the most rows per batch parsed from JSON bytes.
30    pub batch_rows: usize,
31    /// Crossed batches waiting to be parsed, and parsed batches waiting to be consumed, before the generator pauses.
32    pub max_queued: usize,
33    pub dict_crossing: DictCrossing,
34    /// Threads parsing crossed batches into Arrow at once.
35    pub parse_threads: usize,
36    /// A thread made to panic, to test that a panic fails the read (the crossing's test hook).
37    pub panic_at: Option<PanicSite>,
38    /// Bytes of crossed data waiting to be parsed before the generator pauses (one piece larger than this still crosses alone).
39    pub max_queued_bytes: usize,
40}
41
42/// What the parser threads need from the table besides its data: the top-level objects to expand one level, and the connections its `sl.http` jobs may use.
43#[derive(Debug, Clone, Default)]
44pub struct ReadContext {
45    /// The table's name in its source, for a page `transform`'s `ctx.table`.
46    pub table: String,
47    pub flatten: Flatten,
48    pub connections: serde_json::Map<String, serde_json::Value>,
49    /// The table's cursor column, which projected JSON rows must keep.
50    pub cursor_column: Option<String>,
51    /// The table's masked columns, which `keep_record` must not carry.
52    pub masked: Vec<String>,
53    /// Columns whose Arrow lists of scalars cross as lists (the table pins them as arrays); other lists cross as json text.
54    pub arrays: Vec<String>,
55    /// How the table's columns load and the destination's name limit: `cursor_column` and `arrays` are loaded names, which yielded fields match as they load.
56    pub naming: (Naming, Option<usize>),
57    /// The table's `timezone`, which an `sl.field` parse without its own `tz` reads times without an offset in; `None` is UTC.
58    pub zone: Option<chrono_tz::Tz>,
59    /// The most the pages an `sl.http` job requests ahead may hold: a quarter of the table's share of the run's memory budget; `None` without a budget.
60    pub source_part: Option<u64>,
61}
62
63impl ReadContext {
64    /// What the table asks of projected rows.
65    pub fn rules(&self) -> ProjectionRules<'_> {
66        ProjectionRules {
67            cursor_column: self.cursor_column.as_deref(),
68            flatten: Some(&self.flatten),
69            masked: &self.masked,
70            naming: self.naming,
71        }
72    }
73}
74
75/// A crossing thread that can be made to panic for tests.
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub enum PanicSite {
78    /// The thread iterating the generator, after its first item.
79    Producer,
80    /// A thread parsing crossed batches.
81    Parser,
82}
83
84/// One message of a piece's parsed batches, or of the whole read; a channel closed before `Done` means a thread stopped unexpectedly.
85#[derive(Debug)]
86pub(crate) enum Parsed {
87    Batch(RecordBatch),
88    /// `ctx.state` (as JSON) when the piece whose batches came just before crossed.
89    State(String),
90    Failed(CrossError),
91    Done,
92}
93
94/// A piece waiting for a parser thread, and where its batches go.
95#[derive(Debug)]
96pub(crate) struct ParseJob {
97    pub(crate) crossed: Crossed,
98    pub(crate) sender: SyncSender<Parsed>,
99}
100
101/// Hands crossed pieces to the parser threads, registering each in yield order with the thread that passes batches on.
102#[derive(Debug, Clone)]
103pub(crate) struct Dispatch {
104    /// Each piece's batch channel in yield order, with `ctx.state` when it crossed; `None` marks the end of the generator.
105    pub(crate) order: SyncSender<Option<(Receiver<Parsed>, Option<String>)>>,
106    pub(crate) jobs: Sender<ParseJob>,
107    /// Holds the byte budget the generator waits on.
108    pub(crate) stats: Arc<CrossingStats>,
109    /// The objects expanded into `<object>__<key>` columns.
110    pub(crate) flatten: Arc<Flatten>,
111}
112
113/// One piece of yielded data, crossed into Rust and waiting to be parsed.
114#[derive(Debug)]
115pub(crate) enum Crossed {
116    Columns(RowColumns),
117    Json {
118        bytes: PyBackedBytes,
119        read: JsonRead,
120    },
121    ArrowStream(RecordBatchStreamReader),
122    ArrowBatch(RecordBatch),
123    /// An `sl.http` job's definition, run in Rust; its pages are parsed like JSON bytes.
124    Http(String),
125    /// An `sl.checkpoint(...)`: no rows; its state is committed after every piece yielded before it.
126    Checkpoint,
127    Failed(CrossError),
128}
129
130impl Crossed {
131    /// About how many bytes the piece holds while it waits (a stream's batches are read later, so count nothing).
132    pub(crate) fn queued_bytes(&self) -> usize {
133        match self {
134            Self::Columns(columns) => columns.approximate_bytes(),
135            Self::Json { bytes, .. } => bytes.len(),
136            Self::ArrowBatch(batch) => batch.get_array_memory_size(),
137            Self::ArrowStream(_) | Self::Http(_) | Self::Checkpoint | Self::Failed(_) => 0,
138        }
139    }
140}
141
142/// Bytes of crossed data not parsed yet; the generator waits while a new piece would exceed the limit.
143#[derive(Debug, Default)]
144pub(crate) struct ByteBudget {
145    used: Mutex<usize>,
146    freed: Condvar,
147    limit: usize,
148}
149
150impl ByteBudget {
151    pub(crate) fn new(limit: usize) -> Self {
152        Self {
153            used: Mutex::new(0),
154            freed: Condvar::new(),
155            limit,
156        }
157    }
158
159    /// Wait until `bytes` more fit (always when nothing is queued), then count them.
160    pub(crate) fn acquire(&self, bytes: usize) {
161        let Ok(mut used) = self.used.lock() else {
162            return;
163        };
164        while *used > 0 && *used + bytes > self.limit {
165            used = match self.freed.wait(used) {
166                Ok(used) => used,
167                Err(_) => return,
168            };
169        }
170        *used += bytes;
171    }
172
173    /// Stop counting `bytes`, waking a waiting generator.
174    pub(crate) fn release(&self, bytes: usize) {
175        if let Ok(mut used) = self.used.lock() {
176            *used = used.saturating_sub(bytes);
177            self.freed.notify_all();
178        }
179    }
180}
181
182/// Counters of one table read, for benchmarks and logs, and its byte budget.
183#[derive(Debug, Default)]
184pub struct CrossingStats {
185    pub(crate) budget: ByteBudget,
186    pub(crate) rows: AtomicU64,
187    pub(crate) batches: AtomicU64,
188    /// Time spent reading or serialising dicts with the GIL held.
189    pub(crate) gil_nanos: AtomicU64,
190    /// Time spent parsing and converting to Arrow without the GIL.
191    pub(crate) parse_nanos: AtomicU64,
192}
193
194impl CrossingStats {
195    /// The counters so far.
196    pub fn snapshot(&self) -> StatsSnapshot {
197        StatsSnapshot {
198            rows: self.rows.load(Ordering::Relaxed),
199            batches: self.batches.load(Ordering::Relaxed),
200            gil_seconds: self.gil_nanos.load(Ordering::Relaxed) as f64 / 1e9,
201            parse_seconds: self.parse_nanos.load(Ordering::Relaxed) as f64 / 1e9,
202        }
203    }
204
205    pub(crate) fn add(counter: &AtomicU64, elapsed: Duration) {
206        counter.fetch_add(
207            u64::try_from(elapsed.as_nanos()).unwrap_or(u64::MAX),
208            Ordering::Relaxed,
209        );
210    }
211}
212
213/// A table read's counters at one moment.
214#[derive(Debug, Clone, Copy, PartialEq)]
215pub struct StatsSnapshot {
216    pub rows: u64,
217    pub batches: u64,
218    /// Seconds spent reading or serialising dicts with the GIL held.
219    pub gil_seconds: f64,
220    /// Seconds spent parsing and converting to Arrow without the GIL, summed over parser threads.
221    pub parse_seconds: f64,
222}
223
224/// What waiting for the next batch found.
225#[derive(Debug)]
226pub enum Polled {
227    Batch(RecordBatch),
228    /// `ctx.state` (as JSON) once every batch of the rows that crossed with it has come.
229    State(String),
230    Failed(CrossError),
231    /// Nothing arrived within the timeout.
232    Pending,
233    Finished,
234}
235
236/// The record batches of one table generator, each typed by inference, and the schema merged from all so far.
237#[derive(Debug)]
238pub struct TableBatches {
239    pub(crate) receiver: Receiver<Parsed>,
240    pub(crate) schema: Schema,
241    pub(crate) stats: Arc<CrossingStats>,
242    /// Whether the read's end marker has arrived.
243    pub(crate) finished: bool,
244}
245
246impl TableBatches {
247    /// The next batch, waiting at most `timeout`; call it with the GIL released.
248    pub fn poll(&mut self, timeout: Duration) -> Polled {
249        if self.finished {
250            return Polled::Finished;
251        }
252        match self.receiver.recv_timeout(timeout) {
253            Ok(Parsed::Batch(batch)) => {
254                self.schema = merge_schema(&self.schema, &batch.schema());
255                Polled::Batch(batch)
256            }
257            Ok(Parsed::State(state)) => Polled::State(state),
258            Ok(Parsed::Failed(error)) => {
259                self.finished = true;
260                Polled::Failed(error)
261            }
262            Ok(Parsed::Done) => {
263                self.finished = true;
264                Polled::Finished
265            }
266            Err(RecvTimeoutError::Timeout) => Polled::Pending,
267            Err(RecvTimeoutError::Disconnected) => {
268                self.finished = true;
269                Polled::Failed(CrossError::Data(
270                    "the crossing stopped before the table generator finished".to_owned(),
271                ))
272            }
273        }
274    }
275
276    /// The schema merged from every batch returned so far.
277    pub fn schema(&self) -> &Schema {
278        &self.schema
279    }
280
281    /// This read's counters.
282    pub fn stats(&self) -> &CrossingStats {
283        &self.stats
284    }
285}
286
287impl Iterator for TableBatches {
288    type Item = Result<RecordBatch, CrossError>;
289
290    /// The next batch, blocking; call it with the GIL released.
291    fn next(&mut self) -> Option<Self::Item> {
292        loop {
293            match self.poll(Duration::from_secs(3600)) {
294                Polled::Batch(batch) => return Some(Ok(batch)),
295                Polled::Failed(error) => return Some(Err(error)),
296                Polled::Pending | Polled::State(_) => {}
297                Polled::Finished => return None,
298            }
299        }
300    }
301}