-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathpipeline.rs
More file actions
4238 lines (3822 loc) · 152 KB
/
Copy pathpipeline.rs
File metadata and controls
4238 lines (3822 loc) · 152 KB
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::io::{self, Read};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use asupersync::Cx;
use frankensearch_core::{Canonicalizer, Embedder, SearchError, SearchResult};
use fsqlite::AsyncConnection;
use fsqlite_types::value::SqliteValue;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use crate::Storage;
use crate::connection::map_storage_error;
use crate::content_hash::{ContentHasher, record_content_hash};
use crate::document::{DocumentRecord, EmbeddingStatus, upsert_document};
use crate::job_queue::{EnqueueOutcome, EnqueueRequest, PersistentJobQueue, enqueue_inner};
use crate::schema::row_i64;
const PIPELINE_SUBSYSTEM: &str = "storage_pipeline";
const CORRELATION_METADATA_KEY: &str = "correlation_id";
const MAX_CONTENT_PREVIEW_CHARS: usize = 400;
const MAX_SOURCE_FILE_BYTES: usize = 2 * 1024 * 1024;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IngestRequest {
pub doc_id: String,
pub text: String,
pub source_path: Option<String>,
pub metadata: Option<Value>,
pub correlation_id: Option<String>,
pub enqueue_quality: bool,
}
impl IngestRequest {
#[must_use]
pub fn new(doc_id: impl Into<String>, text: impl Into<String>) -> Self {
Self {
doc_id: doc_id.into(),
text: text.into(),
source_path: None,
metadata: None,
correlation_id: None,
enqueue_quality: true,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum IngestAction {
New,
Updated,
Unchanged,
Skipped { reason: String },
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IngestResult {
pub doc_id: String,
pub action: IngestAction,
pub fast_job_enqueued: bool,
pub quality_job_enqueued: bool,
pub correlation_id: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct BatchIngestResult {
pub requested: usize,
pub inserted: usize,
pub updated: usize,
pub unchanged: usize,
pub skipped: usize,
pub fast_jobs_enqueued: usize,
pub quality_jobs_enqueued: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct PipelineConfig {
pub fast_priority: i32,
pub quality_priority: i32,
pub process_batch_size: usize,
pub worker_idle_sleep_ms: u64,
pub worker_max_idle_cycles: Option<usize>,
}
impl Default for PipelineConfig {
fn default() -> Self {
Self {
fast_priority: 1,
quality_priority: 0,
process_batch_size: 32,
worker_idle_sleep_ms: 25,
worker_max_idle_cycles: Some(1),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct BatchProcessResult {
pub jobs_claimed: usize,
pub jobs_completed: usize,
pub jobs_failed: usize,
pub jobs_skipped: usize,
pub terminal_failures: usize,
pub embed_time: Duration,
pub total_time: Duration,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct WorkerReport {
pub reclaimed_on_startup: usize,
pub batches_processed: usize,
pub jobs_completed: usize,
pub jobs_failed: usize,
pub jobs_skipped: usize,
pub idle_cycles: usize,
pub terminal_failures_encountered: usize,
}
#[derive(Debug, Default)]
pub struct PipelineMetrics {
pub total_ingest_calls: AtomicU64,
pub total_ingest_inserted: AtomicU64,
pub total_ingest_updated: AtomicU64,
pub total_ingest_unchanged: AtomicU64,
pub total_ingest_skipped: AtomicU64,
pub total_jobs_claimed: AtomicU64,
pub total_jobs_completed: AtomicU64,
pub total_jobs_failed: AtomicU64,
pub total_jobs_skipped: AtomicU64,
pub total_embed_time_us: AtomicU64,
pub total_reclaimed: AtomicU64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct PipelineMetricsSnapshot {
pub total_ingest_calls: u64,
pub total_ingest_inserted: u64,
pub total_ingest_updated: u64,
pub total_ingest_unchanged: u64,
pub total_ingest_skipped: u64,
pub total_jobs_claimed: u64,
pub total_jobs_completed: u64,
pub total_jobs_failed: u64,
pub total_jobs_skipped: u64,
pub total_embed_time_us: u64,
pub total_reclaimed: u64,
}
impl PipelineMetrics {
#[must_use]
pub fn snapshot(&self) -> PipelineMetricsSnapshot {
PipelineMetricsSnapshot {
total_ingest_calls: self.total_ingest_calls.load(Ordering::Relaxed),
total_ingest_inserted: self.total_ingest_inserted.load(Ordering::Relaxed),
total_ingest_updated: self.total_ingest_updated.load(Ordering::Relaxed),
total_ingest_unchanged: self.total_ingest_unchanged.load(Ordering::Relaxed),
total_ingest_skipped: self.total_ingest_skipped.load(Ordering::Relaxed),
total_jobs_claimed: self.total_jobs_claimed.load(Ordering::Relaxed),
total_jobs_completed: self.total_jobs_completed.load(Ordering::Relaxed),
total_jobs_failed: self.total_jobs_failed.load(Ordering::Relaxed),
total_jobs_skipped: self.total_jobs_skipped.load(Ordering::Relaxed),
total_embed_time_us: self.total_embed_time_us.load(Ordering::Relaxed),
total_reclaimed: self.total_reclaimed.load(Ordering::Relaxed),
}
}
}
pub trait EmbeddingVectorSink: Send + Sync {
fn persist(&self, doc_id: &str, embedder_id: &str, embedding: &[f32]) -> SearchResult<()>;
}
#[derive(Debug, Default)]
pub struct InMemoryVectorSink {
entries: Mutex<Vec<PersistedEmbedding>>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct PersistedEmbedding {
pub doc_id: String,
pub embedder_id: String,
pub embedding: Vec<f32>,
}
impl InMemoryVectorSink {
#[must_use]
pub fn entries(&self) -> Vec<PersistedEmbedding> {
self.entries
.lock()
.unwrap_or_else(|poisoned| {
tracing::warn!(
target: "frankensearch.pipeline",
"vector sink lock poisoned; using recovered state"
);
poisoned.into_inner()
})
.clone()
}
}
impl EmbeddingVectorSink for InMemoryVectorSink {
fn persist(&self, doc_id: &str, embedder_id: &str, embedding: &[f32]) -> SearchResult<()> {
{
let mut guard = self.entries.lock().unwrap_or_else(|poisoned| {
tracing::warn!(
target: "frankensearch.pipeline",
"vector sink lock poisoned; using recovered state"
);
poisoned.into_inner()
});
guard.push(PersistedEmbedding {
doc_id: doc_id.to_owned(),
embedder_id: embedder_id.to_owned(),
embedding: embedding.to_vec(),
});
}
Ok(())
}
}
pub struct StorageBackedJobRunner {
storage: Arc<Storage>,
queue: Arc<PersistentJobQueue>,
canonicalizer: Arc<dyn Canonicalizer>,
fast_embedder: Arc<dyn Embedder>,
quality_embedder: Option<Arc<dyn Embedder>>,
vector_sink: Arc<dyn EmbeddingVectorSink>,
config: PipelineConfig,
metrics: Arc<PipelineMetrics>,
}
impl std::fmt::Debug for StorageBackedJobRunner {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("StorageBackedJobRunner")
.field("config", &self.config)
.field("fast_embedder_id", &self.fast_embedder.id())
.field(
"quality_embedder_id",
&self.quality_embedder.as_ref().map(|embedder| embedder.id()),
)
.finish_non_exhaustive()
}
}
impl StorageBackedJobRunner {
#[must_use]
pub fn new(
storage: Arc<Storage>,
queue: Arc<PersistentJobQueue>,
canonicalizer: Arc<dyn Canonicalizer>,
fast_embedder: Arc<dyn Embedder>,
vector_sink: Arc<dyn EmbeddingVectorSink>,
) -> Self {
Self {
storage,
queue,
canonicalizer,
fast_embedder,
quality_embedder: None,
vector_sink,
config: PipelineConfig::default(),
metrics: Arc::new(PipelineMetrics::default()),
}
}
#[must_use]
pub fn with_quality_embedder(mut self, quality_embedder: Arc<dyn Embedder>) -> Self {
self.quality_embedder = Some(quality_embedder);
self
}
#[must_use]
pub fn with_config(mut self, config: PipelineConfig) -> Self {
self.config = config;
self
}
#[must_use]
pub fn with_metrics(mut self, metrics: Arc<PipelineMetrics>) -> Self {
self.metrics = metrics;
self
}
#[must_use]
pub const fn config(&self) -> &PipelineConfig {
&self.config
}
#[must_use]
pub fn metrics(&self) -> &PipelineMetrics {
self.metrics.as_ref()
}
#[allow(clippy::too_many_lines)]
pub fn ingest(&self, request: IngestRequest) -> SearchResult<IngestResult> {
ensure_non_empty(&request.doc_id, "doc_id")?;
let correlation_id = resolve_correlation_id(&request.doc_id, request.correlation_id);
self.metrics
.total_ingest_calls
.fetch_add(1, Ordering::Relaxed);
let canonical_text = self.canonicalizer.canonicalize(&request.text);
if canonical_text.trim().is_empty() {
self.metrics
.total_ingest_skipped
.fetch_add(1, Ordering::Relaxed);
tracing::info!(
target: "frankensearch.storage.pipeline",
stage = "ingest",
doc_id = %request.doc_id,
correlation_id = %correlation_id,
action = "skip_empty_canonical_text",
"document ingest skipped"
);
return Ok(IngestResult {
doc_id: request.doc_id,
action: IngestAction::Skipped {
reason: "empty_canonical_text".to_owned(),
},
fast_job_enqueued: false,
quality_job_enqueued: false,
correlation_id,
});
}
/* Backpressure check moved inside transaction for TOCTOU safety */
let now_ms = unix_timestamp_ms()?;
let content_hash = ContentHasher::hash(&canonical_text);
// Reuse the digest for the hex form instead of running SHA-256 a second time
// (`hash_hex` would re-hash `canonical_text`). Byte-identical hex, one hash per doc.
let content_hash_hex = ContentHasher::to_hex(&content_hash);
let preview = truncate_chars(&canonical_text, MAX_CONTENT_PREVIEW_CHARS);
// ASCII fast-path: for ASCII text the char count equals the byte length, and `str::is_ascii`
// is a SIMD byte scan far cheaper than `chars().count()`'s per-char count. Non-ASCII falls
// back. Identical result for every input (`content_char_len_matches_slow`).
let content_length = content_char_len(&canonical_text);
let metadata = Some(with_correlation_metadata(request.metadata, &correlation_id));
let document = DocumentRecord {
doc_id: request.doc_id.clone(),
source_path: request.source_path,
content_preview: preview,
content_hash,
content_length,
created_at: now_ms,
updated_at: now_ms,
metadata,
};
let fast_embedder_id = self.fast_embedder.id().to_owned();
let maybe_quality_embedder_id = self
.quality_embedder
.as_ref()
.map(|embedder| embedder.id().to_owned());
let quality_requested = request.enqueue_quality
&& maybe_quality_embedder_id.as_deref() != Some(fast_embedder_id.as_str());
let tx_result = self.storage.transaction(|conn| {
let fast_dedup =
dedup_state_for_doc(conn, &request.doc_id, &content_hash, &fast_embedder_id)?;
let quality_dedup = if quality_requested {
if let Some(quality_embedder_id) = maybe_quality_embedder_id.as_deref() {
Some(dedup_state_for_doc(
conn,
&request.doc_id,
&content_hash,
quality_embedder_id,
)?)
} else {
None
}
} else {
None
};
let fast_needs_enqueue = fast_dedup.state != DedupState::Unchanged;
let quality_needs_enqueue =
quality_dedup.is_some_and(|q| q.state != DedupState::Unchanged);
if !fast_needs_enqueue && !quality_needs_enqueue {
upsert_document(conn, &document)?;
return Ok(IngestTxResult {
action: IngestAction::Unchanged,
fast_job_enqueued: false,
quality_job_enqueued: false,
});
}
let ready_params = [SqliteValue::Integer(now_ms)];
let ready_rows = conn.query_with_params_sync("SELECT COUNT(*) FROM embedding_jobs WHERE status = 'pending' AND submitted_at <= ?1;",
&ready_params,)
.map_err(map_storage_error)?;
let ready_pending = if let Some(row) = ready_rows.first() {
usize::try_from(row_i64(row, 0, "embedding_jobs.ready_pending")?)
.unwrap_or(usize::MAX)
} else {
0
};
if ready_pending > self.queue.config().backpressure_threshold {
return Err(SearchError::QueueFull {
pending: ready_pending,
capacity: self.queue.config().backpressure_threshold,
});
}
upsert_document(conn, &document)?;
if fast_dedup.state == DedupState::Changed {
reset_embedding_status(conn, &request.doc_id)?;
}
let _ = record_content_hash(conn, &content_hash_hex, &request.doc_id, now_ms)?;
let fast_job_enqueued = if fast_needs_enqueue {
let fast_request = EnqueueRequest::new(
request.doc_id.clone(),
fast_embedder_id.clone(),
content_hash,
self.config.fast_priority,
);
let fast_outcome =
enqueue_inner(conn, &fast_request, now_ms, self.queue.config().max_retries)?;
matches!(
fast_outcome,
EnqueueOutcome::Inserted | EnqueueOutcome::Replaced
)
} else {
false
};
let mut quality_job_enqueued = false;
if quality_needs_enqueue {
if let Some(quality_embedder_id) = maybe_quality_embedder_id.as_ref() {
let quality_request = EnqueueRequest::new(
request.doc_id.clone(),
quality_embedder_id.clone(),
content_hash,
self.config.quality_priority,
);
let quality_outcome = enqueue_inner(
conn,
&quality_request,
now_ms,
self.queue.config().max_retries,
)?;
quality_job_enqueued = matches!(
quality_outcome,
EnqueueOutcome::Inserted | EnqueueOutcome::Replaced
);
}
}
let action = match fast_dedup.state {
DedupState::New => IngestAction::New,
DedupState::Changed => IngestAction::Updated,
DedupState::Unchanged => IngestAction::Unchanged,
};
Ok(IngestTxResult {
action,
fast_job_enqueued,
quality_job_enqueued,
})
})?;
self.record_ingest_metrics(&tx_result);
tracing::info!(
target: "frankensearch.storage.pipeline",
stage = "ingest",
event = "document_ingested",
doc_id = %request.doc_id,
correlation_id = %correlation_id,
action = %ingest_action_name(&tx_result.action),
content_hash = %content_hash_hex,
fast_job_enqueued = tx_result.fast_job_enqueued,
quality_job_enqueued = tx_result.quality_job_enqueued,
"document ingest completed"
);
Ok(IngestResult {
doc_id: request.doc_id,
action: tx_result.action,
fast_job_enqueued: tx_result.fast_job_enqueued,
quality_job_enqueued: tx_result.quality_job_enqueued,
correlation_id,
})
}
pub fn ingest_batch(&self, requests: &[IngestRequest]) -> SearchResult<BatchIngestResult> {
let mut summary = BatchIngestResult {
requested: requests.len(),
..BatchIngestResult::default()
};
for request in requests {
let result = self.ingest(request.clone())?;
match result.action {
IngestAction::New => summary.inserted += 1,
IngestAction::Updated => summary.updated += 1,
IngestAction::Unchanged => summary.unchanged += 1,
IngestAction::Skipped { .. } => summary.skipped += 1,
}
if result.fast_job_enqueued {
summary.fast_jobs_enqueued += 1;
}
if result.quality_job_enqueued {
summary.quality_jobs_enqueued += 1;
}
}
Ok(summary)
}
#[allow(clippy::too_many_lines, clippy::future_not_send)]
pub async fn process_batch(
&self,
cx: &Cx,
worker_id: &str,
) -> SearchResult<BatchProcessResult> {
ensure_non_empty(worker_id, "worker_id")?;
pipeline_checkpoint(cx, "storage.pipeline.process_batch")?;
let total_start = Instant::now();
let claimed = self
.queue
.claim_batch(worker_id, self.config.process_batch_size)?;
let mut result = BatchProcessResult {
jobs_claimed: claimed.len(),
..BatchProcessResult::default()
};
if claimed.is_empty() {
result.total_time = total_start.elapsed();
return Ok(result);
}
self.metrics
.total_jobs_claimed
.fetch_add(usize_to_u64(claimed.len()), Ordering::Relaxed);
let embed_start = Instant::now();
for job in &claimed {
pipeline_checkpoint(cx, "storage.pipeline.process_batch")?;
let job_started = Instant::now();
let doc = self.storage.get_document(&job.doc_id)?;
let Some(doc) = doc else {
let message = format!("document {} missing during process_batch", job.doc_id);
if let Err(fail_err) = self.queue.fail(job.job_id, &message) {
tracing::warn!(
target: "frankensearch.storage.pipeline",
job_id = job.job_id,
error = %fail_err,
"failed to record job failure in queue"
);
}
result.jobs_failed += 1;
tracing::warn!(
target: "frankensearch.storage.pipeline",
stage = "process_batch",
worker_id,
doc_id = %job.doc_id,
embedder_id = %job.embedder_id,
reason = "document_missing",
"embedding job failed"
);
continue;
};
let correlation_id = extract_correlation_id(doc.metadata.as_ref())
.unwrap_or_else(|| fallback_correlation_id(&job.doc_id));
let text_cow = if let Some(path) = &doc.source_path {
match read_source_text_with_limit(path, MAX_SOURCE_FILE_BYTES) {
Ok(raw) => std::borrow::Cow::Owned(self.canonicalizer.canonicalize(&raw)),
Err(error) => {
tracing::warn!(
target: "frankensearch.storage.pipeline",
stage = "process_batch",
worker_id,
doc_id = %job.doc_id,
path = %path,
max_source_file_bytes = MAX_SOURCE_FILE_BYTES,
error = %error,
"failed to read source file; falling back to content preview"
);
std::borrow::Cow::Borrowed(doc.content_preview.as_str())
}
}
} else {
if doc.content_length > MAX_CONTENT_PREVIEW_CHARS {
tracing::warn!(
target: "frankensearch.storage.pipeline",
stage = "process_batch",
worker_id,
doc_id = %job.doc_id,
content_length = doc.content_length,
"document has no source_path and exceeds preview length; embedding will be truncated"
);
}
std::borrow::Cow::Borrowed(doc.content_preview.as_str())
};
let text = text_cow.as_ref();
if text.trim().is_empty() {
let skip_reason = "empty content preview";
self.queue.skip(job.job_id, skip_reason)?;
if let Err(error) =
self.storage
.mark_skipped(&job.doc_id, &job.embedder_id, skip_reason)
{
tracing::warn!(
target: "frankensearch.storage.pipeline",
stage = "mark_skipped",
worker_id,
correlation_id = %correlation_id,
doc_id = %job.doc_id,
embedder_id = %job.embedder_id,
error = %error,
"failed to record skipped status"
);
}
result.jobs_skipped += 1;
tracing::info!(
target: "frankensearch.storage.pipeline",
stage = "process_batch",
worker_id,
correlation_id = %correlation_id,
doc_id = %job.doc_id,
embedder_id = %job.embedder_id,
reason = "empty_content_preview",
"embedding job skipped"
);
continue;
}
if is_hash_embedder(&job.embedder_id) {
let skip_reason = "hash embeddings computed on-the-fly";
self.queue.skip(job.job_id, skip_reason)?;
if let Err(error) =
self.storage
.mark_skipped(&job.doc_id, &job.embedder_id, skip_reason)
{
tracing::warn!(
target: "frankensearch.storage.pipeline",
stage = "mark_skipped",
worker_id,
correlation_id = %correlation_id,
doc_id = %job.doc_id,
embedder_id = %job.embedder_id,
error = %error,
"failed to record skipped status"
);
}
result.jobs_skipped += 1;
tracing::info!(
target: "frankensearch.storage.pipeline",
stage = "process_batch",
worker_id,
correlation_id = %correlation_id,
doc_id = %job.doc_id,
embedder_id = %job.embedder_id,
reason = "hash_embedder_on_the_fly",
"embedding job skipped"
);
continue;
}
let embedder = match self.embedder_for_id(&job.embedder_id) {
Ok(embedder) => embedder,
Err(error) => {
let error_message = error.to_string();
if self.handle_job_failure(job, &error) {
result.terminal_failures += 1;
}
result.jobs_failed += 1;
tracing::warn!(
target: "frankensearch.storage.pipeline",
stage = "process_batch",
worker_id,
doc_id = %job.doc_id,
embedder_id = %job.embedder_id,
error = %error_message,
"failed to resolve embedder for queued job"
);
continue;
}
};
let embedding = match embedder.embed(cx, text).await {
Ok(embedding) => embedding,
Err(error) => {
if matches!(error, SearchError::Cancelled { .. }) {
return Err(error);
}
if self.handle_job_failure(job, &error) {
result.terminal_failures += 1;
}
result.jobs_failed += 1;
tracing::warn!(
target: "frankensearch.storage.pipeline",
stage = "embed",
worker_id,
correlation_id = %correlation_id,
doc_id = %job.doc_id,
embedder_id = %job.embedder_id,
error = %error,
"embedding inference failed"
);
continue;
}
};
// Reject unusable embeddings before any sink sees them: an
// all-zero or non-finite vector can never match a query, and a
// persisted one becomes a permanently dead record that drags the
// index toward the NoUsableVectors zero-signal state (bd-tqhc).
let norm_sq: f32 = embedding.iter().map(|value| value * value).sum();
if embedding.iter().any(|value| !value.is_finite())
|| norm_sq == 0.0
|| !norm_sq.is_finite()
{
let error = SearchError::InvalidConfig {
field: "embedding".to_owned(),
value: "<unusable vector>".to_owned(),
reason: "embedding must be finite with non-zero norm; refusing to persist \
an unsearchable record"
.to_owned(),
};
if self.handle_job_failure(job, &error) {
result.terminal_failures += 1;
}
result.jobs_failed += 1;
tracing::warn!(
target: "frankensearch.storage.pipeline",
stage = "validate",
worker_id,
correlation_id = %correlation_id,
doc_id = %job.doc_id,
embedder_id = %job.embedder_id,
"embedder produced an unusable (zero-norm or non-finite) vector; \
job failed without persisting"
);
continue;
}
let write_result = self
.vector_sink
.persist(&job.doc_id, &job.embedder_id, &embedding);
if let Err(error) = write_result {
if matches!(error, SearchError::Cancelled { .. }) {
return Err(error);
}
if self.handle_job_failure(job, &error) {
result.terminal_failures += 1;
}
result.jobs_failed += 1;
tracing::warn!(
target: "frankensearch.storage.pipeline",
stage = "persist",
worker_id,
correlation_id = %correlation_id,
doc_id = %job.doc_id,
embedder_id = %job.embedder_id,
error = %error,
"embedding persistence failed"
);
continue;
}
if let Err(error) = self.storage.mark_embedded(&job.doc_id, &job.embedder_id) {
if self.handle_job_failure(job, &error) {
result.terminal_failures += 1;
}
result.jobs_failed += 1;
tracing::warn!(
target: "frankensearch.storage.pipeline",
stage = "mark_embedded",
worker_id,
correlation_id = %correlation_id,
doc_id = %job.doc_id,
embedder_id = %job.embedder_id,
error = %error,
"failed to record embedded status"
);
continue;
}
if let Err(error) = self.queue.complete(job.job_id) {
if crate::job_queue::is_queue_conflict(&error) {
let skip_reason =
"embedding persisted after completion conflict; skipping reclaimed job";
match self.queue.skip(job.job_id, skip_reason) {
Ok(()) => {}
Err(skip_error) if crate::job_queue::is_queue_conflict(&skip_error) => {}
Err(skip_error) => return Err(skip_error),
}
result.jobs_skipped += 1;
tracing::warn!(
target: "frankensearch.storage.pipeline",
stage = "complete_conflict",
worker_id,
correlation_id = %correlation_id,
job_id = job.job_id,
doc_id = %job.doc_id,
embedder_id = %job.embedder_id,
error = %error,
"queue completion raced with lease reclaim; job left non-fatal"
);
continue;
}
return Err(error);
}
result.jobs_completed += 1;
tracing::info!(
target: "frankensearch.storage.pipeline",
stage = "complete",
event = "job_completed",
worker_id,
correlation_id = %correlation_id,
job_id = job.job_id,
doc_id = %job.doc_id,
embedder_id = %job.embedder_id,
duration_ms = duration_as_u64(job_started.elapsed().as_millis()),
"embedding job completed"
);
}
result.embed_time = embed_start.elapsed();
result.total_time = total_start.elapsed();
self.record_process_metrics(&result);
Ok(result)
}
#[allow(clippy::future_not_send)]
pub async fn run_worker(
&self,
cx: &Cx,
worker_id: &str,
shutdown: &AtomicBool,
) -> SearchResult<WorkerReport> {
ensure_non_empty(worker_id, "worker_id")?;
let reclaimed = self.queue.reclaim_stale_jobs()?;
self.metrics
.total_reclaimed
.fetch_add(usize_to_u64(reclaimed), Ordering::Relaxed);
if reclaimed > 0 {
tracing::warn!(
target: "frankensearch.storage.pipeline",
stage = "startup",
event = "crash_recovery",
worker_id,
recovered_job_count = reclaimed,
"reclaimed stale embedding jobs on worker startup"
);
}
let mut report = WorkerReport {
reclaimed_on_startup: reclaimed,
..WorkerReport::default()
};
let mut idle_cycles = 0_usize;
while !shutdown.load(Ordering::Relaxed) {
pipeline_checkpoint(cx, "storage.pipeline.run_worker")?;
let batch = self.process_batch(cx, worker_id).await?;
if batch.jobs_claimed == 0 {
idle_cycles += 1;
report.idle_cycles = idle_cycles;
if self
.config
.worker_max_idle_cycles
.is_some_and(|limit| idle_cycles >= limit)
{
break;
}
asupersync::time::sleep(
cx.now(),
Duration::from_millis(self.config.worker_idle_sleep_ms),
)
.await;
continue;
}
idle_cycles = 0;
report.batches_processed += 1;
report.jobs_completed += batch.jobs_completed;
report.jobs_failed += batch.jobs_failed;
report.jobs_skipped += batch.jobs_skipped;
report.terminal_failures_encountered += batch.terminal_failures;
}
tracing::info!(
target: "frankensearch.storage.pipeline",
stage = "worker_exit",
worker_id,
reclaimed_on_startup = report.reclaimed_on_startup,
batches_processed = report.batches_processed,
jobs_completed = report.jobs_completed,
jobs_failed = report.jobs_failed,
jobs_skipped = report.jobs_skipped,
terminal_failures_encountered = report.terminal_failures_encountered,
idle_cycles = report.idle_cycles,
"storage-backed embedding worker exited"
);
Ok(report)
}
fn embedder_for_id(&self, embedder_id: &str) -> SearchResult<Arc<dyn Embedder>> {
if self.fast_embedder.id() == embedder_id {
return Ok(Arc::clone(&self.fast_embedder));
}
if let Some(quality) = self.quality_embedder.as_ref()
&& quality.id() == embedder_id
{
return Ok(Arc::clone(quality));
}
Err(pipeline_error(format!(
"no embedder configured for queued embedder_id {embedder_id:?}"
)))
}
/// Handle a job failure by recording it in the queue and optionally
/// marking the document as failed in storage. Returns `true` if the
/// failure was terminal (no more retries).
fn handle_job_failure(&self, job: &crate::ClaimedJob, error: &SearchError) -> bool {
let error_message = error.to_string();
let fail_result = self.queue.fail(job.job_id, &error_message);
let is_terminal = match &fail_result {
Ok(crate::job_queue::FailResult::TerminalFailed { .. }) => true,
Ok(crate::job_queue::FailResult::Retried { .. }) => false,
Err(_) => true,
};
if let Err(fail_err) = fail_result {
tracing::warn!(
target: "frankensearch.storage.pipeline",
job_id = job.job_id,
error = %fail_err,
"failed to record job failure in queue"
);
}
if is_terminal {
if let Err(mark_err) =
self.storage
.mark_failed(&job.doc_id, &job.embedder_id, &error_message)
{
tracing::warn!(
target: "frankensearch.storage.pipeline",
doc_id = %job.doc_id,
error = %mark_err,
"failed to mark document as failed in storage"
);
}
}
is_terminal
}
fn record_ingest_metrics(&self, tx_result: &IngestTxResult) {
match tx_result.action {
IngestAction::New => {
self.metrics
.total_ingest_inserted
.fetch_add(1, Ordering::Relaxed);
}
IngestAction::Updated => {
self.metrics
.total_ingest_updated
.fetch_add(1, Ordering::Relaxed);
}
IngestAction::Unchanged => {
self.metrics
.total_ingest_unchanged
.fetch_add(1, Ordering::Relaxed);
}
IngestAction::Skipped { .. } => {
self.metrics
.total_ingest_skipped
.fetch_add(1, Ordering::Relaxed);
}
}
}
fn record_process_metrics(&self, result: &BatchProcessResult) {
self.metrics
.total_jobs_completed
.fetch_add(usize_to_u64(result.jobs_completed), Ordering::Relaxed);
self.metrics
.total_jobs_failed
.fetch_add(usize_to_u64(result.jobs_failed), Ordering::Relaxed);
self.metrics
.total_jobs_skipped
.fetch_add(usize_to_u64(result.jobs_skipped), Ordering::Relaxed);
let embed_time_us = duration_as_u64(result.embed_time.as_micros());
self.metrics
.total_embed_time_us
.fetch_add(embed_time_us, Ordering::Relaxed);