Skip to main content

o41_training_data/
engine.rs

1use crate::{config::Config, readers};
2use anyhow::{Result, ensure};
3use arrow::record_batch::RecordBatch;
4use crossbeam_channel::{Receiver, bounded};
5use serde::{Deserialize, Serialize};
6use std::{
7    collections::{HashMap, HashSet},
8    sync::Arc,
9};
10
11#[derive(Clone, Debug, Default, Serialize, Deserialize)]
12pub struct Position {
13    pub file: usize,
14    pub row: usize,
15    pub epoch: u64,
16    pub done: bool,
17}
18#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
19pub struct Coordinate {
20    pub stage: usize,
21    pub source: usize,
22    pub file: usize,
23    pub row: usize,
24    pub epoch: u64,
25}
26#[derive(Clone, Debug, Serialize, Deserialize)]
27#[serde(rename_all = "camelCase")]
28pub struct State {
29    pub version: u32,
30    pub stage: usize,
31    pub batch_index: u64,
32    pub batches_yielded: u64,
33    pub rows_yielded: u64,
34    pub positions: Vec<Position>,
35    pub mix_counter: u64,
36    pub shuffle_counter: u64,
37    pub buffer: Vec<Coordinate>,
38    pub partial: Vec<Coordinate>,
39}
40impl State {
41    pub fn new(config: &Config, stage: usize) -> Self {
42        Self {
43            version: 3,
44            stage,
45            batch_index: 0,
46            batches_yielded: 0,
47            rows_yielded: 0,
48            positions: vec![Position::default(); config.stages[stage].sources.len()],
49            mix_counter: 0,
50            shuffle_counter: 0,
51            buffer: Vec::new(),
52            partial: Vec::new(),
53        }
54    }
55    pub fn validate(&self, config: &Config) -> Result<()> {
56        ensure!(
57            self.version == 3 && self.stage < config.stages.len(),
58            "unsupported cursor version or stage"
59        );
60        let stage = &config.stages[self.stage];
61        ensure!(
62            self.positions.len() == stage.sources.len(),
63            "cursor source count mismatch"
64        );
65        for (p, g) in self.positions.iter().zip(&stage.sources) {
66            ensure!(p.file <= g.files.len(), "cursor file out of bounds");
67        }
68        ensure!(
69            self.partial.len() <= stage.batch_size,
70            "cursor partial batch too large"
71        );
72        for c in self.buffer.iter().chain(&self.partial) {
73            ensure!(
74                c.stage < config.stages.len(),
75                "cursor coordinate stage out of bounds"
76            );
77            let stage = &config.stages[c.stage];
78            ensure!(
79                c.source < stage.sources.len() && c.file < stage.sources[c.source].files.len(),
80                "cursor coordinate out of bounds"
81            );
82        }
83        Ok(())
84    }
85}
86// UTF-8 names "mix" and "shuffle". All operations wrap at 64 bits.
87// Stage keys are avalanched before combining, avoiding adjacent-counter shifts.
88fn mix64(mut x: u64) -> u64 {
89    x = (x ^ (x >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
90    x = (x ^ (x >> 27)).wrapping_mul(0x94d049bb133111eb);
91    x ^ (x >> 31)
92}
93pub fn random(seed: u64, stage: usize, name: &str, source: u64, counter: u64) -> u64 {
94    let mut key = 14695981039346656037u64;
95    for b in name.bytes() {
96        key = (key ^ b as u64).wrapping_mul(1099511628211);
97    }
98    let golden = 0x9e3779b97f4a7c15u64;
99    key = key.wrapping_add(seed)
100        ^ mix64((stage as u64).wrapping_add(1).wrapping_mul(golden))
101        ^ mix64(source.wrapping_mul(golden));
102    mix64(key.wrapping_add(counter.wrapping_add(1).wrapping_mul(golden)))
103}
104type Key = (usize, usize, usize);
105pub struct Engine {
106    pub config: Arc<Config>,
107    pub state: State,
108    cache: HashMap<Key, readers::Shard>,
109    pending: HashMap<Key, Receiver<Result<readers::Shard>>>,
110    rows: HashMap<Coordinate, RecordBatch>,
111    orders: Vec<Vec<Vec<usize>>>,
112    window: Option<Key>,
113    pool: rayon::ThreadPool,
114    client: Arc<crate::storage::Client>,
115}
116pub struct Batch {
117    pub columns: RecordBatch,
118    pub stage: usize,
119    pub index: u64,
120    pub state: State,
121}
122impl Engine {
123    pub fn new(config: Arc<Config>, state: State) -> Result<Self> {
124        let pool = rayon::ThreadPoolBuilder::new()
125            .num_threads(config.threads)
126            .build()?;
127        let runtime = Arc::new(
128            tokio::runtime::Builder::new_multi_thread()
129                .worker_threads(1)
130                .enable_all()
131                .build()?,
132        );
133        let client = Arc::new(crate::storage::Client::new(config.storage.clone(), runtime));
134        for (stage_index, stage) in config.stages.iter().enumerate() {
135            for (source_index, source) in stage.sources.iter().enumerate() {
136                let fields = source.fields.as_deref().unwrap_or(&config.fields);
137                let encoding = source
138                    .encoding
139                    .as_ref()
140                    .or(stage.encoding.as_ref())
141                    .unwrap();
142                let mut found = false;
143                for file in &source.files {
144                    use anyhow::Context;
145                    let sample = readers::read(file, encoding, &client, fields, 0, true, &config)
146                        .with_context(|| {
147                        format!("stage={stage_index} source={source_index}")
148                    })?;
149                    if sample.columns.num_rows() > 0 {
150                        found = true;
151                        break;
152                    }
153                }
154                ensure!(
155                    found,
156                    "stage {stage_index} source {source_index} {}: no record for field {}",
157                    source.files[0].uri,
158                    fields[0].name
159                );
160            }
161        }
162        let orders = config
163            .stages
164            .iter()
165            .enumerate()
166            .map(|(stage_index, stage)| {
167                stage
168                    .sources
169                    .iter()
170                    .enumerate()
171                    .map(|(source_index, source)| {
172                        let mut order: Vec<_> = (0..source.files.len()).collect();
173                        if stage.shuffle.is_some() {
174                            for (draw, i) in (1..order.len()).rev().enumerate() {
175                                let j = random(
176                                    config.seed,
177                                    stage_index,
178                                    "shards",
179                                    source_index as u64,
180                                    draw as u64,
181                                ) % (i as u64 + 1);
182                                order.swap(i, j as usize);
183                            }
184                        }
185                        order
186                    })
187                    .collect()
188            })
189            .collect();
190        let mut engine = Self {
191            config,
192            state,
193            cache: HashMap::new(),
194            pending: HashMap::new(),
195            rows: HashMap::new(),
196            orders,
197            window: None,
198            pool,
199            client,
200        };
201        engine.restore_rows()?;
202        Ok(engine)
203    }
204    fn heads(&self) -> impl Iterator<Item = Key> + '_ {
205        self.state
206            .positions
207            .iter()
208            .enumerate()
209            .filter(|(_, p)| !p.done)
210            .map(|(source, p)| {
211                (
212                    self.state.stage,
213                    source,
214                    self.orders[self.state.stage][source][p.file],
215                )
216            })
217    }
218    fn schedule(
219        &mut self,
220        stage_index: usize,
221        source: usize,
222        file: usize,
223        row: usize,
224        required: bool,
225    ) {
226        let key = (stage_index, source, file);
227        if self.cache.contains_key(&key) || self.pending.contains_key(&key) {
228            return;
229        }
230        // Future shards cannot take the slots needed by other sources' current shards.
231        let reserved = if required {
232            0
233        } else {
234            self.heads()
235                .filter(|k| !self.cache.contains_key(k) && !self.pending.contains_key(k))
236                .count()
237        };
238        if self.cache.len() + self.pending.len() + reserved
239            >= self.config.threads * self.config.lookahead
240        {
241            return;
242        }
243        let config = self.config.clone();
244        let client = self.client.clone();
245        let (send, recv) = bounded(1);
246        self.pool.spawn(move || {
247            let stage = &config.stages[stage_index];
248            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
249                readers::read(
250                    &stage.sources[source].files[file],
251                    stage.sources[source]
252                        .encoding
253                        .as_ref()
254                        .or(stage.encoding.as_ref())
255                        .unwrap(),
256                    &client,
257                    stage.sources[source]
258                        .fields
259                        .as_deref()
260                        .unwrap_or(&config.fields),
261                    row,
262                    false,
263                    &config,
264                )
265            }))
266            .unwrap_or_else(|_| Err(anyhow::anyhow!("shard reader panicked")));
267            let result = result
268                .map_err(|error| anyhow::anyhow!("stage={stage_index} source={source}: {error:#}"));
269            let _ = send.send(result);
270        });
271        self.pending.insert(key, recv);
272    }
273    fn lookahead(&mut self, source: usize, file: usize) {
274        if self.window == Some((self.state.stage, source, file)) {
275            return;
276        }
277        self.window = Some((self.state.stage, source, file));
278        let count = self.config.stages[self.state.stage].sources[source]
279            .files
280            .len();
281        for next in file..(file + self.config.threads).min(count) {
282            self.schedule(
283                self.state.stage,
284                source,
285                self.orders[self.state.stage][source][next],
286                if next == file {
287                    self.state.positions[source].row
288                } else {
289                    0
290                },
291                next == file,
292            );
293        }
294    }
295    fn load(&mut self, stage_index: usize, source: usize, file: usize, row: usize) -> Result<()> {
296        let key = (stage_index, source, file);
297        if self.cache.get(&key).is_some_and(|s| s.offset <= row) {
298            return Ok(());
299        }
300        self.cache.remove(&key);
301        if !self.pending.contains_key(&key) {
302            ensure!(
303                self.cache.len() + self.pending.len() < self.config.threads * self.config.lookahead,
304                "reader slots exhausted"
305            );
306            self.schedule(stage_index, source, file, row, true);
307        }
308        let wait = crate::profile::Timer::new(7);
309        let result = self
310            .pending
311            .remove(&key)
312            .unwrap()
313            .recv()
314            .map_err(|_| anyhow::anyhow!("shard worker stopped"))??;
315        drop(wait);
316        if result.offset > row {
317            return self.load(stage_index, source, file, row);
318        }
319        self.cache.insert(key, result);
320        Ok(())
321    }
322    fn retain_row(&mut self, c: Coordinate) -> Result<()> {
323        let shard = &self.cache[&(c.stage, c.source, c.file)];
324        // A slice would retain the entire shard. Copy just the projected row.
325        let row = arrow::compute::interleave_record_batch(
326            &[&shard.columns],
327            &[(0, c.row - shard.offset)],
328        )?;
329        self.rows.insert(c, row);
330        Ok(())
331    }
332    fn restore_rows(&mut self) -> Result<()> {
333        let mut groups = std::collections::BTreeMap::<Key, Vec<Coordinate>>::new();
334        for c in self.state.buffer.iter().chain(&self.state.partial) {
335            groups
336                .entry((c.stage, c.source, c.file))
337                .or_default()
338                .push(c.clone());
339        }
340        let heads: HashSet<_> = self.heads().collect();
341        let mut groups: Vec<_> = groups.into_iter().collect();
342        // Restore old shards first; retain current shards for their unread suffixes.
343        groups.sort_by_key(|(key, _)| heads.contains(key));
344        for (key, coordinates) in groups {
345            let mut start = coordinates.iter().map(|c| c.row).min().unwrap();
346            if heads.contains(&key) {
347                start = start.min(self.state.positions[key.1].row);
348            }
349            self.load(key.0, key.1, key.2, start)?;
350            for c in coordinates {
351                self.retain_row(c)?;
352            }
353            if !heads.contains(&key) {
354                self.cache.remove(&key);
355            }
356        }
357        Ok(())
358    }
359    fn source_next(&mut self, source: usize) -> Result<Option<Coordinate>> {
360        let stage = self.state.stage;
361        let count = self.orders[stage][source].len();
362        let infinite = self.config.stages[stage].infinite;
363        let mut empty = 0;
364        loop {
365            let p = &self.state.positions[source];
366            if p.done {
367                return Ok(None);
368            }
369            let (position, row, epoch) = (p.file, p.row, p.epoch);
370            let file = self.orders[stage][source][position];
371            self.lookahead(source, position);
372            self.load(stage, source, file, row)?;
373            let end = self.cache[&(stage, source, file)].num_rows();
374            let result = if row < end {
375                let c = Coordinate {
376                    stage,
377                    source,
378                    file,
379                    row,
380                    epoch,
381                };
382                self.retain_row(c.clone())?;
383                Some(c)
384            } else {
385                None
386            };
387            let p = &mut self.state.positions[source];
388            p.row += usize::from(result.is_some());
389            if p.row >= end {
390                self.cache.remove(&(stage, source, file));
391                p.row = 0;
392                p.file += 1;
393                if p.file == count {
394                    p.epoch += 1;
395                    if infinite {
396                        p.file = 0;
397                    } else {
398                        p.done = true;
399                    }
400                }
401            }
402            if result.is_some() {
403                return Ok(result);
404            }
405            empty += 1;
406            ensure!(
407                !infinite || empty <= count,
408                "infinite source has no records"
409            );
410        }
411    }
412    fn mixed(&mut self) -> Result<Option<Coordinate>> {
413        loop {
414            let groups = &self.config.stages[self.state.stage].sources;
415            let total: f64 = groups
416                .iter()
417                .zip(&self.state.positions)
418                .filter(|(_, p)| !p.done)
419                .map(|(g, _)| g.weight.unwrap_or(1.0))
420                .sum();
421            if total == 0.0 {
422                return Ok(None);
423            }
424            let mut chosen = 0;
425            if groups.len() > 1 {
426                let draw = (random(
427                    self.config.seed,
428                    self.state.stage,
429                    "mix",
430                    0,
431                    self.state.mix_counter,
432                ) >> 11) as f64
433                    * (1.0 / ((1u64 << 53) as f64));
434                self.state.mix_counter = self.state.mix_counter.wrapping_add(1);
435                let mut target = draw * total;
436                for (i, (g, p)) in groups.iter().zip(&self.state.positions).enumerate() {
437                    if p.done || g.weight.unwrap_or(1.0) == 0.0 {
438                        continue;
439                    }
440                    chosen = i;
441                    target -= g.weight.unwrap_or(1.0);
442                    if target < 0.0 {
443                        break;
444                    }
445                }
446            }
447            if let Some(c) = self.source_next(chosen)? {
448                return Ok(Some(c));
449            }
450        }
451    }
452    fn coordinate(&mut self) -> Result<Option<Coordinate>> {
453        let capacity = self.config.stages[self.state.stage]
454            .shuffle
455            .as_ref()
456            .map_or(0, |s| s.buffer_rows);
457        if capacity == 0 && self.state.buffer.is_empty() {
458            return self.mixed();
459        }
460        while self.state.buffer.len() < capacity {
461            if let Some(c) = self.mixed()? {
462                self.state.buffer.push(c);
463            } else {
464                break;
465            }
466        }
467        if self.state.buffer.is_empty() {
468            return Ok(None);
469        }
470        let i = (random(
471            self.config.seed,
472            self.state.stage,
473            "shuffle",
474            0,
475            self.state.shuffle_counter,
476        ) % self.state.buffer.len() as u64) as usize;
477        self.state.shuffle_counter = self.state.shuffle_counter.wrapping_add(1);
478        let replacement = if self.state.buffer.len() <= capacity {
479            self.mixed()?
480        } else {
481            None
482        };
483        let result = if let Some(c) = replacement {
484            std::mem::replace(&mut self.state.buffer[i], c)
485        } else {
486            self.state.buffer.swap_remove(i)
487        };
488        Ok(Some(result))
489    }
490    fn retire(&mut self) {
491        let keep: HashSet<_> = self
492            .state
493            .buffer
494            .iter()
495            .chain(&self.state.partial)
496            .collect();
497        self.rows.retain(|c, _| keep.contains(c));
498    }
499    fn materialize(&self, coordinates: &[Coordinate]) -> Result<RecordBatch> {
500        let _assembly = crate::profile::Timer::new(6);
501        let rows = coordinates
502            .iter()
503            .map(|c| &self.rows[c])
504            .collect::<Vec<_>>();
505        let order = (0..rows.len()).map(|i| (i, 0)).collect::<Vec<_>>();
506        Ok(arrow::compute::interleave_record_batch(&rows, &order)?)
507    }
508    /// Assembles the next global batch and takes its index, regardless of rank.
509    fn assemble(&mut self) -> Result<Option<(Vec<Coordinate>, u64)>> {
510        let mut short_epochs = 0;
511        loop {
512            let stage = &self.config.stages[self.state.stage];
513            let size = stage.batch_size;
514            let drop_last = stage.drop_last;
515            let epoch_boundary = stage.sources.len() == 1 && stage.shuffle.is_none();
516            let mut coordinates = std::mem::take(&mut self.state.partial);
517            while coordinates.len() < size {
518                let Some(c) = self.coordinate()? else {
519                    break;
520                };
521                if epoch_boundary
522                    && coordinates
523                        .first()
524                        .is_some_and(|first| first.epoch != c.epoch)
525                {
526                    self.state.partial.push(c);
527                    break;
528                }
529                coordinates.push(c);
530            }
531            if coordinates.len() < size && drop_last {
532                if self.state.partial.is_empty() {
533                    return Ok(None);
534                }
535                // Two short batches in a row mean a whole epoch fits in one.
536                short_epochs += 1;
537                ensure!(
538                    short_epochs < 2,
539                    "dropLast discards every batch: an epoch has fewer than batchSize rows"
540                );
541                continue;
542            }
543            if coordinates.is_empty() {
544                return Ok(None);
545            }
546            let index = self.state.batch_index;
547            self.state.batch_index += 1;
548            return Ok(Some((coordinates, index)));
549        }
550    }
551    pub fn next(&mut self) -> Result<Option<Batch>> {
552        loop {
553            let Some((coordinates, index)) = self.assemble()? else {
554                return Ok(None);
555            };
556            if index % self.config.world_size != self.config.rank {
557                self.retire();
558                continue;
559            }
560            let columns = self.materialize(&coordinates)?;
561            self.retire();
562            // Finish the round of world_size batches before yielding, so every
563            // rank yields the same count and a finite tail that cannot fill a
564            // round is dropped on all ranks.
565            while !self
566                .state
567                .batch_index
568                .is_multiple_of(self.config.world_size)
569            {
570                if self.assemble()?.is_none() {
571                    return Ok(None);
572                }
573                self.retire();
574            }
575            self.state.batches_yielded += 1;
576            self.state.rows_yielded += coordinates.len() as u64;
577            return Ok(Some(Batch {
578                columns,
579                stage: self.state.stage,
580                index,
581                state: self.state.clone(),
582            }));
583        }
584    }
585    /// Draws the global batches owned by other ranks up to the next multiple of
586    /// world_size. Ranks that advance after the same number of local batches
587    /// then switch stages from one identical cursor and stay partitioned.
588    pub fn align(&mut self) -> Result<()> {
589        while !self
590            .state
591            .batch_index
592            .is_multiple_of(self.config.world_size)
593        {
594            if self.assemble()?.is_none() {
595                break;
596            }
597            self.retire();
598        }
599        Ok(())
600    }
601}
602
603impl Drop for Engine {
604    fn drop(&mut self) {
605        for (_, pending) in self.pending.drain() {
606            let _ = pending.recv();
607        }
608    }
609}