1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use super::accumulate::{finish_collector_stage, push_collector_stage, validate_batch_schema};
use crate::error::{Error, Result};
use crate::pipeline::{
collate_batch, panic_message, record_first_fatal_error, send_with_backpressure, CollateMode,
CollectorItem, CollectorStage, ErrorPolicy,
};
use crate::pipeline::{SampleChunk, SequenceReorderBuffer, Stage};
use crate::sample::Sample;
use crate::transform::{BatchAccumulator, ShuffleBuffer};
use crossbeam_channel::{Receiver, RecvTimeoutError, Sender};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use std::thread::JoinHandle;
use std::time::Instant;
pub(crate) fn emit_items(
items: &mut Vec<CollectorItem>,
collate_mode: &CollateMode,
out_tx: &Sender<Vec<Sample>>,
error_policy: ErrorPolicy,
errors_skipped: &AtomicU64,
output_paused: &AtomicBool,
shutdown: &AtomicBool,
fatal_error: &std::sync::Mutex<Option<Error>>,
) -> bool {
for item in items.drain(..) {
match item {
CollectorItem::Sample(sample) => {
// Single samples are emitted without schema validation
if send_with_backpressure(out_tx, vec![sample], output_paused, shutdown) {
return true;
}
}
CollectorItem::Batch(batch) => {
// Validate schema consistency before collation (only when collation is enabled)
// This catches transforms that silently change field names/dtypes/shapes
let collation_enabled = !matches!(collate_mode, CollateMode::Disabled);
if collation_enabled {
if let Err(error) = validate_batch_schema(&batch) {
if handle_collector_error(
fatal_error,
error,
error_policy,
errors_skipped,
shutdown,
) && error_policy == ErrorPolicy::Fail
{
return true;
}
}
}
match collate_batch(batch, collate_mode) {
Ok(output) => {
if send_with_backpressure(out_tx, output, output_paused, shutdown) {
return true;
}
}
Err(error) => {
if handle_collector_error(
fatal_error,
error,
error_policy,
errors_skipped,
shutdown,
) && error_policy == ErrorPolicy::Fail
{
return true;
}
}
}
}
}
}
false
}
pub(crate) fn handle_collector_error(
fatal_error: &std::sync::Mutex<Option<Error>>,
error: Error,
error_policy: ErrorPolicy,
errors_skipped: &AtomicU64,
shutdown: &AtomicBool,
) -> bool {
match error_policy {
ErrorPolicy::Skip => {
errors_skipped.fetch_add(1, Ordering::Relaxed);
tracing::warn!("skipping collector item: {error}");
false
}
ErrorPolicy::Fail => {
tracing::error!("collector error: {error}");
record_first_fatal_error(fatal_error, error);
shutdown.store(true, Ordering::Relaxed);
true
}
}
}
#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
pub(crate) fn spawn_collector_thread(
raw_collector_stages: Vec<Stage>,
collate_mode: CollateMode,
error_policy: ErrorPolicy,
shuffle_seed: Option<u64>,
pending_sequence_limit: usize,
sequence_gap_timeout: std::time::Duration,
drop_last: bool,
proc_rx: Receiver<SampleChunk>,
out_tx: Sender<Vec<Sample>>,
output_paused: Arc<AtomicBool>,
shutdown: Arc<AtomicBool>,
errors_skipped: Arc<AtomicU64>,
fatal_error: Arc<std::sync::Mutex<Option<crate::error::Error>>>,
) -> Result<JoinHandle<()>> {
std::thread::Builder::new()
.name("tenshift-collector".into())
.spawn(move || {
let mut collector_stages: Vec<CollectorStage> = raw_collector_stages
.into_iter()
.filter_map(|stage| match stage {
Stage::Shuffle(buffer_size) => {
Some(CollectorStage::Shuffle(ShuffleBuffer::new(buffer_size, shuffle_seed)))
}
Stage::Batch(batch_size) => {
Some(CollectorStage::Batch(BatchAccumulator::new(batch_size, drop_last)))
}
Stage::Stateless(_) => {
// Invariant violation: partitioning should have routed
// stateless stages to worker threads. Log and skip.
tracing::error!(
"collector received a stateless transform that should \
have been partitioned to workers - skipping"
);
None
}
})
.collect();
let mut pending =
SequenceReorderBuffer::with_capacity(pending_sequence_limit.saturating_add(1));
let mut next_sequence = 0_u64;
let mut gap_started_at: Option<Instant> = None;
let mut items = Vec::with_capacity(4);
let mut next = Vec::with_capacity(4);
loop {
if shutdown.load(Ordering::Relaxed) {
break;
}
while let Some(chunk_samples) = pending.pop_next(next_sequence) {
gap_started_at = None;
next_sequence += 1;
for sample in chunk_samples {
items.clear();
items.push(CollectorItem::Sample(sample));
let mut failed = false;
for stage in &mut collector_stages {
next.clear();
for item in items.drain(..) {
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
push_collector_stage(stage, item, &mut next)
})) {
Ok(Ok(())) => {}
Ok(Err(error)) => {
if error_policy == ErrorPolicy::Fail {
record_first_fatal_error(&fatal_error, error.clone());
}
if handle_collector_error(
&fatal_error,
error,
error_policy,
&errors_skipped,
&shutdown,
) {
failed = true;
break;
}
}
Err(payload) => {
let msg = panic_message(payload);
tracing::error!("collector stage panicked during push: {}", msg);
if error_policy == ErrorPolicy::Fail {
record_first_fatal_error(
&fatal_error,
crate::error::Error::CollateFailed {
reason: format!("collector stage panicked: {msg}"),
},
);
shutdown.store(true, Ordering::Relaxed);
} else {
errors_skipped.fetch_add(1, Ordering::Relaxed);
}
failed = true;
break;
}
}
}
if failed || shutdown.load(Ordering::Relaxed) {
break;
}
std::mem::swap(&mut items, &mut next);
}
if (failed || shutdown.load(Ordering::Relaxed))
&& error_policy == ErrorPolicy::Fail
{
return;
}
if emit_items(
&mut items,
&collate_mode,
&out_tx,
error_policy,
&errors_skipped,
output_paused.as_ref(),
&shutdown,
&fatal_error,
) {
return;
}
}
}
// Backpressure instead of dropping. Workers forward *every*
// sequence -- an item that errors under `Skip` still emits its
// chunk (with fewer samples) -- so a sequence that has not arrived
// yet is merely delayed, never lost. When the out-of-order buffer
// grows past the limit, pause the source so the in-flight workers
// drain and the delayed chunk filling the gap arrives, rather than
// skipping it (which silently loses data under worker contention).
// A genuinely dead worker is still recovered by the gap timeout
// below. The pause latch clears once the buffer drains back down.
if pending.len() > pending_sequence_limit {
output_paused.store(true, Ordering::Relaxed);
} else if pending.len() <= pending_sequence_limit / 2 {
output_paused.store(false, Ordering::Relaxed);
}
if pending.has_sequence(next_sequence) {
continue;
}
if !pending.is_empty() {
let gap_started = gap_started_at.get_or_insert_with(Instant::now);
let elapsed = gap_started.elapsed();
if elapsed >= sequence_gap_timeout {
if error_policy == ErrorPolicy::Fail {
tracing::error!(
"collector timed out after {:?} waiting for missing sequence {} -- failing pipeline",
sequence_gap_timeout,
next_sequence
);
shutdown.store(true, Ordering::Relaxed);
return;
}
if let Some(first_avail) = pending.first_sequence() {
tracing::warn!(
"collector timed out after {:?} waiting for missing sequence {}; jumping to next available {}",
sequence_gap_timeout,
next_sequence,
first_avail
);
next_sequence = first_avail;
} else {
next_sequence += 1;
}
gap_started_at = None;
continue;
}
let remaining = sequence_gap_timeout.checked_sub(elapsed).unwrap_or_default();
match proc_rx.recv_timeout(remaining) {
Ok(chunk) => {
if chunk.sequence < next_sequence {
tracing::warn!("collector received obsolete sequence {}; dropping to prevent leak", chunk.sequence);
} else {
pending.insert(chunk.sequence, chunk.samples);
}
continue;
}
Err(RecvTimeoutError::Timeout) => {
if error_policy == ErrorPolicy::Fail {
tracing::error!(
"collector timed out after {:?} waiting for missing sequence {} -- failing pipeline",
sequence_gap_timeout,
next_sequence
);
shutdown.store(true, Ordering::Relaxed);
return;
}
if let Some(first_avail) = pending.first_sequence() {
tracing::warn!(
"collector timed out after {:?} waiting for missing sequence {}; jumping to next available {}",
sequence_gap_timeout,
next_sequence,
first_avail
);
next_sequence = first_avail;
} else {
next_sequence += 1;
}
gap_started_at = None;
continue;
}
Err(RecvTimeoutError::Disconnected) => break,
}
}
match proc_rx.recv() {
Ok(chunk) => {
if chunk.sequence < next_sequence {
tracing::warn!("collector received obsolete sequence {}; dropping to prevent leak", chunk.sequence);
} else {
pending.insert(chunk.sequence, chunk.samples);
}
}
Err(_) => break,
}
}
output_paused.store(false, Ordering::Relaxed);
if shutdown.load(Ordering::Relaxed) {
return;
}
let mut flush_items = Vec::new();
// If any stranded out-of-order sequences remain in pending (e.g. missing gaps), emit them chronologically.
for stranded_chunk in pending.into_ordered_chunks() {
for sample in stranded_chunk {
flush_items.push(CollectorItem::Sample(sample));
}
}
for stage in &mut collector_stages {
let mut next = Vec::with_capacity(flush_items.len());
for item in flush_items.drain(..) {
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
push_collector_stage(stage, item, &mut next)
})) {
Ok(Ok(())) => {}
Ok(Err(error)) => {
if error_policy == ErrorPolicy::Fail {
record_first_fatal_error(&fatal_error, error.clone());
}
if handle_collector_error(
&fatal_error,
error,
error_policy,
&errors_skipped,
&shutdown,
) && error_policy == ErrorPolicy::Fail
{
return;
}
}
Err(payload) => {
let msg = panic_message(payload);
tracing::error!("collector stage panicked during push: {}", msg);
if error_policy == ErrorPolicy::Fail {
record_first_fatal_error(
&fatal_error,
crate::error::Error::CollateFailed {
reason: format!("collector stage panicked: {msg}"),
},
);
shutdown.store(true, Ordering::Relaxed);
return;
}
errors_skipped.fetch_add(1, Ordering::Relaxed);
}
}
}
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
finish_collector_stage(stage)
})) {
Ok(finished) => next.extend(finished),
Err(payload) => {
let msg = panic_message(payload);
tracing::error!("collector stage panicked during finish: {}", msg);
if error_policy == ErrorPolicy::Fail {
record_first_fatal_error(
&fatal_error,
crate::error::Error::CollateFailed {
reason: format!("collector stage panicked during finish: {msg}"),
},
);
shutdown.store(true, Ordering::Relaxed);
return;
}
errors_skipped.fetch_add(1, Ordering::Relaxed);
}
}
flush_items = next;
}
let _ = emit_items(
&mut flush_items,
&collate_mode,
&out_tx,
error_policy,
&errors_skipped,
output_paused.as_ref(),
&shutdown,
&fatal_error,
);
})
.map_err(Into::into)
}