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 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(
689 from: &str,
690 to: &str,
691 window: Option<crate::backfill::plan::WindowStep>,
692 ) -> BackfillRange {
693 let tz: chrono_tz::Tz = "UTC".parse().unwrap();
694 BackfillRange::Time {
695 from: crate::backfill::plan::parse_boundary(from, tz).unwrap(),
696 to: crate::backfill::plan::parse_boundary(to, tz).unwrap(),
697 window,
698 tz,
699 }
700 }
701
702 fn base_opts(range: BackfillRange) -> BackfillOptions {
703 BackfillOptions {
704 pipeline_name: "orders".into(),
705 execution: None,
706 auth: crate::auth_catalog::AuthCatalog::default(),
707 resilience: None,
708 range,
709 concurrency: 2,
710 row: None,
711 into_sink: None,
712 dry_run: true,
713 resume: false,
714 restart: false,
715 cancel: None,
716 }
717 }
718
719 #[tokio::test]
720 async fn dry_run_plans_31_units_without_running() {
721 let cfg = parse_cfg(SCOPED);
722 let opts = base_opts(time_range(
723 "2026-06-01",
724 "2026-07-02",
725 Some(crate::backfill::plan::WindowStep::Days(1)),
726 ));
727 let out = run_backfill(&cfg, opts).await.unwrap();
728 assert!(out.dry_run);
729 assert_eq!(out.planned, 31);
730 assert_eq!(out.units.len(), 31);
731 assert!(out.units.iter().all(|u| u.outcome == "pending"));
732 assert_eq!(out.succeeded + out.failed, 0);
733 }
734
735 #[tokio::test]
736 async fn unscoped_source_rejected_with_actionable_error() {
737 let cfg = parse_cfg(
738 r#"
739version: 1
740name: orders
741pipeline:
742 source: { type: rest, config: { url: "https://api.example.com/orders" } }
743 sink: { type: jsonl, config: { path: ./out.jsonl } }
744"#,
745 );
746 let opts = base_opts(time_range("2026-06-01", "2026-06-02", None));
747 let err = run_backfill(&cfg, opts).await.unwrap_err();
748 let msg = err.to_string();
749 assert!(msg.contains("${backfill.start}"), "actionable: {msg}");
750 assert!(
751 msg.contains("--from-bookmark"),
752 "suggests alternative: {msg}"
753 );
754 }
755
756 #[tokio::test]
757 async fn bookmark_mode_requires_state_block() {
758 let cfg = parse_cfg(SCOPED);
759 let opts = base_opts(BackfillRange::Bookmark {
760 from: json!("2026-01-01"),
761 to: None,
762 field: None,
763 });
764 let err = run_backfill(&cfg, opts).await.unwrap_err();
765 assert!(err.to_string().contains("state"), "{err}");
766 }
767
768 #[tokio::test]
769 async fn to_bookmark_requires_field() {
770 let cfg = parse_cfg(&format!(
771 "{SCOPED} state: {{ type: memory, config: {{}} }}\n"
772 ));
773 let opts = base_opts(BackfillRange::Bookmark {
774 from: json!(1),
775 to: Some(json!(9)),
776 field: None,
777 });
778 let err = run_backfill(&cfg, opts).await.unwrap_err();
779 assert!(err.to_string().contains("--bookmark-field"), "{err}");
780 }
781
782 #[tokio::test]
783 async fn into_unknown_sink_lists_available() {
784 let cfg = parse_cfg(
785 r#"
786version: 1
787name: orders
788pipeline:
789 sources:
790 default:
791 type: rest
792 config: { url: "https://api.example.com/x?s=${backfill.start}" }
793 sinks:
794 default: { type: jsonl, config: { path: ./out.jsonl } }
795 staging: { type: jsonl, config: { path: ./staging.jsonl } }
796"#,
797 );
798 let mut opts = base_opts(time_range("2026-06-01", "2026-06-02", None));
799 opts.into_sink = Some("nope".into());
800 let err = run_backfill(&cfg, opts).await.unwrap_err();
801 let msg = err.to_string();
802 assert!(msg.contains("staging"), "lists templates: {msg}");
803 }
804
805 #[tokio::test]
806 async fn multiple_roots_require_row_selection() {
807 let cfg = parse_cfg(
808 r#"
809version: 1
810name: orders
811pipeline:
812 source:
813 type: rest
814 config: { url: "https://api.example.com/x?s=${backfill.start}" }
815 sink: { type: jsonl, config: { path: ./out.jsonl } }
816matrix:
817 - id: a
818 - id: b
819"#,
820 );
821 let opts = base_opts(time_range("2026-06-01", "2026-06-02", None));
822 let err = run_backfill(&cfg, opts).await.unwrap_err();
823 assert!(err.to_string().contains("--row"), "{err}");
824
825 let mut opts = base_opts(time_range("2026-06-01", "2026-06-02", None));
826 opts.row = Some("b".into());
827 let out = run_backfill(&cfg, opts).await.unwrap();
828 assert_eq!(out.planned, 1);
829
830 let mut opts = base_opts(time_range("2026-06-01", "2026-06-02", None));
831 opts.row = Some("zzz".into());
832 let err = run_backfill(&cfg, opts).await.unwrap_err();
833 assert!(err.to_string().contains("available: a, b"), "{err}");
834 }
835
836 #[test]
837 fn unit_node_is_namespaced_and_at_least_once() {
838 let cfg = parse_cfg(SCOPED);
839 let root = select_root(expand(&cfg).unwrap(), None).unwrap();
840 let tz: chrono_tz::Tz = "UTC".parse().unwrap();
841 let unit = BackfillUnit {
842 id: "20260601T000000Z".into(),
843 start: crate::backfill::plan::parse_boundary("2026-06-01", tz).unwrap(),
844 end: crate::backfill::plan::parse_boundary("2026-06-02", tz).unwrap(),
845 };
846 let node = build_unit_node(&root, &unit, true).unwrap();
847 assert_eq!(node.id, "backfill::20260601T000000Z");
848 assert_eq!(node.delivery, faucet_core::DeliveryMode::AtLeastOnce);
849 let url = node.source.config["url"].as_str().unwrap();
850 assert!(url.contains("since=2026-06-01T00:00:00+00:00"), "{url}");
851 assert!(url.contains("until=2026-06-02T00:00:00+00:00"), "{url}");
852 }
853
854 #[tokio::test]
855 async fn restart_clears_scoped_unit_state() {
856 let store: Arc<dyn StateStore> = Arc::new(faucet_core::MemoryStateStore::new());
860 let key = unit_state_key("orders", "bookmark");
861 store.put(&key, &json!(500)).await.unwrap();
862
863 let tz: chrono_tz::Tz = "UTC".parse().unwrap();
864 let unit = BackfillUnit {
865 id: "bookmark".into(),
866 start: crate::backfill::plan::parse_boundary("2026-06-01", tz).unwrap(),
867 end: crate::backfill::plan::parse_boundary("2026-06-02", tz).unwrap(),
868 };
869 clear_scoped_unit_state(&store, "orders", std::slice::from_ref(&unit))
870 .await
871 .unwrap();
872 assert_eq!(
873 store.get(&key).await.unwrap(),
874 None,
875 "restart must delete the surviving scoped bookmark"
876 );
877 }
878
879 #[test]
880 fn descriptor_distinguishes_ranges_and_rows() {
881 let r1 = time_range("2026-06-01", "2026-07-01", None).descriptor("a");
882 let r2 = time_range("2026-06-01", "2026-07-01", None).descriptor("b");
883 let r3 = time_range("2026-06-01", "2026-07-02", None).descriptor("a");
884 assert_ne!(r1, r2);
885 assert_ne!(r1, r3);
886 let b = BackfillRange::Bookmark {
887 from: json!(5),
888 to: Some(json!(9)),
889 field: Some("id".into()),
890 }
891 .descriptor("a");
892 assert!(b.starts_with("bookmark|"), "{b}");
893 }
894
895 struct FixtureSource(Vec<Value>);
898
899 #[faucet_core::async_trait]
900 impl faucet_core::Source for FixtureSource {
901 async fn fetch_with_context(
902 &self,
903 _c: &std::collections::HashMap<String, Value>,
904 ) -> Result<Vec<Value>, FaucetError> {
905 Ok(self.0.clone())
906 }
907 }
908
909 #[tokio::test]
910 async fn bounded_source_drops_records_past_the_bound() {
911 use faucet_core::Source as _;
912 use futures::StreamExt;
913 let inner = FixtureSource(vec![
914 json!({"id": 1, "ts": "2026-06-01"}),
915 json!({"id": 2, "ts": "2026-06-15"}),
916 json!({"id": 3, "ts": "2026-07-05"}),
917 json!({"id": 4}), ]);
919 let bounded = BoundedSource {
920 inner: Box::new(inner),
921 field: "ts".into(),
922 to: json!("2026-06-30"),
923 };
924 let ctx = std::collections::HashMap::new();
925 let records = bounded.fetch_with_context(&ctx).await.unwrap();
926 let ids: Vec<i64> = records.iter().map(|r| r["id"].as_i64().unwrap()).collect();
927 assert_eq!(ids, vec![1, 2, 4], "record past the bound dropped");
928
929 let mut pages = bounded.stream_pages(&ctx, 10);
930 let page = pages.next().await.unwrap().unwrap();
931 assert_eq!(page.records.len(), 3);
932 }
933}