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, 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<crate::backfill::plan::WindowStep>,
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.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 run_id: None,
289 execution: opts.execution.clone(),
290 dry_run: false,
291 limit: None,
292 state_path_override: None,
293 shard: None,
294 auth: opts.auth.clone(),
295 clock,
296 cancel: Some(cancel),
297 resilience: opts.resilience.clone(),
298 sla: None,
301 #[cfg(feature = "lineage")]
302 lineage: None,
303 #[cfg(feature = "lineage")]
304 lineage_cfg: None,
305 #[cfg(feature = "notify")]
306 notifier: None,
307 #[cfg(feature = "catalog")]
308 catalog: None,
309 }
310}
311
312pub async fn run_backfill(
316 cfg: &PipelineConfig,
317 opts: BackfillOptions,
318) -> CliResult<BackfillOutcome> {
319 let nodes = expand(cfg)?;
320 let root = select_root(nodes, opts.row.as_deref())?;
321 let mut root = root;
322
323 if let Some(name) = &opts.into_sink {
325 let spec = cfg.pipeline.sinks.get(name).ok_or_else(|| {
326 let mut available: Vec<&str> = cfg.pipeline.sinks.keys().map(String::as_str).collect();
327 available.sort_unstable();
328 CliError::Config(format!(
329 "--into '{name}' does not name a sink template under pipeline.sinks — \
330 available: {}",
331 if available.is_empty() {
332 "none".to_string()
333 } else {
334 available.join(", ")
335 }
336 ))
337 })?;
338 root.sink = spec.clone();
339 root.sink_ref = name.clone();
340 }
341
342 let time_mode = matches!(opts.range, BackfillRange::Time { .. });
343
344 if time_mode {
346 let serialized = root.source.config.to_string();
347 if !has_scoping_tokens(&serialized) {
348 return Err(CliError::Config(format!(
349 "source '{}' is not scoped to the backfill window — its config references \
350 no `${{backfill.start}}` / `${{backfill.end}}` / `${{now.*}}` token, so every \
351 window would replay identical data. Add a window predicate (e.g. \
352 `query: … WHERE updated_at >= '${{backfill.start}}' AND updated_at < \
353 '${{backfill.end}}'`), or use --from-bookmark for bookmark-positioned \
354 sources",
355 root.source.kind
356 )));
357 }
358 } else if root.state.is_none() {
359 return Err(CliError::Config(
360 "--from-bookmark requires a `state:` block — the bookmark is seeded into the \
361 backfill's scoped state key"
362 .into(),
363 ));
364 }
365 if let BackfillRange::Bookmark {
366 to: Some(_), field, ..
367 } = &opts.range
368 && field.is_none()
369 {
370 return Err(CliError::Config(
371 "--to-bookmark requires --bookmark-field naming the record field the bound \
372 applies to"
373 .into(),
374 ));
375 }
376 if !sink_dedups(&root) {
377 tracing::warn!(
378 sink = %root.sink.kind,
379 "backfill sink is append-only — replaying an overlapping window will duplicate \
380 rows. Recommended: `write_mode: upsert` with a `key` (or --into a staging sink)"
381 );
382 }
383
384 let units = match &opts.range {
386 BackfillRange::Time {
387 from,
388 to,
389 window,
390 tz,
391 } => plan_windows(*from, *to, *window, *tz)?,
392 BackfillRange::Bookmark { .. } => vec![BackfillUnit {
393 id: "bookmark".into(),
394 start: chrono::Utc::now().fixed_offset(),
395 end: chrono::Utc::now().fixed_offset(),
396 }],
397 };
398 if units.len() > WARN_UNITS {
399 tracing::warn!(
400 units = units.len(),
401 "large backfill plan — consider a bigger --window"
402 );
403 }
404 let descriptor = opts.range.descriptor(&root.id);
405 let marker_k = marker_key(&opts.pipeline_name, &range_hash(&descriptor));
406
407 let store: Arc<dyn StateStore> = match cfg.pipeline.state.as_ref() {
409 Some(spec) => crate::state::build_state_store(spec).await?,
410 None => {
411 tracing::warn!(
412 "no `state:` block — backfill progress is not durable and --resume will \
413 not survive a restart"
414 );
415 Arc::new(faucet_core::MemoryStateStore::new())
416 }
417 };
418 let marker = match store.get(&marker_k).await? {
419 Some(v) if opts.restart => {
420 let prior = BackfillState::from_value(v)?;
421 tracing::warn!(
422 done = prior.done_count(),
423 failed = prior.failed_count(),
424 "--restart: discarding the previous progress marker for this range"
425 );
426 BackfillState::new(descriptor.clone())
427 }
428 Some(v) => {
429 let prior = BackfillState::from_value(v)?;
430 if !opts.resume && !opts.dry_run {
431 return Err(CliError::Config(format!(
432 "a previous backfill of this range exists ({} done, {} failed of {} \
433 planned) — pass --resume to continue it or --restart to start over",
434 prior.done_count(),
435 prior.failed_count(),
436 units.len()
437 )));
438 }
439 prior
440 }
441 None => BackfillState::new(descriptor.clone()),
442 };
443
444 let planned = units.len();
445 let (todo, skipped) = split_remaining(units.clone(), &marker);
446 for _ in 0..skipped {
447 super::metrics::record_unit(&opts.pipeline_name, "skipped");
448 }
449
450 if opts.dry_run {
452 let reports = units
453 .iter()
454 .map(|u| UnitReport {
455 unit: u.id.clone(),
456 start: u.start.to_rfc3339(),
457 end: u.end.to_rfc3339(),
458 outcome: if marker.is_done(&u.id) {
459 "skipped".into()
460 } else {
461 "pending".into()
462 },
463 error: None,
464 })
465 .collect();
466 return Ok(BackfillOutcome {
467 descriptor,
468 planned,
469 skipped,
470 succeeded: 0,
471 failed: 0,
472 dry_run: true,
473 units: reports,
474 });
475 }
476
477 let cancel = match &opts.cancel {
479 Some(token) => token.clone(),
480 None => {
481 let token = CancellationToken::new();
482 crate::replication::orchestrator::spawn_cancel_on_signal(token.clone());
483 token
484 }
485 };
486 if opts.restart {
494 clear_scoped_unit_state(&store, &opts.pipeline_name, &units).await?;
495 }
496
497 store.put(&marker_k, &marker.to_value()?).await?;
500
501 let semaphore = Arc::new(tokio::sync::Semaphore::new(opts.concurrency.max(1)));
502 let marker_lock = Arc::new(tokio::sync::Mutex::new(marker));
503 let mut join = tokio::task::JoinSet::new();
504 let opts = Arc::new(opts);
505 let root = Arc::new(root);
506 let total_todo = todo.len();
507 let mut reports: Vec<UnitReport> = Vec::with_capacity(total_todo);
508
509 for unit in todo {
510 let permit = semaphore
511 .clone()
512 .acquire_owned()
513 .await
514 .map_err(|e| CliError::Internal(format!("backfill semaphore closed: {e}")))?;
515 if cancel.is_cancelled() {
516 drop(permit);
517 break;
518 }
519 let opts = opts.clone();
520 let root = root.clone();
521 let cfg_range = opts.range.clone();
522 let store = store.clone();
523 let cancel = cancel.clone();
524 join.spawn(async move {
525 let _permit = permit;
526 let result = run_one_unit(&root, &unit, &cfg_range, &opts, &store, cancel).await;
527 (unit, result)
528 });
529 }
530
531 let mut succeeded = 0usize;
532 let mut failed = 0usize;
533 while let Some(joined) = join.join_next().await {
534 let (unit, result) =
535 joined.map_err(|e| CliError::Internal(format!("backfill unit task panicked: {e}")))?;
536 let (outcome, error) = match result {
537 Ok(()) => {
538 succeeded += 1;
539 super::metrics::record_unit(&opts.pipeline_name, "ok");
540 ("done".to_string(), None)
541 }
542 Err(e) => {
543 failed += 1;
544 super::metrics::record_unit(&opts.pipeline_name, "err");
545 ("failed".to_string(), Some(e.to_string()))
546 }
547 };
548 {
551 let mut m = marker_lock.lock().await;
552 match &error {
553 None => m.mark_done(&unit.id),
554 Some(e) => m.mark_failed(&unit.id, e.clone()),
555 }
556 store.put(&marker_k, &m.to_value()?).await?;
557 super::metrics::set_progress(&opts.pipeline_name, m.done_count(), planned);
558 tracing::info!(
559 unit = %unit.id,
560 outcome = %outcome,
561 done = m.done_count(),
562 failed = m.failed_count(),
563 planned,
564 "backfill unit finished"
565 );
566 }
567 reports.push(UnitReport {
568 unit: unit.id.clone(),
569 start: unit.start.to_rfc3339(),
570 end: unit.end.to_rfc3339(),
571 outcome,
572 error,
573 });
574 }
575
576 reports.sort_by(|a, b| a.unit.cmp(&b.unit));
577 Ok(BackfillOutcome {
578 descriptor,
579 planned,
580 skipped,
581 succeeded,
582 failed,
583 dry_run: false,
584 units: reports,
585 })
586}
587
588async fn clear_scoped_unit_state(
592 store: &Arc<dyn StateStore>,
593 pipeline_name: &str,
594 units: &[BackfillUnit],
595) -> CliResult<()> {
596 for unit in units {
597 store
598 .delete(&unit_state_key(pipeline_name, &unit.id))
599 .await?;
600 }
601 Ok(())
602}
603
604async fn run_one_unit(
606 root: &ExpandedNode,
607 unit: &BackfillUnit,
608 range: &BackfillRange,
609 opts: &BackfillOptions,
610 store: &Arc<dyn StateStore>,
611 cancel: CancellationToken,
612) -> CliResult<()> {
613 let time_mode = matches!(range, BackfillRange::Time { .. });
614 let mut node = build_unit_node(root, unit, time_mode)?;
615
616 if let BackfillRange::Bookmark { from, to, field } = range {
617 let key = unit_state_key(&opts.pipeline_name, &unit.id);
620 if store.get(&key).await?.is_none() {
621 store.put(&key, from).await?;
622 }
623 if let (Some(to), Some(field)) = (to, field) {
626 let mut source_cfg = node.source.config.clone();
627 crate::executor::resolve_now_inplace(&mut source_cfg, unit.start)?;
628 let inner = crate::registry::build_source(
629 &node.source.kind,
630 source_cfg,
631 &opts.auth,
632 opts.resilience.as_ref().map(|r| &r.retry),
633 )
634 .await?;
635 node.source_override = Some(crate::dlq_replay::reader::SourceOverride::new(Box::new(
636 BoundedSource {
637 inner,
638 field: field.clone(),
639 to: to.clone(),
640 },
641 )));
642 }
643 }
644
645 let summary = run_expanded(vec![node], make_opts(opts, unit.start, cancel.clone())).await?;
646 if summary.had_failures() {
647 let detail = summary
648 .invocations
649 .iter()
650 .find_map(|i| i.error.clone())
651 .unwrap_or_else(|| "unknown error".to_string());
652 return Err(CliError::Internal(format!(
653 "unit {} failed: {detail}",
654 unit.id
655 )));
656 }
657 if cancel.is_cancelled() {
658 return Err(CliError::Internal(format!(
661 "unit {} interrupted by shutdown before completion",
662 unit.id
663 )));
664 }
665 Ok(())
666}
667
668#[cfg(test)]
669mod tests {
670 use super::*;
671 use serde_json::json;
672
673 fn parse_cfg(yaml: &str) -> PipelineConfig {
674 crate::config::parse_with_extension(yaml, "yaml").unwrap()
675 }
676
677 const SCOPED: &str = r#"
678version: 1
679name: orders
680pipeline:
681 source:
682 type: rest
683 config: { url: "https://api.example.com/orders?since=${backfill.start}&until=${backfill.end}" }
684 sink:
685 type: jsonl
686 config: { path: ./out.jsonl }
687"#;
688
689 fn time_range(
690 from: &str,
691 to: &str,
692 window: Option<crate::backfill::plan::WindowStep>,
693 ) -> BackfillRange {
694 let tz: chrono_tz::Tz = "UTC".parse().unwrap();
695 BackfillRange::Time {
696 from: crate::backfill::plan::parse_boundary(from, tz).unwrap(),
697 to: crate::backfill::plan::parse_boundary(to, tz).unwrap(),
698 window,
699 tz,
700 }
701 }
702
703 fn base_opts(range: BackfillRange) -> BackfillOptions {
704 BackfillOptions {
705 pipeline_name: "orders".into(),
706 execution: None,
707 auth: crate::auth_catalog::AuthCatalog::default(),
708 resilience: None,
709 range,
710 concurrency: 2,
711 row: None,
712 into_sink: None,
713 dry_run: true,
714 resume: false,
715 restart: false,
716 cancel: None,
717 }
718 }
719
720 #[tokio::test]
721 async fn dry_run_plans_31_units_without_running() {
722 let cfg = parse_cfg(SCOPED);
723 let opts = base_opts(time_range(
724 "2026-06-01",
725 "2026-07-02",
726 Some(crate::backfill::plan::WindowStep::Days(1)),
727 ));
728 let out = run_backfill(&cfg, opts).await.unwrap();
729 assert!(out.dry_run);
730 assert_eq!(out.planned, 31);
731 assert_eq!(out.units.len(), 31);
732 assert!(out.units.iter().all(|u| u.outcome == "pending"));
733 assert_eq!(out.succeeded + out.failed, 0);
734 }
735
736 #[tokio::test]
737 async fn unscoped_source_rejected_with_actionable_error() {
738 let cfg = parse_cfg(
739 r#"
740version: 1
741name: orders
742pipeline:
743 source: { type: rest, config: { url: "https://api.example.com/orders" } }
744 sink: { type: jsonl, config: { path: ./out.jsonl } }
745"#,
746 );
747 let opts = base_opts(time_range("2026-06-01", "2026-06-02", None));
748 let err = run_backfill(&cfg, opts).await.unwrap_err();
749 let msg = err.to_string();
750 assert!(msg.contains("${backfill.start}"), "actionable: {msg}");
751 assert!(
752 msg.contains("--from-bookmark"),
753 "suggests alternative: {msg}"
754 );
755 }
756
757 #[tokio::test]
758 async fn bookmark_mode_requires_state_block() {
759 let cfg = parse_cfg(SCOPED);
760 let opts = base_opts(BackfillRange::Bookmark {
761 from: json!("2026-01-01"),
762 to: None,
763 field: None,
764 });
765 let err = run_backfill(&cfg, opts).await.unwrap_err();
766 assert!(err.to_string().contains("state"), "{err}");
767 }
768
769 #[tokio::test]
770 async fn to_bookmark_requires_field() {
771 let cfg = parse_cfg(&format!(
772 "{SCOPED} state: {{ type: memory, config: {{}} }}\n"
773 ));
774 let opts = base_opts(BackfillRange::Bookmark {
775 from: json!(1),
776 to: Some(json!(9)),
777 field: None,
778 });
779 let err = run_backfill(&cfg, opts).await.unwrap_err();
780 assert!(err.to_string().contains("--bookmark-field"), "{err}");
781 }
782
783 #[tokio::test]
784 async fn into_unknown_sink_lists_available() {
785 let cfg = parse_cfg(
786 r#"
787version: 1
788name: orders
789pipeline:
790 sources:
791 default:
792 type: rest
793 config: { url: "https://api.example.com/x?s=${backfill.start}" }
794 sinks:
795 default: { type: jsonl, config: { path: ./out.jsonl } }
796 staging: { type: jsonl, config: { path: ./staging.jsonl } }
797"#,
798 );
799 let mut opts = base_opts(time_range("2026-06-01", "2026-06-02", None));
800 opts.into_sink = Some("nope".into());
801 let err = run_backfill(&cfg, opts).await.unwrap_err();
802 let msg = err.to_string();
803 assert!(msg.contains("staging"), "lists templates: {msg}");
804 }
805
806 #[tokio::test]
807 async fn multiple_roots_require_row_selection() {
808 let cfg = parse_cfg(
809 r#"
810version: 1
811name: orders
812pipeline:
813 source:
814 type: rest
815 config: { url: "https://api.example.com/x?s=${backfill.start}" }
816 sink: { type: jsonl, config: { path: ./out.jsonl } }
817matrix:
818 - id: a
819 - id: b
820"#,
821 );
822 let opts = base_opts(time_range("2026-06-01", "2026-06-02", None));
823 let err = run_backfill(&cfg, opts).await.unwrap_err();
824 assert!(err.to_string().contains("--row"), "{err}");
825
826 let mut opts = base_opts(time_range("2026-06-01", "2026-06-02", None));
827 opts.row = Some("b".into());
828 let out = run_backfill(&cfg, opts).await.unwrap();
829 assert_eq!(out.planned, 1);
830
831 let mut opts = base_opts(time_range("2026-06-01", "2026-06-02", None));
832 opts.row = Some("zzz".into());
833 let err = run_backfill(&cfg, opts).await.unwrap_err();
834 assert!(err.to_string().contains("available: a, b"), "{err}");
835 }
836
837 #[test]
838 fn unit_node_is_namespaced_and_at_least_once() {
839 let cfg = parse_cfg(SCOPED);
840 let root = select_root(expand(&cfg).unwrap(), None).unwrap();
841 let tz: chrono_tz::Tz = "UTC".parse().unwrap();
842 let unit = BackfillUnit {
843 id: "20260601T000000Z".into(),
844 start: crate::backfill::plan::parse_boundary("2026-06-01", tz).unwrap(),
845 end: crate::backfill::plan::parse_boundary("2026-06-02", tz).unwrap(),
846 };
847 let node = build_unit_node(&root, &unit, true).unwrap();
848 assert_eq!(node.id, "backfill::20260601T000000Z");
849 assert_eq!(node.delivery, faucet_core::DeliveryMode::AtLeastOnce);
850 let url = node.source.config["url"].as_str().unwrap();
851 assert!(url.contains("since=2026-06-01T00:00:00+00:00"), "{url}");
852 assert!(url.contains("until=2026-06-02T00:00:00+00:00"), "{url}");
853 }
854
855 #[tokio::test]
856 async fn restart_clears_scoped_unit_state() {
857 let store: Arc<dyn StateStore> = Arc::new(faucet_core::MemoryStateStore::new());
861 let key = unit_state_key("orders", "bookmark");
862 store.put(&key, &json!(500)).await.unwrap();
863
864 let tz: chrono_tz::Tz = "UTC".parse().unwrap();
865 let unit = BackfillUnit {
866 id: "bookmark".into(),
867 start: crate::backfill::plan::parse_boundary("2026-06-01", tz).unwrap(),
868 end: crate::backfill::plan::parse_boundary("2026-06-02", tz).unwrap(),
869 };
870 clear_scoped_unit_state(&store, "orders", std::slice::from_ref(&unit))
871 .await
872 .unwrap();
873 assert_eq!(
874 store.get(&key).await.unwrap(),
875 None,
876 "restart must delete the surviving scoped bookmark"
877 );
878 }
879
880 #[test]
881 fn descriptor_distinguishes_ranges_and_rows() {
882 let r1 = time_range("2026-06-01", "2026-07-01", None).descriptor("a");
883 let r2 = time_range("2026-06-01", "2026-07-01", None).descriptor("b");
884 let r3 = time_range("2026-06-01", "2026-07-02", None).descriptor("a");
885 assert_ne!(r1, r2);
886 assert_ne!(r1, r3);
887 let b = BackfillRange::Bookmark {
888 from: json!(5),
889 to: Some(json!(9)),
890 field: Some("id".into()),
891 }
892 .descriptor("a");
893 assert!(b.starts_with("bookmark|"), "{b}");
894 }
895
896 struct FixtureSource(Vec<Value>);
899
900 #[faucet_core::async_trait]
901 impl faucet_core::Source for FixtureSource {
902 async fn fetch_with_context(
903 &self,
904 _c: &std::collections::HashMap<String, Value>,
905 ) -> Result<Vec<Value>, FaucetError> {
906 Ok(self.0.clone())
907 }
908 }
909
910 #[tokio::test]
911 async fn bounded_source_drops_records_past_the_bound() {
912 use faucet_core::Source as _;
913 use futures::StreamExt;
914 let inner = FixtureSource(vec![
915 json!({"id": 1, "ts": "2026-06-01"}),
916 json!({"id": 2, "ts": "2026-06-15"}),
917 json!({"id": 3, "ts": "2026-07-05"}),
918 json!({"id": 4}), ]);
920 let bounded = BoundedSource {
921 inner: Box::new(inner),
922 field: "ts".into(),
923 to: json!("2026-06-30"),
924 };
925 let ctx = std::collections::HashMap::new();
926 let records = bounded.fetch_with_context(&ctx).await.unwrap();
927 let ids: Vec<i64> = records.iter().map(|r| r["id"].as_i64().unwrap()).collect();
928 assert_eq!(ids, vec![1, 2, 4], "record past the bound dropped");
929
930 let mut pages = bounded.stream_pages(&ctx, 10);
931 let page = pages.next().await.unwrap().unwrap();
932 assert_eq!(page.records.len(), 3);
933 }
934}