1use crate::auth_catalog::AuthCatalog;
17use crate::backfill::plan::{
18 BackfillUnit, WARN_UNITS, plan_windows, range_hash, substitute_unit_tokens,
19};
20use crate::backfill::spec::has_scoping_tokens;
21use crate::backfill::state::{
22 BackfillState, marker_key, split_remaining, unit_row_id, unit_state_key,
23};
24use crate::config::{ExecutionSpec, PipelineConfig};
25use crate::error::{CliError, CliResult};
26use crate::executor::{ExecuteOptions, run_expanded};
27use crate::expand::{ExpandedNode, expand};
28use chrono::{DateTime, Duration, FixedOffset};
29use faucet_core::{FaucetError, StateStore, Stream, StreamPage, json_gt};
30use serde::Serialize;
31use serde_json::Value;
32use std::pin::Pin;
33use std::sync::Arc;
34use tokio_util::sync::CancellationToken;
35
36#[derive(Debug, Clone)]
38pub enum BackfillRange {
39 Time {
41 from: DateTime<FixedOffset>,
42 to: DateTime<FixedOffset>,
43 window: Option<Duration>,
44 tz: chrono_tz::Tz,
45 },
46 Bookmark {
50 from: Value,
51 to: Option<Value>,
52 field: Option<String>,
53 },
54}
55
56impl BackfillRange {
57 fn descriptor(&self, row: &str) -> String {
60 match self {
61 Self::Time {
62 from, to, window, ..
63 } => format!(
64 "time|{}|{}|{}|{row}",
65 from.to_rfc3339(),
66 to.to_rfc3339(),
67 window
68 .map(|w| w.num_seconds().to_string())
69 .unwrap_or_else(|| "whole".into()),
70 ),
71 Self::Bookmark { from, to, .. } => format!(
72 "bookmark|{from}|{}|{row}",
73 to.as_ref().map(Value::to_string).unwrap_or_default()
74 ),
75 }
76 }
77}
78
79pub struct BackfillOptions {
81 pub pipeline_name: String,
82 pub execution: Option<ExecutionSpec>,
83 pub auth: AuthCatalog,
84 pub resilience: Option<faucet_core::ResiliencePolicy>,
85 pub range: BackfillRange,
86 pub concurrency: usize,
88 pub row: Option<String>,
90 pub into_sink: Option<String>,
92 pub dry_run: bool,
94 pub resume: bool,
96 pub restart: bool,
98 pub cancel: Option<CancellationToken>,
100}
101
102#[derive(Debug, Clone, Serialize, PartialEq)]
104pub struct UnitReport {
105 pub unit: String,
106 pub start: String,
107 pub end: String,
108 pub outcome: String,
110 #[serde(skip_serializing_if = "Option::is_none")]
111 pub error: Option<String>,
112}
113
114#[derive(Debug, Clone, Serialize, PartialEq)]
116pub struct BackfillOutcome {
117 pub descriptor: String,
118 pub planned: usize,
119 pub skipped: usize,
120 pub succeeded: usize,
121 pub failed: usize,
122 pub dry_run: bool,
123 pub units: Vec<UnitReport>,
124}
125
126fn select_root(nodes: Vec<ExpandedNode>, row: Option<&str>) -> CliResult<ExpandedNode> {
128 let roots: Vec<ExpandedNode> = nodes
129 .into_iter()
130 .filter(|n| matches!(n.role, crate::expand::NodeRole::Root))
131 .collect();
132 match row {
133 Some(id) => {
134 let available: Vec<String> = roots.iter().map(|n| n.id.clone()).collect();
135 roots.into_iter().find(|n| n.id == id).ok_or_else(|| {
136 CliError::Config(format!(
137 "no root row named '{id}' — available: {}",
138 available.join(", ")
139 ))
140 })
141 }
142 None => {
143 if roots.len() > 1 {
144 return Err(CliError::Config(format!(
145 "the config has {} root rows — pick one with --row ({})",
146 roots.len(),
147 roots
148 .iter()
149 .map(|n| n.id.as_str())
150 .collect::<Vec<_>>()
151 .join(", ")
152 )));
153 }
154 roots
155 .into_iter()
156 .next()
157 .ok_or_else(|| CliError::Config("the config has no root rows".into()))
158 }
159 }
160}
161
162fn build_unit_node(
166 root: &ExpandedNode,
167 unit: &BackfillUnit,
168 time_mode: bool,
169) -> CliResult<ExpandedNode> {
170 let mut n = root.clone();
171 n.id = unit_row_id(&unit.id);
172 if time_mode {
173 substitute_unit_tokens(&mut n.source.config, unit)?;
174 substitute_unit_tokens(&mut n.sink.config, unit)?;
175 }
176 n.delivery = faucet_core::DeliveryMode::AtLeastOnce;
177 if n.delivery_guarantee
178 != faucet_core::DeliveryGuarantee::EffectivelyOnce(
179 faucet_core::EffectivelyOnceMechanism::KeyedUpsert,
180 )
181 {
182 n.delivery_guarantee = faucet_core::DeliveryGuarantee::AtLeastOnce;
183 }
184 Ok(n)
185}
186
187fn sink_dedups(node: &ExpandedNode) -> bool {
189 matches!(
190 node.sink.config.get("write_mode").and_then(Value::as_str),
191 Some("upsert") | Some("delete")
192 )
193}
194
195struct BoundedSource {
199 inner: Box<dyn faucet_core::Source>,
200 field: String,
201 to: Value,
202}
203
204impl BoundedSource {
205 fn within_bound(&self, record: &Value) -> bool {
206 match record.get(&self.field) {
207 Some(v) => !json_gt(v, &self.to),
208 None => true,
209 }
210 }
211}
212
213#[faucet_core::async_trait]
214impl faucet_core::Source for BoundedSource {
215 async fn fetch_with_context(
216 &self,
217 context: &std::collections::HashMap<String, Value>,
218 ) -> Result<Vec<Value>, FaucetError> {
219 let records = self.inner.fetch_with_context(context).await?;
220 Ok(records
221 .into_iter()
222 .filter(|r| self.within_bound(r))
223 .collect())
224 }
225
226 async fn fetch_with_context_incremental(
227 &self,
228 context: &std::collections::HashMap<String, Value>,
229 ) -> Result<(Vec<Value>, Option<Value>), FaucetError> {
230 let (records, bookmark) = self.inner.fetch_with_context_incremental(context).await?;
231 Ok((
232 records
233 .into_iter()
234 .filter(|r| self.within_bound(r))
235 .collect(),
236 bookmark,
237 ))
238 }
239
240 fn stream_pages<'a>(
241 &'a self,
242 context: &'a std::collections::HashMap<String, Value>,
243 batch_size: usize,
244 ) -> Pin<Box<dyn Stream<Item = Result<StreamPage, FaucetError>> + Send + 'a>> {
245 use futures::StreamExt;
246 let inner = self.inner.stream_pages(context, batch_size);
247 Box::pin(inner.map(move |page| {
248 page.map(|p| StreamPage {
249 records: p
250 .records
251 .into_iter()
252 .filter(|r| self.within_bound(r))
253 .collect(),
254 bookmark: p.bookmark,
255 })
256 }))
257 }
258
259 fn state_key(&self) -> Option<String> {
260 self.inner.state_key()
261 }
262
263 async fn apply_start_bookmark(&self, bookmark: Value) -> Result<(), FaucetError> {
264 self.inner.apply_start_bookmark(bookmark).await
265 }
266
267 fn config_schema(&self) -> Value {
268 self.inner.config_schema()
269 }
270
271 fn connector_name(&self) -> &'static str {
272 self.inner.connector_name()
273 }
274
275 fn dataset_uri(&self) -> String {
276 self.inner.dataset_uri()
277 }
278}
279
280fn make_opts(
282 opts: &BackfillOptions,
283 clock: DateTime<FixedOffset>,
284 cancel: CancellationToken,
285) -> ExecuteOptions {
286 ExecuteOptions {
287 pipeline_name: opts.pipeline_name.clone(),
288 execution: opts.execution.clone(),
289 dry_run: false,
290 limit: None,
291 state_path_override: None,
292 shard: None,
293 auth: opts.auth.clone(),
294 clock,
295 cancel: Some(cancel),
296 resilience: opts.resilience.clone(),
297 sla: None,
300 #[cfg(feature = "lineage")]
301 lineage: None,
302 #[cfg(feature = "lineage")]
303 lineage_cfg: None,
304 #[cfg(feature = "notify")]
305 notifier: None,
306 #[cfg(feature = "catalog")]
307 catalog: None,
308 }
309}
310
311pub async fn run_backfill(
315 cfg: &PipelineConfig,
316 opts: BackfillOptions,
317) -> CliResult<BackfillOutcome> {
318 let nodes = expand(cfg)?;
319 let root = select_root(nodes, opts.row.as_deref())?;
320 let mut root = root;
321
322 if let Some(name) = &opts.into_sink {
324 let spec = cfg.pipeline.sinks.get(name).ok_or_else(|| {
325 let mut available: Vec<&str> = cfg.pipeline.sinks.keys().map(String::as_str).collect();
326 available.sort_unstable();
327 CliError::Config(format!(
328 "--into '{name}' does not name a sink template under pipeline.sinks — \
329 available: {}",
330 if available.is_empty() {
331 "none".to_string()
332 } else {
333 available.join(", ")
334 }
335 ))
336 })?;
337 root.sink = spec.clone();
338 root.sink_ref = name.clone();
339 }
340
341 let time_mode = matches!(opts.range, BackfillRange::Time { .. });
342
343 if time_mode {
345 let serialized = root.source.config.to_string();
346 if !has_scoping_tokens(&serialized) {
347 return Err(CliError::Config(format!(
348 "source '{}' is not scoped to the backfill window — its config references \
349 no `${{backfill.start}}` / `${{backfill.end}}` / `${{now.*}}` token, so every \
350 window would replay identical data. Add a window predicate (e.g. \
351 `query: … WHERE updated_at >= '${{backfill.start}}' AND updated_at < \
352 '${{backfill.end}}'`), or use --from-bookmark for bookmark-positioned \
353 sources",
354 root.source.kind
355 )));
356 }
357 } else if root.state.is_none() {
358 return Err(CliError::Config(
359 "--from-bookmark requires a `state:` block — the bookmark is seeded into the \
360 backfill's scoped state key"
361 .into(),
362 ));
363 }
364 if let BackfillRange::Bookmark {
365 to: Some(_), field, ..
366 } = &opts.range
367 && field.is_none()
368 {
369 return Err(CliError::Config(
370 "--to-bookmark requires --bookmark-field naming the record field the bound \
371 applies to"
372 .into(),
373 ));
374 }
375 if !sink_dedups(&root) {
376 tracing::warn!(
377 sink = %root.sink.kind,
378 "backfill sink is append-only — replaying an overlapping window will duplicate \
379 rows. Recommended: `write_mode: upsert` with a `key` (or --into a staging sink)"
380 );
381 }
382
383 let units = match &opts.range {
385 BackfillRange::Time {
386 from,
387 to,
388 window,
389 tz,
390 } => plan_windows(*from, *to, *window, *tz)?,
391 BackfillRange::Bookmark { .. } => vec![BackfillUnit {
392 id: "bookmark".into(),
393 start: chrono::Utc::now().fixed_offset(),
394 end: chrono::Utc::now().fixed_offset(),
395 }],
396 };
397 if units.len() > WARN_UNITS {
398 tracing::warn!(
399 units = units.len(),
400 "large backfill plan — consider a bigger --window"
401 );
402 }
403 let descriptor = opts.range.descriptor(&root.id);
404 let marker_k = marker_key(&opts.pipeline_name, &range_hash(&descriptor));
405
406 let store: Arc<dyn StateStore> = match cfg.pipeline.state.as_ref() {
408 Some(spec) => crate::state::build_state_store(spec).await?,
409 None => {
410 tracing::warn!(
411 "no `state:` block — backfill progress is not durable and --resume will \
412 not survive a restart"
413 );
414 Arc::new(faucet_core::MemoryStateStore::new())
415 }
416 };
417 let marker = match store.get(&marker_k).await? {
418 Some(v) if opts.restart => {
419 let prior = BackfillState::from_value(v)?;
420 tracing::warn!(
421 done = prior.done_count(),
422 failed = prior.failed_count(),
423 "--restart: discarding the previous progress marker for this range"
424 );
425 BackfillState::new(descriptor.clone())
426 }
427 Some(v) => {
428 let prior = BackfillState::from_value(v)?;
429 if !opts.resume && !opts.dry_run {
430 return Err(CliError::Config(format!(
431 "a previous backfill of this range exists ({} done, {} failed of {} \
432 planned) — pass --resume to continue it or --restart to start over",
433 prior.done_count(),
434 prior.failed_count(),
435 units.len()
436 )));
437 }
438 prior
439 }
440 None => BackfillState::new(descriptor.clone()),
441 };
442
443 let planned = units.len();
444 let (todo, skipped) = split_remaining(units.clone(), &marker);
445 for _ in 0..skipped {
446 super::metrics::record_unit(&opts.pipeline_name, "skipped");
447 }
448
449 if opts.dry_run {
451 let reports = units
452 .iter()
453 .map(|u| UnitReport {
454 unit: u.id.clone(),
455 start: u.start.to_rfc3339(),
456 end: u.end.to_rfc3339(),
457 outcome: if marker.is_done(&u.id) {
458 "skipped".into()
459 } else {
460 "pending".into()
461 },
462 error: None,
463 })
464 .collect();
465 return Ok(BackfillOutcome {
466 descriptor,
467 planned,
468 skipped,
469 succeeded: 0,
470 failed: 0,
471 dry_run: true,
472 units: reports,
473 });
474 }
475
476 let cancel = match &opts.cancel {
478 Some(token) => token.clone(),
479 None => {
480 let token = CancellationToken::new();
481 crate::replication::orchestrator::spawn_cancel_on_signal(token.clone());
482 token
483 }
484 };
485 if opts.restart {
493 clear_scoped_unit_state(&store, &opts.pipeline_name, &units).await?;
494 }
495
496 store.put(&marker_k, &marker.to_value()?).await?;
499
500 let semaphore = Arc::new(tokio::sync::Semaphore::new(opts.concurrency.max(1)));
501 let marker_lock = Arc::new(tokio::sync::Mutex::new(marker));
502 let mut join = tokio::task::JoinSet::new();
503 let opts = Arc::new(opts);
504 let root = Arc::new(root);
505 let total_todo = todo.len();
506 let mut reports: Vec<UnitReport> = Vec::with_capacity(total_todo);
507
508 for unit in todo {
509 let permit = semaphore
510 .clone()
511 .acquire_owned()
512 .await
513 .map_err(|e| CliError::Internal(format!("backfill semaphore closed: {e}")))?;
514 if cancel.is_cancelled() {
515 drop(permit);
516 break;
517 }
518 let opts = opts.clone();
519 let root = root.clone();
520 let cfg_range = opts.range.clone();
521 let store = store.clone();
522 let cancel = cancel.clone();
523 join.spawn(async move {
524 let _permit = permit;
525 let result = run_one_unit(&root, &unit, &cfg_range, &opts, &store, cancel).await;
526 (unit, result)
527 });
528 }
529
530 let mut succeeded = 0usize;
531 let mut failed = 0usize;
532 while let Some(joined) = join.join_next().await {
533 let (unit, result) =
534 joined.map_err(|e| CliError::Internal(format!("backfill unit task panicked: {e}")))?;
535 let (outcome, error) = match result {
536 Ok(()) => {
537 succeeded += 1;
538 super::metrics::record_unit(&opts.pipeline_name, "ok");
539 ("done".to_string(), None)
540 }
541 Err(e) => {
542 failed += 1;
543 super::metrics::record_unit(&opts.pipeline_name, "err");
544 ("failed".to_string(), Some(e.to_string()))
545 }
546 };
547 {
550 let mut m = marker_lock.lock().await;
551 match &error {
552 None => m.mark_done(&unit.id),
553 Some(e) => m.mark_failed(&unit.id, e.clone()),
554 }
555 store.put(&marker_k, &m.to_value()?).await?;
556 super::metrics::set_progress(&opts.pipeline_name, m.done_count(), planned);
557 tracing::info!(
558 unit = %unit.id,
559 outcome = %outcome,
560 done = m.done_count(),
561 failed = m.failed_count(),
562 planned,
563 "backfill unit finished"
564 );
565 }
566 reports.push(UnitReport {
567 unit: unit.id.clone(),
568 start: unit.start.to_rfc3339(),
569 end: unit.end.to_rfc3339(),
570 outcome,
571 error,
572 });
573 }
574
575 reports.sort_by(|a, b| a.unit.cmp(&b.unit));
576 Ok(BackfillOutcome {
577 descriptor,
578 planned,
579 skipped,
580 succeeded,
581 failed,
582 dry_run: false,
583 units: reports,
584 })
585}
586
587async fn clear_scoped_unit_state(
591 store: &Arc<dyn StateStore>,
592 pipeline_name: &str,
593 units: &[BackfillUnit],
594) -> CliResult<()> {
595 for unit in units {
596 store
597 .delete(&unit_state_key(pipeline_name, &unit.id))
598 .await?;
599 }
600 Ok(())
601}
602
603async fn run_one_unit(
605 root: &ExpandedNode,
606 unit: &BackfillUnit,
607 range: &BackfillRange,
608 opts: &BackfillOptions,
609 store: &Arc<dyn StateStore>,
610 cancel: CancellationToken,
611) -> CliResult<()> {
612 let time_mode = matches!(range, BackfillRange::Time { .. });
613 let mut node = build_unit_node(root, unit, time_mode)?;
614
615 if let BackfillRange::Bookmark { from, to, field } = range {
616 let key = unit_state_key(&opts.pipeline_name, &unit.id);
619 if store.get(&key).await?.is_none() {
620 store.put(&key, from).await?;
621 }
622 if let (Some(to), Some(field)) = (to, field) {
625 let mut source_cfg = node.source.config.clone();
626 crate::executor::resolve_now_inplace(&mut source_cfg, unit.start)?;
627 let inner = crate::registry::build_source(
628 &node.source.kind,
629 source_cfg,
630 &opts.auth,
631 opts.resilience.as_ref().map(|r| &r.retry),
632 )
633 .await?;
634 node.source_override = Some(crate::dlq_replay::reader::SourceOverride::new(Box::new(
635 BoundedSource {
636 inner,
637 field: field.clone(),
638 to: to.clone(),
639 },
640 )));
641 }
642 }
643
644 let summary = run_expanded(vec![node], make_opts(opts, unit.start, cancel.clone())).await?;
645 if summary.had_failures() {
646 let detail = summary
647 .invocations
648 .iter()
649 .find_map(|i| i.error.clone())
650 .unwrap_or_else(|| "unknown error".to_string());
651 return Err(CliError::Internal(format!(
652 "unit {} failed: {detail}",
653 unit.id
654 )));
655 }
656 if cancel.is_cancelled() {
657 return Err(CliError::Internal(format!(
660 "unit {} interrupted by shutdown before completion",
661 unit.id
662 )));
663 }
664 Ok(())
665}
666
667#[cfg(test)]
668mod tests {
669 use super::*;
670 use serde_json::json;
671
672 fn parse_cfg(yaml: &str) -> PipelineConfig {
673 crate::config::parse_with_extension(yaml, "yaml").unwrap()
674 }
675
676 const SCOPED: &str = r#"
677version: 1
678name: orders
679pipeline:
680 source:
681 type: rest
682 config: { url: "https://api.example.com/orders?since=${backfill.start}&until=${backfill.end}" }
683 sink:
684 type: jsonl
685 config: { path: ./out.jsonl }
686"#;
687
688 fn time_range(from: &str, to: &str, window: Option<chrono::Duration>) -> BackfillRange {
689 let tz: chrono_tz::Tz = "UTC".parse().unwrap();
690 BackfillRange::Time {
691 from: crate::backfill::plan::parse_boundary(from, tz).unwrap(),
692 to: crate::backfill::plan::parse_boundary(to, tz).unwrap(),
693 window,
694 tz,
695 }
696 }
697
698 fn base_opts(range: BackfillRange) -> BackfillOptions {
699 BackfillOptions {
700 pipeline_name: "orders".into(),
701 execution: None,
702 auth: crate::auth_catalog::AuthCatalog::default(),
703 resilience: None,
704 range,
705 concurrency: 2,
706 row: None,
707 into_sink: None,
708 dry_run: true,
709 resume: false,
710 restart: false,
711 cancel: None,
712 }
713 }
714
715 #[tokio::test]
716 async fn dry_run_plans_31_units_without_running() {
717 let cfg = parse_cfg(SCOPED);
718 let opts = base_opts(time_range(
719 "2026-06-01",
720 "2026-07-02",
721 Some(chrono::Duration::days(1)),
722 ));
723 let out = run_backfill(&cfg, opts).await.unwrap();
724 assert!(out.dry_run);
725 assert_eq!(out.planned, 31);
726 assert_eq!(out.units.len(), 31);
727 assert!(out.units.iter().all(|u| u.outcome == "pending"));
728 assert_eq!(out.succeeded + out.failed, 0);
729 }
730
731 #[tokio::test]
732 async fn unscoped_source_rejected_with_actionable_error() {
733 let cfg = parse_cfg(
734 r#"
735version: 1
736name: orders
737pipeline:
738 source: { type: rest, config: { url: "https://api.example.com/orders" } }
739 sink: { type: jsonl, config: { path: ./out.jsonl } }
740"#,
741 );
742 let opts = base_opts(time_range("2026-06-01", "2026-06-02", None));
743 let err = run_backfill(&cfg, opts).await.unwrap_err();
744 let msg = err.to_string();
745 assert!(msg.contains("${backfill.start}"), "actionable: {msg}");
746 assert!(
747 msg.contains("--from-bookmark"),
748 "suggests alternative: {msg}"
749 );
750 }
751
752 #[tokio::test]
753 async fn bookmark_mode_requires_state_block() {
754 let cfg = parse_cfg(SCOPED);
755 let opts = base_opts(BackfillRange::Bookmark {
756 from: json!("2026-01-01"),
757 to: None,
758 field: None,
759 });
760 let err = run_backfill(&cfg, opts).await.unwrap_err();
761 assert!(err.to_string().contains("state"), "{err}");
762 }
763
764 #[tokio::test]
765 async fn to_bookmark_requires_field() {
766 let cfg = parse_cfg(&format!(
767 "{SCOPED} state: {{ type: memory, config: {{}} }}\n"
768 ));
769 let opts = base_opts(BackfillRange::Bookmark {
770 from: json!(1),
771 to: Some(json!(9)),
772 field: None,
773 });
774 let err = run_backfill(&cfg, opts).await.unwrap_err();
775 assert!(err.to_string().contains("--bookmark-field"), "{err}");
776 }
777
778 #[tokio::test]
779 async fn into_unknown_sink_lists_available() {
780 let cfg = parse_cfg(
781 r#"
782version: 1
783name: orders
784pipeline:
785 sources:
786 default:
787 type: rest
788 config: { url: "https://api.example.com/x?s=${backfill.start}" }
789 sinks:
790 default: { type: jsonl, config: { path: ./out.jsonl } }
791 staging: { type: jsonl, config: { path: ./staging.jsonl } }
792"#,
793 );
794 let mut opts = base_opts(time_range("2026-06-01", "2026-06-02", None));
795 opts.into_sink = Some("nope".into());
796 let err = run_backfill(&cfg, opts).await.unwrap_err();
797 let msg = err.to_string();
798 assert!(msg.contains("staging"), "lists templates: {msg}");
799 }
800
801 #[tokio::test]
802 async fn multiple_roots_require_row_selection() {
803 let cfg = parse_cfg(
804 r#"
805version: 1
806name: orders
807pipeline:
808 source:
809 type: rest
810 config: { url: "https://api.example.com/x?s=${backfill.start}" }
811 sink: { type: jsonl, config: { path: ./out.jsonl } }
812matrix:
813 - id: a
814 - id: b
815"#,
816 );
817 let opts = base_opts(time_range("2026-06-01", "2026-06-02", None));
818 let err = run_backfill(&cfg, opts).await.unwrap_err();
819 assert!(err.to_string().contains("--row"), "{err}");
820
821 let mut opts = base_opts(time_range("2026-06-01", "2026-06-02", None));
822 opts.row = Some("b".into());
823 let out = run_backfill(&cfg, opts).await.unwrap();
824 assert_eq!(out.planned, 1);
825
826 let mut opts = base_opts(time_range("2026-06-01", "2026-06-02", None));
827 opts.row = Some("zzz".into());
828 let err = run_backfill(&cfg, opts).await.unwrap_err();
829 assert!(err.to_string().contains("available: a, b"), "{err}");
830 }
831
832 #[test]
833 fn unit_node_is_namespaced_and_at_least_once() {
834 let cfg = parse_cfg(SCOPED);
835 let root = select_root(expand(&cfg).unwrap(), None).unwrap();
836 let tz: chrono_tz::Tz = "UTC".parse().unwrap();
837 let unit = BackfillUnit {
838 id: "20260601T000000Z".into(),
839 start: crate::backfill::plan::parse_boundary("2026-06-01", tz).unwrap(),
840 end: crate::backfill::plan::parse_boundary("2026-06-02", tz).unwrap(),
841 };
842 let node = build_unit_node(&root, &unit, true).unwrap();
843 assert_eq!(node.id, "backfill::20260601T000000Z");
844 assert_eq!(node.delivery, faucet_core::DeliveryMode::AtLeastOnce);
845 let url = node.source.config["url"].as_str().unwrap();
846 assert!(url.contains("since=2026-06-01T00:00:00+00:00"), "{url}");
847 assert!(url.contains("until=2026-06-02T00:00:00+00:00"), "{url}");
848 }
849
850 #[tokio::test]
851 async fn restart_clears_scoped_unit_state() {
852 let store: Arc<dyn StateStore> = Arc::new(faucet_core::MemoryStateStore::new());
856 let key = unit_state_key("orders", "bookmark");
857 store.put(&key, &json!(500)).await.unwrap();
858
859 let tz: chrono_tz::Tz = "UTC".parse().unwrap();
860 let unit = BackfillUnit {
861 id: "bookmark".into(),
862 start: crate::backfill::plan::parse_boundary("2026-06-01", tz).unwrap(),
863 end: crate::backfill::plan::parse_boundary("2026-06-02", tz).unwrap(),
864 };
865 clear_scoped_unit_state(&store, "orders", std::slice::from_ref(&unit))
866 .await
867 .unwrap();
868 assert_eq!(
869 store.get(&key).await.unwrap(),
870 None,
871 "restart must delete the surviving scoped bookmark"
872 );
873 }
874
875 #[test]
876 fn descriptor_distinguishes_ranges_and_rows() {
877 let r1 = time_range("2026-06-01", "2026-07-01", None).descriptor("a");
878 let r2 = time_range("2026-06-01", "2026-07-01", None).descriptor("b");
879 let r3 = time_range("2026-06-01", "2026-07-02", None).descriptor("a");
880 assert_ne!(r1, r2);
881 assert_ne!(r1, r3);
882 let b = BackfillRange::Bookmark {
883 from: json!(5),
884 to: Some(json!(9)),
885 field: Some("id".into()),
886 }
887 .descriptor("a");
888 assert!(b.starts_with("bookmark|"), "{b}");
889 }
890
891 struct FixtureSource(Vec<Value>);
894
895 #[faucet_core::async_trait]
896 impl faucet_core::Source for FixtureSource {
897 async fn fetch_with_context(
898 &self,
899 _c: &std::collections::HashMap<String, Value>,
900 ) -> Result<Vec<Value>, FaucetError> {
901 Ok(self.0.clone())
902 }
903 }
904
905 #[tokio::test]
906 async fn bounded_source_drops_records_past_the_bound() {
907 use faucet_core::Source as _;
908 use futures::StreamExt;
909 let inner = FixtureSource(vec![
910 json!({"id": 1, "ts": "2026-06-01"}),
911 json!({"id": 2, "ts": "2026-06-15"}),
912 json!({"id": 3, "ts": "2026-07-05"}),
913 json!({"id": 4}), ]);
915 let bounded = BoundedSource {
916 inner: Box::new(inner),
917 field: "ts".into(),
918 to: json!("2026-06-30"),
919 };
920 let ctx = std::collections::HashMap::new();
921 let records = bounded.fetch_with_context(&ctx).await.unwrap();
922 let ids: Vec<i64> = records.iter().map(|r| r["id"].as_i64().unwrap()).collect();
923 assert_eq!(ids, vec![1, 2, 4], "record past the bound dropped");
924
925 let mut pages = bounded.stream_pages(&ctx, 10);
926 let page = pages.next().await.unwrap().unwrap();
927 assert_eq!(page.records.len(), 3);
928 }
929}