use crate::auth_catalog::AuthCatalog;
use crate::config::{ExecutionSpec, OnError};
use crate::error::{CliError, CliResult};
use crate::expand::{ExpandedNode, NodeRole};
use crate::interpolate::interpolate_record;
use crate::registry::{build_sink, build_source};
use crate::state::build_state_store;
use crate::transforms::compile_transforms;
use async_trait::async_trait;
use chrono::{DateTime, FixedOffset};
use faucet_core::observability::Labels;
use faucet_core::{DlqConfig, FaucetError, OnBatchError, Pipeline, Sink, Source, StateStore};
use serde_json::Value;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use tokio::sync::{Mutex, Semaphore};
type CapturedRecords = Arc<Mutex<HashMap<String, Vec<Arc<Value>>>>>;
use tokio_util::sync::CancellationToken;
pub struct ExecuteOptions {
pub pipeline_name: String,
pub execution: Option<ExecutionSpec>,
pub dry_run: bool,
pub limit: Option<usize>,
pub state_path_override: Option<PathBuf>,
pub shard: Option<faucet_core::ShardSpec>,
pub auth: AuthCatalog,
pub clock: DateTime<FixedOffset>,
pub cancel: Option<CancellationToken>,
pub resilience: Option<faucet_core::ResiliencePolicy>,
pub sla: Option<crate::sla::SlaSpec>,
#[cfg(feature = "lineage")]
pub lineage: Option<std::sync::Arc<faucet_lineage::LineageEmitter>>,
#[cfg(feature = "lineage")]
pub lineage_cfg: Option<faucet_lineage::LineageConfig>,
#[cfg(feature = "notify")]
pub notifier: Option<std::sync::Arc<crate::notify::Notifier>>,
#[cfg(feature = "catalog")]
pub catalog: Option<crate::catalog::CatalogHandle>,
}
const STOP_FLUSH_GRACE: Duration = Duration::from_secs(5);
#[derive(Debug)]
pub struct InvocationOutcome {
pub row_id: String,
pub parent_record_key: Option<String>,
pub records_written: usize,
pub error: Option<String>,
}
#[derive(Debug)]
pub struct RunSummary {
pub invocations: Vec<InvocationOutcome>,
}
impl RunSummary {
pub fn failure_count(&self) -> usize {
self.invocations
.iter()
.filter(|i| i.error.is_some())
.count()
}
pub fn had_failures(&self) -> bool {
self.failure_count() > 0
}
}
fn default_concurrency() -> usize {
std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(4)
.clamp(1, 8)
}
pub async fn run_expanded(nodes: Vec<ExpandedNode>, opts: ExecuteOptions) -> CliResult<RunSummary> {
let on_error = opts
.execution
.as_ref()
.map(|e| e.on_error)
.unwrap_or_default();
let max_concurrent = opts
.execution
.as_ref()
.and_then(|e| e.max_concurrent)
.unwrap_or_else(default_concurrency)
.max(1);
let semaphore = Arc::new(Semaphore::new(max_concurrent));
let mut children_of: HashMap<String, Vec<String>> = HashMap::new();
for n in nodes.iter() {
if let NodeRole::Child { parent_id, .. } = &n.role {
children_of
.entry(parent_id.clone())
.or_default()
.push(n.id.clone());
}
}
let captured: CapturedRecords = Arc::new(Mutex::new(HashMap::new()));
let mut outcomes: Vec<InvocationOutcome> = Vec::new();
let mut skipped_subtrees: HashSet<String> = HashSet::new();
let cancel = opts.cancel.clone().unwrap_or_default();
let opts = Arc::new(opts);
let mut remaining: HashSet<String> = nodes.iter().map(|n| n.id.clone()).collect();
let mut completed: HashSet<String> = HashSet::new();
let nodes_by_id: HashMap<String, ExpandedNode> =
nodes.into_iter().map(|n| (n.id.clone(), n)).collect();
let projections = build_projections(&nodes_by_id, &children_of);
let bfs_order: Vec<String> = {
let mut ids: Vec<(usize, String)> = nodes_by_id
.values()
.map(|n| (n.row_index, n.id.clone()))
.collect();
ids.sort_by_key(|(i, _)| *i);
ids.into_iter().map(|(_, id)| id).collect()
};
while !remaining.is_empty() {
let ready: Vec<String> = bfs_order
.iter()
.filter(|id| remaining.contains(*id))
.filter(|id| {
let node = &nodes_by_id[*id];
let parent_done = match &node.role {
NodeRole::Root => true,
NodeRole::Child { parent_id, .. } => {
completed.contains(parent_id) || skipped_subtrees.contains(parent_id)
}
};
parent_done
&& node
.depends_on
.iter()
.all(|d| completed.contains(d) || skipped_subtrees.contains(d))
})
.cloned()
.collect();
if ready.is_empty() {
let mut stuck: Vec<String> = remaining.iter().cloned().collect();
stuck.sort();
return Err(CliError::Internal(format!(
"executor deadlock: {} node(s) never became ready (no completed/skipped \
parent or dependency): {}",
stuck.len(),
stuck.join(", ")
)));
}
let mut units: Vec<Unit> = Vec::new();
let level_records: HashMap<String, Vec<Arc<Value>>> = {
let consumed_parents: HashSet<&str> = ready
.iter()
.filter_map(|id| match &nodes_by_id[id].role {
NodeRole::Child { parent_id, .. } => Some(parent_id.as_str()),
NodeRole::Root => None,
})
.collect();
let mut cap = captured.lock().await;
consumed_parents
.iter()
.filter_map(|p| cap.remove(*p).map(|v| (p.to_string(), v)))
.collect()
};
for id in &ready {
let node = &nodes_by_id[id];
if let NodeRole::Child { parent_id, .. } = &node.role
&& skipped_subtrees.contains(parent_id)
{
skipped_subtrees.insert(id.clone());
tracing::warn!(row = %id, parent = %parent_id, "skipping subtree under failed parent");
continue;
}
if let Some(dep) = node
.depends_on
.iter()
.find(|d| skipped_subtrees.contains(d.as_str()))
{
skipped_subtrees.insert(id.clone());
tracing::warn!(
row = %id, dependency = %dep,
"skipping row: a depends_on row failed or was skipped"
);
continue;
}
match &node.role {
NodeRole::Root => {
let uses_state = node.state.is_some() || opts.state_path_override.is_some();
let state_key = build_state_key(&opts.pipeline_name, &node.id, None);
validate_unit_state_key(&node.id, uses_state, &state_key)?;
units.push(Unit {
node: node.clone(),
parent_record: None,
state_key,
parent_record_key: None,
});
}
NodeRole::Child {
parent_id,
parent_key,
} => {
let parent_records = level_records.get(parent_id).cloned().unwrap_or_default();
if parent_records.is_empty() {
tracing::info!(
row = %id, parent = %parent_id,
"parent produced no records — child skipped"
);
continue;
}
let uses_state = node.state.is_some() || opts.state_path_override.is_some();
let mut seen_keys: HashSet<String> = HashSet::new();
for record in &parent_records {
let pk_value = resolve_parent_key(record, parent_key);
let pk_string = pk_value
.as_ref()
.map(value_to_string_brief)
.unwrap_or_else(|| "(missing)".to_string());
let state_key =
build_state_key(&opts.pipeline_name, &node.id, Some(&pk_string));
validate_unit_state_key(&node.id, uses_state, &state_key)?;
if !seen_keys.insert(state_key.clone()) {
return Err(CliError::DuplicateStateKey {
id: node.id.clone(),
state_key,
});
}
units.push(Unit {
node: node.clone(),
parent_record: Some(record.clone()),
state_key,
parent_record_key: Some(pk_string),
});
}
}
}
}
drop(level_records);
let mut had_level_failure = false;
let mut nodes_with_any_failure: HashSet<String> = HashSet::new();
let level_cancel = cancel.child_token();
let mut joinset = tokio::task::JoinSet::new();
let mut task_meta: HashMap<tokio::task::Id, (String, Option<String>)> = HashMap::new();
for unit in units {
let sem = Arc::clone(&semaphore);
let opts2 = Arc::clone(&opts);
let captured = Arc::clone(&captured);
let capture = projections.get(&unit.node.id).cloned();
let meta = (unit.node.id.clone(), unit.parent_record_key.clone());
let unit_cancel = level_cancel.clone();
let handle = joinset.spawn(async move {
let _permit = sem.acquire().await.expect("semaphore not closed");
run_unit(&unit, capture, &captured, &opts2, unit_cancel).await
});
task_meta.insert(handle.id(), meta);
}
let mut stop_triggered = false;
let mut aborted = false;
let mut stop_deadline: Option<tokio::time::Instant> = None;
loop {
let joined = match stop_deadline {
Some(deadline) if !aborted => {
match tokio::time::timeout_at(deadline, joinset.join_next_with_id()).await {
Ok(j) => j,
Err(_) => {
tracing::warn!(
"on_error: stop — flush grace elapsed; aborting remaining \
in-flight invocations"
);
joinset.abort_all();
aborted = true;
continue;
}
}
}
_ => joinset.join_next_with_id().await,
};
let Some(joined) = joined else { break };
let outcome = match joined {
Ok((_id, outcome)) => outcome,
Err(e) if e.is_cancelled() => {
continue;
}
Err(e) => {
let (row_id, parent_record_key) = task_meta
.get(&e.id())
.cloned()
.unwrap_or_else(|| ("<unknown>".to_string(), None));
InvocationOutcome {
row_id,
parent_record_key,
records_written: 0,
error: Some(format!("pipeline invocation task panicked: {e}")),
}
}
};
if let Some(err) = &outcome.error {
tracing::error!(row = %outcome.row_id, error = %err, "pipeline invocation failed");
had_level_failure = true;
nodes_with_any_failure.insert(outcome.row_id.clone());
if matches!(on_error, OnError::Stop) && !stop_triggered {
stop_triggered = true;
tracing::error!(
"on_error: stop — cancelling in-flight invocations (cooperative \
flush), then aborting any that don't stop within the grace window"
);
level_cancel.cancel();
stop_deadline = Some(tokio::time::Instant::now() + STOP_FLUSH_GRACE);
}
} else {
tracing::info!(
row = %outcome.row_id,
records_written = outcome.records_written,
"pipeline invocation completed"
);
}
outcomes.push(outcome);
}
for id in ready {
remaining.remove(&id);
if nodes_with_any_failure.contains(&id) {
skipped_subtrees.insert(id.clone());
if let Some(children) = children_of.get(&id) {
for cid in children {
skipped_subtrees.insert(cid.clone());
}
}
} else {
completed.insert(id);
}
}
if had_level_failure && matches!(on_error, OnError::Stop) {
tracing::error!("on_error: stop — aborting after first failure");
break;
}
}
Ok(RunSummary {
invocations: outcomes,
})
}
struct Unit {
node: ExpandedNode,
parent_record: Option<Arc<Value>>,
state_key: String,
parent_record_key: Option<String>,
}
async fn run_unit(
unit: &Unit,
capture: Option<Arc<Projection>>,
captured: &CapturedRecords,
opts: &ExecuteOptions,
cancel: CancellationToken,
) -> InvocationOutcome {
let needs_capture = capture.is_some();
let result = run_one_invocation(
&unit.node,
unit.parent_record.as_deref(),
&unit.state_key,
capture,
opts,
cancel,
)
.await;
let row_id = unit.node.id.clone();
let parent_record_key = unit.parent_record_key.clone();
match result {
Ok((records, written)) => {
if needs_capture {
captured
.lock()
.await
.entry(row_id.clone())
.or_default()
.extend(records.into_iter().map(Arc::new));
}
InvocationOutcome {
row_id,
parent_record_key,
records_written: written,
error: None,
}
}
Err(e) => InvocationOutcome {
row_id,
parent_record_key,
records_written: 0,
error: Some(e.to_string()),
},
}
}
pub(crate) fn build_state_key(
pipeline_name: &str,
row_id: &str,
parent_key: Option<&str>,
) -> String {
match parent_key {
None => format!("{pipeline_name}::{row_id}"),
Some(k) => format!("{pipeline_name}::{row_id}::{k}"),
}
}
fn validate_unit_state_key(node_id: &str, uses_state: bool, state_key: &str) -> CliResult<()> {
if uses_state {
faucet_core::state::validate_state_key(state_key).map_err(|e| {
CliError::InvalidStateKey {
id: node_id.to_owned(),
state_key: state_key.to_owned(),
reason: e.to_string(),
}
})?;
}
Ok(())
}
fn resolve_parent_key(record: &Value, parent_key: &str) -> Option<Value> {
let mut cur = record;
for segment in parent_key.split('.') {
cur = match cur {
Value::Object(m) => m.get(segment)?,
Value::Array(a) => a.get(segment.parse::<usize>().ok()?)?,
_ => return None,
};
}
Some(cur.clone())
}
#[derive(Debug, Clone)]
enum Projection {
Full,
Paths(Vec<Vec<String>>),
}
fn split_path(path: &str) -> Vec<String> {
path.split('.').map(|s| s.to_string()).collect()
}
fn minimal_paths(mut paths: Vec<Vec<String>>) -> Vec<Vec<String>> {
paths.sort();
paths.dedup();
let mut kept: Vec<Vec<String>> = Vec::new();
for p in paths {
let covered = kept
.iter()
.any(|anc| p.len() >= anc.len() && p[..anc.len()] == anc[..]);
if !covered {
kept.push(p);
}
}
kept
}
fn walk_value(record: &Value, segments: &[String]) -> Option<Value> {
let mut cur = record;
for seg in segments {
cur = match cur {
Value::Object(m) => m.get(seg)?,
Value::Array(a) => a.get(seg.parse::<usize>().ok()?)?,
_ => return None,
};
}
Some(cur.clone())
}
fn graft_object(out: &mut Value, segments: &[String], leaf: Value) {
if segments.is_empty() {
return;
}
let mut cur = out;
for seg in &segments[..segments.len() - 1] {
let map = match cur {
Value::Object(m) => m,
_ => return,
};
cur = map
.entry(seg.clone())
.or_insert_with(|| Value::Object(serde_json::Map::new()));
}
if let Value::Object(m) = cur {
m.insert(segments[segments.len() - 1].clone(), leaf);
}
}
fn project_record(record: &Value, projection: &Projection) -> Value {
match projection {
Projection::Full => record.clone(),
Projection::Paths(paths) => {
let mut out = Value::Object(serde_json::Map::new());
for segs in paths {
if let Some(v) = walk_value(record, segs) {
graft_object(&mut out, segs, v);
}
}
out
}
}
}
fn build_projections(
nodes_by_id: &HashMap<String, ExpandedNode>,
children_of: &HashMap<String, Vec<String>>,
) -> HashMap<String, Arc<Projection>> {
let mut out = HashMap::new();
for (parent_id, child_ids) in children_of {
let mut raw: Vec<Vec<String>> = Vec::new();
let mut full = false;
for cid in child_ids {
let child = &nodes_by_id[cid];
if let NodeRole::Child { parent_key, .. } = &child.role {
if parent_key.is_empty() {
full = true;
} else {
raw.push(split_path(parent_key));
}
}
for dref in &child.deferred_refs {
if dref.referenced_id == *parent_id {
if dref.dotted_path.is_empty() {
full = true; } else {
raw.push(split_path(&dref.dotted_path));
}
}
}
}
let projection = if full || raw.is_empty() {
Projection::Full
} else {
Projection::Paths(minimal_paths(raw))
};
out.insert(parent_id.clone(), Arc::new(projection));
}
out
}
async fn run_one_invocation(
node: &ExpandedNode,
parent_record: Option<&Value>,
state_key: &str,
capture: Option<Arc<Projection>>,
opts: &ExecuteOptions,
cancel: CancellationToken,
) -> CliResult<(Vec<Value>, usize)> {
let run_id = uuid::Uuid::now_v7().to_string();
let pipeline_name = opts.pipeline_name.clone();
let row_id = node.id.clone();
#[cfg(feature = "lineage")]
let lineage = opts.lineage.clone();
#[cfg(feature = "lineage")]
let lineage_cfg = opts.lineage_cfg.clone();
let obs_labels = Labels::new(pipeline_name.clone(), row_id.clone(), run_id.clone());
#[cfg(feature = "catalog")]
let catalog_active = opts.catalog.is_some()
&& matches!(node.role, NodeRole::Root)
&& !opts.dry_run
&& opts.limit.is_none()
&& opts.shard.is_none();
let mut source_cfg = node.source.config.clone();
let mut sink_cfg = node.sink.config.clone();
resolve_now_inplace(&mut source_cfg, opts.clock)?;
resolve_now_inplace(&mut sink_cfg, opts.clock)?;
if let (Some(record), NodeRole::Child { parent_id, .. }) = (parent_record, &node.role) {
let ctx: HashMap<String, Value> = HashMap::from([(parent_id.clone(), record.clone())]);
resolve_inplace(&mut source_cfg, &ctx)?;
resolve_inplace(&mut sink_cfg, &ctx)?;
}
let source = match node.source_override.as_ref().and_then(|o| o.take()) {
Some(prebuilt) => prebuilt,
None => {
build_source(
&node.source.kind,
source_cfg,
&opts.auth,
opts.resilience.as_ref().map(|r| &r.retry),
)
.await?
}
};
#[cfg(feature = "catalog")]
let source_dataset_uri = source.dataset_uri();
if let Some(shard) = &opts.shard {
source
.apply_shard(shard)
.await
.map_err(|e| CliError::Internal(format!("applying shard {:?}: {e}", shard.id)))?;
}
let raw_sink: Box<dyn Sink> = if opts.dry_run {
Box::new(CountingSink::new())
} else {
build_sink(&node.sink.kind, sink_cfg, &opts.auth).await?
};
#[cfg(feature = "catalog")]
let sink_dataset_uri = raw_sink.dataset_uri();
let raw_sink: Box<dyn Sink> = match opts.limit {
Some(n) => Box::new(LimitedSink::wrap(raw_sink, n)),
None => raw_sink,
};
let captured = Arc::new(Mutex::new(Vec::<Value>::new()));
let sink: Box<dyn Sink> = match &capture {
Some(projection) => Box::new(CapturingSink::wrap(
raw_sink,
Arc::clone(&captured),
Arc::clone(projection),
)),
None => raw_sink,
};
#[cfg(feature = "lineage")]
let (in_sample, out_sample) = {
use std::sync::Arc as StdArc;
let mut want = false;
let mut cap = 0usize;
if let (Some(_), Some(lc)) = (&lineage, &lineage_cfg) {
let want_schema = lc.include_schema_facet || lc.include_column_lineage;
if want_schema {
cap = cap.max(lc.sample_records);
}
want = want_schema || lc.emit_on.running;
}
#[cfg(feature = "catalog")]
if catalog_active {
want = true;
cap = cap.max(
opts.catalog
.as_ref()
.map(|h| h.sample_records)
.unwrap_or(crate::catalog::DEFAULT_SAMPLE_RECORDS),
);
}
if want {
(
Some(StdArc::new(faucet_lineage::SampleState::new(cap))),
Some(StdArc::new(faucet_lineage::SampleState::new(cap))),
)
} else {
(None, None)
}
};
#[cfg(feature = "lineage")]
let source: Box<dyn Source> = match &in_sample {
Some(state) => Box::new(faucet_lineage::SamplingSource::new(
source,
std::sync::Arc::clone(state),
)),
None => source,
};
let stages = if node.transforms.is_empty() {
compile_transforms(&node.transforms)?
} else {
let mut transforms = node.transforms.clone();
for t in &mut transforms {
resolve_now_inplace(&mut t.config, opts.clock)?;
}
compile_transforms(&transforms)?
};
let source: Box<dyn Source> = if stages.is_empty() {
source
} else {
Box::new(faucet_core::TransformingSource::new(
source,
stages,
obs_labels.clone(),
)?)
};
let state = build_state_for_node(node, opts.state_path_override.as_deref()).await?;
let sla_store = state.clone();
let effective_state_key = match &opts.shard {
Some(shard) => format!("{state_key}::{}", shard.id),
None => state_key.to_owned(),
};
let source: Box<dyn Source> = if state.is_some() && source.state_key().is_some() {
Box::new(StateKeyOverride {
inner: source,
key: effective_state_key,
})
} else {
source
};
#[cfg(feature = "lineage")]
let sink: Box<dyn Sink> = match &out_sample {
Some(state) => Box::new(faucet_lineage::SamplingSink::new(
sink,
std::sync::Arc::clone(state),
)),
None => sink,
};
#[cfg(feature = "lineage")]
let pipeline = Pipeline::new(source.as_ref(), sink.as_ref())
.with_name(pipeline_name.clone())
.with_row(row_id.clone())
.with_run_id(run_id.clone());
#[cfg(not(feature = "lineage"))]
let pipeline = Pipeline::new(source.as_ref(), sink.as_ref())
.with_name(pipeline_name)
.with_row(row_id)
.with_run_id(run_id);
let pipeline = match state {
Some(store) => pipeline.with_state_store(store),
None => pipeline,
};
let pipeline = if let Some(ref dlq_spec) = node.dlq {
let dlq_cfg = build_dlq_config(dlq_spec).await?;
pipeline.with_dlq(dlq_cfg)
} else {
pipeline
};
let pipeline = pipeline.with_cancel(cancel.clone());
#[cfg(feature = "quality")]
let pipeline = if let Some(ref quality_spec) = node.quality {
let compiled = Arc::new(
faucet_core::CompiledQuality::compile(quality_spec)
.map_err(|e| CliError::Config(format!("quality: {e}")))?,
);
pipeline.with_quality(compiled)
} else {
pipeline
};
#[cfg(feature = "contract")]
let pipeline = if let Some(ref contract_spec) = node.contract {
let compiled = Arc::new(
faucet_core::CompiledContract::compile(contract_spec)
.map_err(|e| CliError::Config(format!("contract: {e}")))?,
);
pipeline.with_contract(compiled)
} else {
pipeline
};
#[cfg(feature = "masking")]
let pipeline = if let Some(ref masking_spec) = node.masking {
let sink_ids = [node.sink_ref.as_str(), node.sink.kind.as_str()];
let compiled = faucet_core::CompiledMasking::compile_for_sink(masking_spec, &sink_ids)
.map_err(|e| CliError::Config(format!("masking: {e}")))?;
if compiled.is_empty() {
pipeline
} else {
pipeline.with_masking(Arc::new(compiled))
}
} else {
pipeline
};
let pipeline = if let Some(ref sd) = node.schema {
pipeline.with_schema_drift(faucet_core::SchemaDriftPolicy::compile(sd))
} else {
pipeline
};
let pipeline = if let Some(ab) = opts
.execution
.as_ref()
.and_then(|e| e.adaptive_batch_size.clone())
{
ab.validate()
.map_err(|e| CliError::Config(format!("adaptive_batch_size: {e}")))?;
pipeline.with_adaptive(ab)
} else {
pipeline
};
let pipeline = if let Some(policy) = opts.resilience.clone() {
pipeline.with_resilience(policy)
} else {
pipeline
};
let effective_delivery = if opts.dry_run || opts.limit.is_some() {
faucet_core::idempotency::DeliveryMode::AtLeastOnce
} else {
node.delivery
};
let pipeline = pipeline.with_delivery(effective_delivery);
#[cfg(feature = "lineage")]
let lineage_ctx = match (&lineage, &lineage_cfg) {
(Some(em), Some(lc)) => {
let job_name =
crate::interpolate::resolve_lineage_job_name(&lc.job_name, &pipeline_name, &row_id);
let mut ctx = faucet_lineage::RunLifecycle {
job_namespace: lc.namespace.clone(),
job_name,
run_id: run_id.clone(),
parent: lc.parent_job.clone(),
input: faucet_lineage::DatasetRef {
namespace: lc.namespace.clone(),
name: source.dataset_uri(),
},
output: faucet_lineage::DatasetRef {
namespace: lc.namespace.clone(),
name: sink.dataset_uri(),
},
started_at: chrono::Utc::now(),
finished_at: None,
records: 0,
error: None,
input_schema: None,
output_schema: None,
column_lineage: None,
source_code: None,
};
em.emit(faucet_lineage::EventType::Start, &ctx).await;
let hb_handle = if lc.emit_on.running {
let em2 = std::sync::Arc::clone(em);
let interval = lc.heartbeat_interval;
let mut beat_ctx = ctx.clone();
let counter = out_sample.clone();
Some(tokio::spawn(async move {
let mut tick = tokio::time::interval(interval);
tick.tick().await; loop {
tick.tick().await;
if let Some(c) = &counter {
beat_ctx.records = c.count();
}
em2.emit(faucet_lineage::EventType::Running, &beat_ctx)
.await;
}
}))
} else {
None
};
ctx.source_code = if lc.include_source_code_facet {
Some(serde_json::to_string(&node.source.config).unwrap_or_default())
} else {
None
};
Some((std::sync::Arc::clone(em), ctx, hb_handle))
}
_ => None,
};
let result: Result<faucet_core::PipelineResult, FaucetError> = match pipeline.run().await {
Ok(r) => sink.flush().await.map(|_| r),
Err(e) => Err(e),
};
#[cfg(feature = "lineage")]
if let Some((em, mut ctx, hb)) = lineage_ctx {
if let Some(h) = hb {
h.abort();
}
ctx.finished_at = Some(chrono::Utc::now());
if let Some(state) = &out_sample {
ctx.records = state.count();
if lineage_cfg
.as_ref()
.map(|l| l.include_schema_facet)
.unwrap_or(false)
{
ctx.output_schema = Some(state.inferred_schema());
}
}
if let Some(state) = &in_sample
&& lineage_cfg
.as_ref()
.map(|l| l.include_schema_facet || l.include_column_lineage)
.unwrap_or(false)
{
let in_schema = state.inferred_schema();
if lineage_cfg
.as_ref()
.map(|l| l.include_column_lineage)
.unwrap_or(false)
{
let input_fields: Vec<String> =
in_schema.fields.iter().map(|(n, _)| n.clone()).collect();
#[cfg(feature = "masking")]
let has_masking = node.masking.is_some();
#[cfg(not(feature = "masking"))]
let has_masking = false;
let ops = crate::lineage_glue::column_ops(&node.transforms, has_masking);
ctx.column_lineage = faucet_lineage::derive_column_lineage(&input_fields, &ops);
}
if lineage_cfg
.as_ref()
.map(|l| l.include_schema_facet)
.unwrap_or(false)
{
ctx.input_schema = Some(in_schema);
}
}
let ev = match &result {
Err(e) => {
ctx.error = Some(e.to_string());
faucet_lineage::EventType::Fail
}
Ok(_) if cancel.is_cancelled() => faucet_lineage::EventType::Abort,
Ok(_) => faucet_lineage::EventType::Complete,
};
em.emit(ev, &ctx).await;
}
let is_notifiable_root = matches!(node.role, NodeRole::Root)
&& !opts.dry_run
&& opts.limit.is_none()
&& opts.shard.is_none()
&& !cancel.is_cancelled();
#[cfg_attr(not(feature = "notify"), allow(unused_variables))]
let sla_violations = if let Some(spec) = &opts.sla
&& is_notifiable_root
{
let outcome = match &result {
Ok(r) => crate::sla::RunOutcome::Success {
rows: r.records_written as u64,
},
Err(_) => crate::sla::RunOutcome::Failure,
};
crate::sla::evaluate_post_run(
spec,
sla_store.as_ref(),
state_key,
&obs_labels.pipeline,
&obs_labels.row,
outcome,
chrono::Utc::now().timestamp(),
)
.await
} else {
Vec::new()
};
#[cfg(feature = "notify")]
if let Some(notifier) = &opts.notifier
&& is_notifiable_root
{
use crate::notify::NotifyEvent;
let pipeline = obs_labels.pipeline.to_string();
let row = obs_labels.row.to_string();
match &result {
Ok(r) => {
notifier
.emit(NotifyEvent::run_success(
pipeline.clone(),
row.clone(),
r.records_written as u64,
))
.await;
if let Some(dlq) = &r.dlq
&& dlq.records_dlq > 0
{
notifier
.emit(NotifyEvent::dlq_threshold(
pipeline.clone(),
row.clone(),
dlq.records_dlq as u64,
))
.await;
}
}
Err(e) => {
notifier.emit(error_event(&pipeline, &row, e)).await;
}
}
for v in &sla_violations {
notifier
.emit(NotifyEvent::sla_breach(
pipeline.clone(),
row.clone(),
v.kind(),
v.to_string(),
))
.await;
}
}
#[cfg(feature = "catalog")]
if let Some(handle) = &opts.catalog
&& catalog_active
&& !cancel.is_cancelled()
&& let Ok(pipeline_result) = &result
{
use crate::catalog::model::{canonicalize_uri, schema_from_samples};
use crate::serve::history::catalog::{CatalogUpdate, DatasetObservation, DatasetRole};
let records_written = pipeline_result.records_written as u64;
let source_schema = in_sample
.as_ref()
.and_then(|s| schema_from_samples(&s.samples()));
let sink_schema = out_sample
.as_ref()
.and_then(|s| schema_from_samples(&s.samples()));
let records_read = in_sample
.as_ref()
.map(|s| s.count())
.unwrap_or(records_written);
let records_out = out_sample
.as_ref()
.map(|s| s.count())
.unwrap_or(records_written);
let column_lineage = in_sample.as_ref().and_then(|s| {
let input_fields: Vec<String> = s
.inferred_schema()
.fields
.iter()
.map(|(n, _)| n.clone())
.collect();
#[cfg(feature = "masking")]
let has_masking = node.masking.is_some();
#[cfg(not(feature = "masking"))]
let has_masking = false;
let ops = crate::lineage_glue::column_ops(&node.transforms, has_masking);
faucet_lineage::derive_column_lineage(&input_fields, &ops).map(|cl| {
let fields: serde_json::Map<String, Value> = cl
.edges
.iter()
.map(|(out, ins)| {
(
out.clone(),
Value::Array(ins.iter().map(|s| Value::String(s.clone())).collect()),
)
})
.collect();
serde_json::json!({ "fields": fields })
})
});
let update = CatalogUpdate {
run_id: handle.run_id.clone().unwrap_or_else(|| run_id.clone()),
pipeline: obs_labels.pipeline.to_string(),
row: obs_labels.row.to_string(),
recorded_at: chrono::Utc::now(),
source: DatasetObservation {
uri: canonicalize_uri(&source_dataset_uri, &node.source.config, opts.clock),
kind: node.source.kind.clone(),
role: DatasetRole::Source,
schema: source_schema,
records: records_read,
},
sink: DatasetObservation {
uri: canonicalize_uri(&sink_dataset_uri, &node.sink.config, opts.clock),
kind: node.sink.kind.clone(),
role: DatasetRole::Sink,
schema: sink_schema,
records: records_out,
},
column_lineage,
};
crate::catalog::record(handle, &update).await;
}
let result = result?;
let captured = if capture.is_some() {
std::mem::take(&mut *captured.lock().await)
} else {
Vec::new()
};
Ok((captured, result.records_written))
}
async fn build_state_for_node(
node: &ExpandedNode,
state_path_override: Option<&Path>,
) -> CliResult<Option<Arc<dyn StateStore>>> {
match (&node.state, state_path_override) {
(Some(spec), None) => Ok(Some(build_state_store(spec).await?)),
(None, Some(path)) => Ok(Some(state_from_override(path))),
(Some(spec), Some(path)) => {
if spec.kind == "file" {
Ok(Some(state_from_override(path)))
} else {
tracing::warn!(
state = %spec.kind,
"--state-path is only meaningful for the 'file' backend; ignoring override"
);
Ok(Some(build_state_store(spec).await?))
}
}
(None, None) => Ok(None),
}
}
fn state_from_override(path: &Path) -> Arc<dyn StateStore> {
Arc::new(faucet_core::FileStateStore::new(path)) as Arc<dyn StateStore>
}
pub async fn build_dlq_config(spec: &crate::config::DlqSpec) -> CliResult<DlqConfig> {
let sink = build_sink(
&spec.sink.kind,
spec.sink.config.clone(),
&AuthCatalog::new(),
)
.await?;
Ok(DlqConfig {
sink: Arc::from(sink),
on_batch_error: match spec.on_batch_error {
crate::config::OnBatchErrorSpec::Propagate => OnBatchError::Propagate,
crate::config::OnBatchErrorSpec::DlqAll => OnBatchError::DlqAll,
},
max_failures_per_page: spec.max_failures_per_page,
max_failures_total: spec.max_failures_total,
include_original_payload: spec.include_original_payload,
})
}
#[cfg(feature = "notify")]
fn error_event(pipeline: &str, row: &str, err: &FaucetError) -> crate::notify::NotifyEvent {
use crate::notify::NotifyEvent;
match err {
FaucetError::CircuitOpen { failures, cooldown } => {
NotifyEvent::circuit_open(pipeline, row, *failures, cooldown.as_secs())
}
FaucetError::ContractViolation { message, .. } => {
NotifyEvent::contract_abort(pipeline, row, message.clone())
}
other => {
NotifyEvent::run_failure(pipeline, row, faucet_error_kind(other), other.to_string())
}
}
}
#[cfg(feature = "notify")]
fn faucet_error_kind(err: &FaucetError) -> &'static str {
match err {
FaucetError::Config(_) => "config",
FaucetError::Source(_) => "source",
FaucetError::Sink(_) => "sink",
FaucetError::State(_) => "state",
FaucetError::QualityFailure { .. } => "quality",
FaucetError::SchemaDrift { .. } => "schema_drift",
_ => "error",
}
}
pub(crate) fn resolve_now_inplace(
value: &mut Value,
clock: DateTime<FixedOffset>,
) -> CliResult<()> {
match value {
Value::String(s) => {
*s = crate::interpolate::resolve_now(s, clock)?;
Ok(())
}
Value::Array(a) => a.iter_mut().try_for_each(|v| resolve_now_inplace(v, clock)),
Value::Object(m) => m
.values_mut()
.try_for_each(|v| resolve_now_inplace(v, clock)),
_ => Ok(()),
}
}
fn resolve_inplace(value: &mut Value, ctx: &HashMap<String, Value>) -> CliResult<()> {
match value {
Value::String(s) => {
let resolved = interpolate_record(s, ctx)?;
*s = resolved;
Ok(())
}
Value::Array(a) => a.iter_mut().try_for_each(|v| resolve_inplace(v, ctx)),
Value::Object(m) => m.values_mut().try_for_each(|v| resolve_inplace(v, ctx)),
_ => Ok(()),
}
}
struct StateKeyOverride {
inner: Box<dyn Source>,
key: String,
}
#[async_trait]
impl Source for StateKeyOverride {
async fn fetch_with_context(
&self,
ctx: &HashMap<String, Value>,
) -> Result<Vec<Value>, FaucetError> {
self.inner.fetch_with_context(ctx).await
}
async fn fetch_with_context_incremental(
&self,
ctx: &HashMap<String, Value>,
) -> Result<(Vec<Value>, Option<Value>), FaucetError> {
self.inner.fetch_with_context_incremental(ctx).await
}
fn stream_pages<'a>(
&'a self,
ctx: &'a HashMap<String, Value>,
batch_size: usize,
) -> std::pin::Pin<
Box<
dyn faucet_core::Stream<Item = Result<faucet_core::StreamPage, FaucetError>>
+ Send
+ 'a,
>,
> {
self.inner.stream_pages(ctx, batch_size)
}
fn connector_name(&self) -> &'static str {
self.inner.connector_name()
}
fn dataset_uri(&self) -> String {
self.inner.dataset_uri()
}
fn state_key(&self) -> Option<String> {
Some(self.key.clone())
}
async fn apply_start_bookmark(&self, bookmark: Value) -> Result<(), FaucetError> {
self.inner.apply_start_bookmark(bookmark).await
}
fn supports_exactly_once(&self) -> bool {
self.inner.supports_exactly_once()
}
fn replay_guarantee(&self) -> faucet_core::ReplayGuarantee {
self.inner.replay_guarantee()
}
async fn capture_resume_position(&self) -> Result<Option<Value>, FaucetError> {
self.inner.capture_resume_position().await
}
}
struct CapturingSink {
inner: Box<dyn Sink>,
captured: Arc<Mutex<Vec<Value>>>,
projection: Arc<Projection>,
}
impl CapturingSink {
fn wrap(
inner: Box<dyn Sink>,
captured: Arc<Mutex<Vec<Value>>>,
projection: Arc<Projection>,
) -> Self {
Self {
inner,
captured,
projection,
}
}
}
#[async_trait]
impl Sink for CapturingSink {
fn connector_name(&self) -> &'static str {
self.inner.connector_name()
}
fn dataset_uri(&self) -> String {
self.inner.dataset_uri()
}
async fn write_batch(&self, records: &[Value]) -> Result<usize, FaucetError> {
let written = self.inner.write_batch(records).await?;
let n = written.min(records.len());
let mut buf = self.captured.lock().await;
buf.extend(
records
.iter()
.take(n)
.map(|r| project_record(r, &self.projection)),
);
Ok(written)
}
async fn flush(&self) -> Result<(), FaucetError> {
self.inner.flush().await
}
fn supports_idempotent_writes(&self) -> bool {
self.inner.supports_idempotent_writes()
}
fn sink_guarantee(&self) -> faucet_core::SinkGuarantee {
self.inner.sink_guarantee()
}
fn dedups_by_key(&self) -> bool {
self.inner.dedups_by_key()
}
fn supported_write_modes(&self) -> &'static [faucet_core::WriteMode] {
self.inner.supported_write_modes()
}
async fn write_batch_idempotent(
&self,
records: &[Value],
scope: &str,
token: &str,
) -> Result<usize, FaucetError> {
let written = self
.inner
.write_batch_idempotent(records, scope, token)
.await?;
let n = written.min(records.len());
let mut buf = self.captured.lock().await;
buf.extend(
records
.iter()
.take(n)
.map(|r| project_record(r, &self.projection)),
);
Ok(written)
}
async fn last_committed_token(&self, scope: &str) -> Result<Option<String>, FaucetError> {
self.inner.last_committed_token(scope).await
}
async fn current_schema(&self) -> Result<Option<Value>, FaucetError> {
self.inner.current_schema().await
}
fn supports_schema_evolution(&self) -> bool {
self.inner.supports_schema_evolution()
}
async fn evolve_schema(
&self,
evolution: &faucet_core::SchemaEvolution,
) -> Result<(), FaucetError> {
self.inner.evolve_schema(evolution).await
}
}
struct LimitedSink {
inner: Box<dyn Sink>,
remaining: AtomicUsize,
}
impl LimitedSink {
fn wrap(inner: Box<dyn Sink>, cap: usize) -> Self {
Self {
inner,
remaining: AtomicUsize::new(cap),
}
}
}
#[async_trait]
impl Sink for LimitedSink {
fn connector_name(&self) -> &'static str {
self.inner.connector_name()
}
fn dataset_uri(&self) -> String {
self.inner.dataset_uri()
}
async fn write_batch(&self, records: &[Value]) -> Result<usize, FaucetError> {
let remaining = self.remaining.load(Ordering::Relaxed);
if remaining == 0 {
return Ok(0);
}
let take = remaining.min(records.len());
let slice = &records[..take];
let written = self.inner.write_batch(slice).await?;
self.remaining
.fetch_sub(written.min(remaining), Ordering::Relaxed);
Ok(written)
}
async fn flush(&self) -> Result<(), FaucetError> {
self.inner.flush().await
}
}
struct CountingSink {
seen: AtomicUsize,
}
impl CountingSink {
fn new() -> Self {
Self {
seen: AtomicUsize::new(0),
}
}
}
#[async_trait]
impl Sink for CountingSink {
fn connector_name(&self) -> &'static str {
"dry-run"
}
async fn write_batch(&self, records: &[Value]) -> Result<usize, FaucetError> {
self.seen.fetch_add(records.len(), Ordering::Relaxed);
Ok(records.len())
}
}
fn value_to_string_brief(v: &Value) -> String {
match v {
Value::String(s) => s.clone(),
other => other.to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::{ConnectorSpec, PipelineConfig, PipelineSpec};
use crate::expand::expand;
use serde_json::json;
fn cfg_csv_to_jsonl(input: &Path, output: &Path) -> PipelineConfig {
PipelineConfig {
version: 1,
name: Some("test".into()),
vars: None,
auth: None,
pipeline: PipelineSpec {
source: Some(ConnectorSpec {
kind: "csv".into(),
config: json!({"path": input.to_str().unwrap()}),
transforms: None,
inherit_transforms: true,
}),
sink: Some(ConnectorSpec {
kind: "jsonl".into(),
config: json!({"path": output.to_str().unwrap()}),
transforms: None,
inherit_transforms: true,
}),
sources: Default::default(),
sinks: Default::default(),
transforms: Vec::new(),
state: None,
dlq: None,
#[cfg(feature = "quality")]
quality: None,
#[cfg(feature = "contract")]
contract: None,
#[cfg(feature = "masking")]
masking: None,
schema: None,
},
matrix: Vec::new(),
execution: None,
observability: None,
delivery: faucet_core::DeliveryMode::default(),
resilience: None,
sla: None,
shard: None,
replication: None,
#[cfg(feature = "schedule")]
schedule: None,
#[cfg(feature = "lineage")]
lineage: None,
#[cfg(feature = "catalog")]
catalog: None,
#[cfg(feature = "notify")]
notifications: Vec::new(),
}
}
#[tokio::test]
async fn empty_matrix_runs_pipeline_once() {
let dir = tempfile::tempdir().unwrap();
let input = dir.path().join("in.csv");
let output = dir.path().join("out.jsonl");
std::fs::write(&input, "name\nalice\nbob\n").unwrap();
let cfg = cfg_csv_to_jsonl(&input, &output);
let nodes = expand(&cfg).unwrap();
let summary = run_expanded(
nodes,
ExecuteOptions {
pipeline_name: "t".into(),
execution: None,
dry_run: false,
limit: None,
state_path_override: None,
shard: None,
auth: Default::default(),
clock: chrono::Utc::now().fixed_offset(),
cancel: None,
resilience: None,
sla: None,
#[cfg(feature = "lineage")]
lineage: None,
#[cfg(feature = "lineage")]
lineage_cfg: None,
#[cfg(feature = "notify")]
notifier: None,
#[cfg(feature = "catalog")]
catalog: None,
},
)
.await
.unwrap();
assert_eq!(summary.invocations.len(), 1);
assert_eq!(summary.invocations[0].records_written, 2);
assert!(!summary.had_failures());
let body = std::fs::read_to_string(&output).unwrap();
assert_eq!(body.lines().count(), 2);
}
#[cfg(feature = "catalog")]
fn opts_with_catalog(name: &str, handle: crate::catalog::CatalogHandle) -> ExecuteOptions {
let mut o = opts(name);
o.catalog = Some(handle);
o
}
#[cfg(feature = "catalog")]
#[tokio::test]
async fn catalog_records_schema_timeline_across_two_runs() {
use crate::catalog::CatalogHandle;
use crate::serve::history::RunHistory as _;
use crate::serve::history::catalog::{self, CatalogListFilter};
use crate::serve::history::memory::MemoryHistory;
let dir = tempfile::tempdir().unwrap();
let input = dir.path().join("in.csv");
let output = dir.path().join("out.jsonl");
let store = Arc::new(MemoryHistory::new(std::time::Duration::from_secs(60)));
let handle = CatalogHandle {
store: store.clone(),
run_id: None,
sample_records: 10,
};
std::fs::write(&input, "id,name\n1,alice\n2,bob\n").unwrap();
let cfg = cfg_csv_to_jsonl(&input, &output);
let nodes = expand(&cfg).unwrap();
let summary = run_expanded(nodes, opts_with_catalog("cat", handle.clone()))
.await
.unwrap();
assert!(!summary.had_failures());
std::fs::write(&input, "id,name,email\n1,alice,a@x.io\n2,bob,b@x.io\n").unwrap();
let nodes = expand(&cfg).unwrap();
let summary = run_expanded(nodes, opts_with_catalog("cat", handle))
.await
.unwrap();
assert!(!summary.had_failures());
let page = store
.catalog_list_datasets(&CatalogListFilter {
limit: 10,
..Default::default()
})
.await
.unwrap();
assert_eq!(page.datasets.len(), 2, "source + sink datasets");
for ds in &page.datasets {
let detail = store
.catalog_get_dataset(&ds.id)
.await
.unwrap()
.expect("dataset detail");
assert_eq!(detail.dataset.runs, 2);
assert_eq!(
detail.schema_timeline.len(),
2,
"exactly two timeline entries for {}",
ds.uri
);
assert!(detail.schema_timeline[0].diff.is_none());
let diff = detail.schema_timeline[1]
.diff
.as_ref()
.expect("second version carries a diff");
assert!(
diff["added"]
.as_array()
.unwrap()
.iter()
.any(|c| c["column"] == "email"),
"diff must show the added email column: {diff}"
);
assert_eq!(detail.stats.len(), 2, "one volume point per run");
}
let edges = store.catalog_lineage(None, 5).await.unwrap();
assert_eq!(edges.len(), 1);
assert_eq!(edges[0].runs, 2);
assert_eq!(edges[0].last_records, 2);
assert_eq!(edges[0].src_id, catalog::dataset_id(&edges[0].src_uri));
}
#[cfg(feature = "catalog")]
struct FailingCatalogStore;
#[cfg(feature = "catalog")]
#[async_trait]
impl crate::serve::history::RunHistory for FailingCatalogStore {
async fn claim_idempotency(
&self,
_: &str,
_: &str,
_: &str,
_: std::time::Duration,
) -> Result<crate::serve::history::Claim, crate::serve::history::HistoryError> {
Err(crate::serve::history::HistoryError::Backend("down".into()))
}
async fn upsert(
&self,
_: &crate::serve::history::RunRecord,
) -> Result<(), crate::serve::history::HistoryError> {
Err(crate::serve::history::HistoryError::Backend("down".into()))
}
async fn get(
&self,
_: &str,
) -> Result<Option<crate::serve::history::RunRecord>, crate::serve::history::HistoryError>
{
Err(crate::serve::history::HistoryError::Backend("down".into()))
}
async fn list(
&self,
_: &crate::serve::history::ListFilter,
) -> Result<crate::serve::history::ListPage, crate::serve::history::HistoryError> {
Err(crate::serve::history::HistoryError::Backend("down".into()))
}
async fn delete(
&self,
_: &str,
) -> Result<crate::serve::history::DeleteOutcome, crate::serve::history::HistoryError>
{
Err(crate::serve::history::HistoryError::Backend("down".into()))
}
async fn purge_expired(
&self,
_: std::time::Duration,
) -> Result<usize, crate::serve::history::HistoryError> {
Err(crate::serve::history::HistoryError::Backend("down".into()))
}
async fn recover_orphans(&self) -> Result<usize, crate::serve::history::HistoryError> {
Err(crate::serve::history::HistoryError::Backend("down".into()))
}
async fn catalog_record(
&self,
_: &crate::serve::history::catalog::CatalogUpdate,
) -> Result<(), crate::serve::history::HistoryError> {
Err(crate::serve::history::HistoryError::Backend(
"catalog write refused".into(),
))
}
fn degraded(&self) -> bool {
false
}
}
#[cfg(feature = "catalog")]
#[tokio::test]
async fn catalog_write_failure_never_fails_the_run() {
use crate::catalog::CatalogHandle;
let dir = tempfile::tempdir().unwrap();
let input = dir.path().join("in.csv");
let output = dir.path().join("out.jsonl");
std::fs::write(&input, "name\nalice\n").unwrap();
let cfg = cfg_csv_to_jsonl(&input, &output);
let nodes = expand(&cfg).unwrap();
let handle = CatalogHandle {
store: Arc::new(FailingCatalogStore),
run_id: None,
sample_records: 10,
};
let summary = run_expanded(nodes, opts_with_catalog("cat-fail", handle))
.await
.unwrap();
assert!(
!summary.had_failures(),
"catalog failure must not fail the run"
);
assert_eq!(summary.invocations[0].records_written, 1);
assert_eq!(
std::fs::read_to_string(&output).unwrap().lines().count(),
1,
"sink output written despite the catalog error"
);
}
#[tokio::test]
async fn matrix_two_independent_roots_both_run() {
let dir = tempfile::tempdir().unwrap();
let csv_a = dir.path().join("a.csv");
let csv_b = dir.path().join("b.csv");
let out_a = dir.path().join("a.jsonl");
let out_b = dir.path().join("b.jsonl");
std::fs::write(&csv_a, "name\nalice\n").unwrap();
std::fs::write(&csv_b, "name\nbob\n").unwrap();
let yaml = format!(
r#"version: 1
pipeline:
source: {{ type: csv, config: {{ path: {a} }} }}
sink: {{ type: jsonl, config: {{ path: {out_a} }} }}
matrix:
- id: rowA
- id: rowB
source: {{ config: {{ path: {b} }} }}
sink: {{ config: {{ path: {out_b} }} }}
"#,
a = csv_a.display(),
b = csv_b.display(),
out_a = out_a.display(),
out_b = out_b.display(),
);
let cfg = crate::config::parse_with_extension(&yaml, "yaml").unwrap();
let nodes = expand(&cfg).unwrap();
let summary = run_expanded(
nodes,
ExecuteOptions {
pipeline_name: "matrix".into(),
execution: None,
dry_run: false,
limit: None,
state_path_override: None,
shard: None,
auth: Default::default(),
clock: chrono::Utc::now().fixed_offset(),
cancel: None,
resilience: None,
sla: None,
#[cfg(feature = "lineage")]
lineage: None,
#[cfg(feature = "lineage")]
lineage_cfg: None,
#[cfg(feature = "notify")]
notifier: None,
#[cfg(feature = "catalog")]
catalog: None,
},
)
.await
.unwrap();
assert_eq!(summary.invocations.len(), 2);
assert!(out_a.exists());
assert!(out_b.exists());
}
#[tokio::test]
async fn dag_child_fans_out_per_parent_record() {
let dir = tempfile::tempdir().unwrap();
let parent_csv = dir.path().join("parents.csv");
let child_csv = dir.path().join("child.csv");
std::fs::write(&parent_csv, "id,name\n1,alice\n2,bob\n").unwrap();
std::fs::write(&child_csv, "x\nA\nB\nC\n").unwrap();
let parent_out = dir.path().join("parents.jsonl");
let child_out_pattern = dir.path().join("child-${parents.id}.jsonl");
let yaml = format!(
r#"version: 1
pipeline:
source: {{ type: csv, config: {{ path: {parent} }} }}
sink: {{ type: jsonl, config: {{ path: {parent_out} }} }}
matrix:
- id: parents
- id: child
parent: parents
source: {{ config: {{ path: {child} }} }}
sink: {{ config: {{ path: "{child_out}" }} }}
"#,
parent = parent_csv.display(),
parent_out = parent_out.display(),
child = child_csv.display(),
child_out = child_out_pattern.display(),
);
let cfg = crate::config::parse_with_extension(&yaml, "yaml").unwrap();
let nodes = expand(&cfg).unwrap();
let summary = run_expanded(
nodes,
ExecuteOptions {
pipeline_name: "dagtest".into(),
execution: None,
dry_run: false,
limit: None,
state_path_override: None,
shard: None,
auth: Default::default(),
clock: chrono::Utc::now().fixed_offset(),
cancel: None,
resilience: None,
sla: None,
#[cfg(feature = "lineage")]
lineage: None,
#[cfg(feature = "lineage")]
lineage_cfg: None,
#[cfg(feature = "notify")]
notifier: None,
#[cfg(feature = "catalog")]
catalog: None,
},
)
.await
.unwrap();
assert_eq!(summary.invocations.len(), 3);
assert!(!summary.had_failures(), "{:?}", summary);
assert!(dir.path().join("child-1.jsonl").exists());
assert!(dir.path().join("child-2.jsonl").exists());
}
#[tokio::test]
async fn depends_on_root_runs_after_dependency() {
let dir = tempfile::tempdir().unwrap();
let input = dir.path().join("in.csv");
let mid = dir.path().join("mid.csv");
let out = dir.path().join("out.jsonl");
std::fs::write(&input, "name\nalice\nbob\n").unwrap();
let yaml = format!(
r#"version: 1
pipeline:
source: {{ type: csv, config: {{ path: {input} }} }}
sink: {{ type: jsonl, config: {{ path: {out} }} }}
matrix:
- id: stage
sink: {{ type: csv, config: {{ path: {mid} }} }}
- id: load
depends_on: [stage]
source: {{ config: {{ path: {mid} }} }}
"#,
input = input.display(),
mid = mid.display(),
out = out.display(),
);
let cfg = crate::config::parse_with_extension(&yaml, "yaml").unwrap();
let nodes = expand(&cfg).unwrap();
let summary = run_expanded(nodes, opts("depsorder")).await.unwrap();
assert_eq!(summary.invocations.len(), 2, "{summary:?}");
assert!(!summary.had_failures(), "{summary:?}");
let load = summary
.invocations
.iter()
.find(|i| i.row_id == "load")
.unwrap();
assert_eq!(load.records_written, 2);
let written = std::fs::read_to_string(&out).unwrap();
assert_eq!(written.lines().count(), 2);
}
#[tokio::test]
async fn diamond_dependency_waits_for_all_prerequisites() {
let dir = tempfile::tempdir().unwrap();
let input = dir.path().join("in.csv");
let mid_a = dir.path().join("mid_a.csv");
let mid_b = dir.path().join("mid_b.csv");
let out = dir.path().join("out.jsonl");
std::fs::write(&input, "name\nalice\n").unwrap();
let yaml = format!(
r#"version: 1
pipeline:
source: {{ type: csv, config: {{ path: {input} }} }}
sink: {{ type: jsonl, config: {{ path: {out} }} }}
matrix:
- id: a
sink: {{ type: csv, config: {{ path: {mid_a} }} }}
- id: b
sink: {{ type: csv, config: {{ path: {mid_b} }} }}
- id: c
depends_on: [a, b]
source: {{ config: {{ path: {mid_a} }} }}
"#,
input = input.display(),
mid_a = mid_a.display(),
mid_b = mid_b.display(),
out = out.display(),
);
let cfg = crate::config::parse_with_extension(&yaml, "yaml").unwrap();
let nodes = expand(&cfg).unwrap();
let summary = run_expanded(nodes, opts("diamond")).await.unwrap();
assert_eq!(summary.invocations.len(), 3, "{summary:?}");
assert!(!summary.had_failures(), "{summary:?}");
assert!(mid_b.exists(), "b must have run before c became ready");
assert!(out.exists());
}
#[tokio::test]
async fn failed_dependency_skips_dependent() {
let dir = tempfile::tempdir().unwrap();
let good_input = dir.path().join("good.csv");
let out = dir.path().join("out.jsonl");
std::fs::write(&good_input, "name\nalice\n").unwrap();
let yaml = format!(
r#"version: 1
pipeline:
source: {{ type: csv, config: {{ path: {good} }} }}
sink: {{ type: jsonl, config: {{ path: {out} }} }}
matrix:
- id: stage
source: {{ config: {{ path: {missing} }} }}
- id: load
depends_on: [stage]
"#,
good = good_input.display(),
missing = dir.path().join("nonexistent.csv").display(),
out = out.display(),
);
let cfg = crate::config::parse_with_extension(&yaml, "yaml").unwrap();
let nodes = expand(&cfg).unwrap();
let summary = run_expanded(nodes, opts("depskip")).await.unwrap();
assert_eq!(summary.invocations.len(), 1, "{summary:?}");
assert_eq!(summary.invocations[0].row_id, "stage");
assert!(summary.invocations[0].error.is_some());
assert!(
!out.exists(),
"dependent row must not run after its dependency failed"
);
}
#[tokio::test]
async fn dependency_on_skipped_row_cascades() {
let dir = tempfile::tempdir().unwrap();
let good_input = dir.path().join("good.csv");
let out = dir.path().join("q.jsonl");
std::fs::write(&good_input, "id\n1\n").unwrap();
let yaml = format!(
r#"version: 1
pipeline:
source: {{ type: csv, config: {{ path: {good} }} }}
sink: {{ type: jsonl, config: {{ path: {out} }} }}
matrix:
- id: p
source: {{ config: {{ path: {missing} }} }}
- id: c
parent: p
- id: q
depends_on: [c]
"#,
good = good_input.display(),
missing = dir.path().join("nonexistent.csv").display(),
out = out.display(),
);
let cfg = crate::config::parse_with_extension(&yaml, "yaml").unwrap();
let nodes = expand(&cfg).unwrap();
let summary = run_expanded(nodes, opts("depcascade")).await.unwrap();
assert_eq!(summary.invocations.len(), 1, "{summary:?}");
assert_eq!(summary.invocations[0].row_id, "p");
assert!(summary.invocations[0].error.is_some());
assert!(
!out.exists(),
"q must be skipped when its dependency was skipped"
);
}
#[tokio::test]
async fn on_error_stop_reports_failure_and_runs_no_extra_work() {
let dir = tempfile::tempdir().unwrap();
let good_csv = dir.path().join("good.csv");
std::fs::write(&good_csv, "x\n1\n").unwrap();
let good_out = dir.path().join("good.jsonl");
let bad_sink_dir = dir.path().to_path_buf();
let yaml = format!(
r#"version: 1
pipeline:
source: {{ type: csv, config: {{ path: {good_csv} }} }}
sink: {{ type: jsonl, config: {{ path: {good_out} }} }}
matrix:
- id: bad
sink: {{ config: {{ path: {bad_dir} }} }}
- id: good
execution:
max_concurrent: 1
on_error: stop
"#,
good_csv = good_csv.display(),
good_out = good_out.display(),
bad_dir = bad_sink_dir.display(),
);
let cfg = crate::config::parse_with_extension(&yaml, "yaml").unwrap();
let nodes = expand(&cfg).unwrap();
let summary = run_expanded(
nodes,
ExecuteOptions {
pipeline_name: "stoptest".into(),
execution: cfg.execution.clone(),
dry_run: false,
limit: None,
state_path_override: None,
shard: None,
auth: Default::default(),
clock: chrono::Utc::now().fixed_offset(),
cancel: None,
resilience: None,
sla: None,
#[cfg(feature = "lineage")]
lineage: None,
#[cfg(feature = "lineage")]
lineage_cfg: None,
#[cfg(feature = "notify")]
notifier: None,
#[cfg(feature = "catalog")]
catalog: None,
},
)
.await
.unwrap();
assert!(summary.had_failures(), "the failing root must be reported");
let bad: Vec<_> = summary
.invocations
.iter()
.filter(|o| o.row_id == "bad")
.collect();
assert_eq!(bad.len(), 1, "bad must run exactly once");
assert!(bad[0].error.is_some(), "bad must be recorded as a failure");
assert!(
summary.invocations.len() <= 2,
"at most the two roots may run, got {:?}",
summary.invocations
);
let good_wrote = summary
.invocations
.iter()
.find(|o| o.row_id == "good" && o.error.is_none())
.map(|o| o.records_written)
.unwrap_or(0);
if good_wrote > 0 {
assert!(
good_out.exists(),
"a good that wrote records must have produced its output file"
);
}
}
#[tokio::test]
async fn invalid_pipeline_name_with_state_errors_up_front() {
let dir = tempfile::tempdir().unwrap();
let input = dir.path().join("in.csv");
let output = dir.path().join("out.jsonl");
std::fs::write(&input, "name\nalice\n").unwrap();
let yaml = format!(
r#"version: 1
pipeline:
source: {{ type: csv, config: {{ path: {input} }} }}
sink: {{ type: jsonl, config: {{ path: {output} }} }}
state: {{ type: memory }}
"#,
input = input.display(),
output = output.display(),
);
let cfg = crate::config::parse_with_extension(&yaml, "yaml").unwrap();
let nodes = expand(&cfg).unwrap();
let err = run_expanded(
nodes,
ExecuteOptions {
pipeline_name: "bad name".into(), execution: None,
dry_run: false,
limit: None,
state_path_override: None,
shard: None,
auth: Default::default(),
clock: chrono::Utc::now().fixed_offset(),
cancel: None,
resilience: None,
sla: None,
#[cfg(feature = "lineage")]
lineage: None,
#[cfg(feature = "lineage")]
lineage_cfg: None,
#[cfg(feature = "notify")]
notifier: None,
#[cfg(feature = "catalog")]
catalog: None,
},
)
.await
.expect_err("an invalid pipeline name must be rejected up front when state is configured");
assert!(matches!(err, CliError::InvalidStateKey { .. }), "{err:?}");
}
#[tokio::test]
async fn invalid_parent_key_value_with_state_errors_up_front() {
let dir = tempfile::tempdir().unwrap();
let parent_csv = dir.path().join("parents.csv");
let child_csv = dir.path().join("child.csv");
std::fs::write(&parent_csv, "id\nbad id\n").unwrap();
std::fs::write(&child_csv, "x\nA\n").unwrap();
let parent_out = dir.path().join("parents.jsonl");
let child_out = dir.path().join("child.jsonl");
let yaml = format!(
r#"version: 1
pipeline:
source: {{ type: csv, config: {{ path: {parent} }} }}
sink: {{ type: jsonl, config: {{ path: {parent_out} }} }}
state: {{ type: memory }}
matrix:
- id: parents
- id: child
parent: parents
source: {{ config: {{ path: {child} }} }}
sink: {{ config: {{ path: {child_out} }} }}
"#,
parent = parent_csv.display(),
parent_out = parent_out.display(),
child = child_csv.display(),
child_out = child_out.display(),
);
let cfg = crate::config::parse_with_extension(&yaml, "yaml").unwrap();
let nodes = expand(&cfg).unwrap();
let err = run_expanded(
nodes,
ExecuteOptions {
pipeline_name: "ok".into(),
execution: None,
dry_run: false,
limit: None,
state_path_override: None,
shard: None,
auth: Default::default(),
clock: chrono::Utc::now().fixed_offset(),
cancel: None,
resilience: None,
sla: None,
#[cfg(feature = "lineage")]
lineage: None,
#[cfg(feature = "lineage")]
lineage_cfg: None,
#[cfg(feature = "notify")]
notifier: None,
#[cfg(feature = "catalog")]
catalog: None,
},
)
.await
.expect_err(
"an illegal parent-key value must be rejected up front when state is configured",
);
assert!(matches!(err, CliError::InvalidStateKey { .. }), "{err:?}");
}
#[tokio::test]
async fn on_error_stop_under_parallelism_aborts_other_in_flight() {
let dir = tempfile::tempdir().unwrap();
let bad_sink_dir = dir.path().to_path_buf();
let good_csv = dir.path().join("good.csv");
std::fs::write(&good_csv, "x\n1\n").unwrap();
let yaml = format!(
r#"version: 1
pipeline:
source: {{ type: csv, config: {{ path: {good_csv} }} }}
sink: {{ type: jsonl, config: {{ path: {bad_dir} }} }}
matrix:
- id: bad
- id: good_a
- id: good_b
execution:
max_concurrent: 3
on_error: stop
"#,
good_csv = good_csv.display(),
bad_dir = bad_sink_dir.display(),
);
let cfg = crate::config::parse_with_extension(&yaml, "yaml").unwrap();
let nodes = expand(&cfg).unwrap();
let summary = run_expanded(
nodes,
ExecuteOptions {
pipeline_name: "stop_parallel".into(),
execution: cfg.execution.clone(),
dry_run: false,
limit: None,
state_path_override: None,
shard: None,
auth: Default::default(),
clock: chrono::Utc::now().fixed_offset(),
cancel: None,
resilience: None,
sla: None,
#[cfg(feature = "lineage")]
lineage: None,
#[cfg(feature = "lineage")]
lineage_cfg: None,
#[cfg(feature = "notify")]
notifier: None,
#[cfg(feature = "catalog")]
catalog: None,
},
)
.await
.unwrap();
assert!(
summary.had_failures(),
"summary should record at least one failure: {summary:?}"
);
assert!(
summary.invocations[0].error.is_some(),
"first outcome must be the failure that triggered stop: {summary:?}"
);
for inv in &summary.invocations {
assert_eq!(inv.records_written, 0, "no records should land: {inv:?}");
}
}
#[tokio::test]
async fn on_error_continue_skips_failed_subtree_only() {
let dir = tempfile::tempdir().unwrap();
let good_csv = dir.path().join("good.csv");
std::fs::write(&good_csv, "x\n1\n").unwrap();
let good_out = dir.path().join("good.jsonl");
let yaml = format!(
r#"version: 1
pipeline:
source: {{ type: csv, config: {{ path: {good_csv} }} }}
sink: {{ type: jsonl, config: {{ path: {good_out} }} }}
matrix:
- id: bad
sink: {{ config: {{ path: {bad_dir} }} }}
- id: good
"#,
good_csv = good_csv.display(),
good_out = good_out.display(),
bad_dir = dir.path().display(),
);
let cfg = crate::config::parse_with_extension(&yaml, "yaml").unwrap();
let nodes = expand(&cfg).unwrap();
let summary = run_expanded(
nodes,
ExecuteOptions {
pipeline_name: "continuetest".into(),
execution: None,
dry_run: false,
limit: None,
state_path_override: None,
shard: None,
auth: Default::default(),
clock: chrono::Utc::now().fixed_offset(),
cancel: None,
resilience: None,
sla: None,
#[cfg(feature = "lineage")]
lineage: None,
#[cfg(feature = "lineage")]
lineage_cfg: None,
#[cfg(feature = "notify")]
notifier: None,
#[cfg(feature = "catalog")]
catalog: None,
},
)
.await
.unwrap();
assert_eq!(summary.invocations.len(), 2);
assert_eq!(summary.failure_count(), 1);
let good_outcome = summary
.invocations
.iter()
.find(|i| i.row_id == "good")
.unwrap();
assert!(good_outcome.error.is_none());
}
#[test]
fn split_path_splits_on_dots() {
assert_eq!(split_path("id"), vec!["id".to_string()]);
assert_eq!(
split_path("user.name"),
vec!["user".to_string(), "name".to_string()]
);
}
#[test]
fn minimal_paths_drops_descendants_of_kept_ancestors() {
let paths = vec![
vec!["user".into(), "name".into()],
vec!["user".into()],
vec!["id".into()],
vec!["id".into()],
];
let min = minimal_paths(paths);
assert!(min.contains(&vec!["user".to_string()]));
assert!(min.contains(&vec!["id".to_string()]));
assert!(
!min.contains(&vec!["user".to_string(), "name".to_string()]),
"user.name must be dropped — covered by user"
);
assert_eq!(min.len(), 2);
}
#[test]
fn project_full_clones_whole_record() {
let r = json!({"a": 1, "b": {"c": 2}});
assert_eq!(project_record(&r, &Projection::Full), r);
}
#[test]
fn project_keeps_only_referenced_paths() {
let r = json!({"id": 7, "user": {"name": "a", "age": 3}, "blob": "<huge>"});
let p = Projection::Paths(vec![vec!["id".into()], vec!["user".into(), "name".into()]]);
let got = project_record(&r, &p);
assert_eq!(got, json!({"id": 7, "user": {"name": "a"}}));
assert!(got.get("blob").is_none());
assert!(got["user"].get("age").is_none());
}
#[test]
fn project_array_index_path_resolves_same_as_original() {
let r = json!({"tags": ["x", "y", "z"]});
let p = Projection::Paths(vec![vec!["tags".into(), "0".into()]]);
let got = project_record(&r, &p);
assert_eq!(got, json!({"tags": {"0": "x"}}));
assert_eq!(resolve_parent_key(&got, "tags.0"), Some(json!("x")));
assert_eq!(
resolve_parent_key(&got, "tags.0"),
resolve_parent_key(&r, "tags.0"),
"reduced tree must resolve the same value as the original"
);
}
#[test]
fn project_numeric_object_key_resolves_same_as_original() {
let r = json!({"data": {"0": "x", "1": "y"}});
let p = Projection::Paths(vec![vec!["data".into(), "0".into()]]);
let got = project_record(&r, &p);
assert_eq!(got, json!({"data": {"0": "x"}}));
assert_eq!(
resolve_parent_key(&got, "data.0"),
resolve_parent_key(&r, "data.0"),
"numeric object-key path must resolve identically on the reduced tree"
);
}
#[test]
fn project_missing_path_is_omitted() {
let r = json!({"id": 1});
let p = Projection::Paths(vec![vec!["nope".into()]]);
assert_eq!(project_record(&r, &p), json!({}));
}
#[test]
fn build_projections_unions_parent_key_and_refs() {
use crate::config::ConnectorSpec;
use crate::expand::{DeferredRef, ExpandedNode, NodeRole};
fn child(id: &str, parent: &str, parent_key: &str, refs: &[(&str, &str)]) -> ExpandedNode {
ExpandedNode {
id: id.into(),
row_index: 0,
role: NodeRole::Child {
parent_id: parent.into(),
parent_key: parent_key.into(),
},
source: ConnectorSpec {
kind: "csv".into(),
config: json!({}),
transforms: None,
inherit_transforms: true,
},
sink: ConnectorSpec {
kind: "jsonl".into(),
config: json!({}),
transforms: None,
inherit_transforms: true,
},
transforms: Vec::new(),
state: None,
dlq: None,
delivery: faucet_core::DeliveryMode::AtLeastOnce,
delivery_guarantee: faucet_core::DeliveryGuarantee::AtLeastOnce,
#[cfg(feature = "quality")]
quality: None,
#[cfg(feature = "contract")]
contract: None,
#[cfg(feature = "masking")]
masking: None,
sink_ref: "default".into(),
schema: None,
depends_on: Vec::new(),
deferred_refs: refs
.iter()
.map(|(rid, p)| DeferredRef {
referenced_id: (*rid).into(),
dotted_path: (*p).into(),
token: format!("${{{rid}.{p}}}"),
})
.collect(),
source_override: None,
}
}
let c1 = child("c1", "p", "id", &[("p", "user.name")]);
let c2 = child("c2", "p", "id", &[("p", "email"), ("q", "x")]);
let nodes_by_id = HashMap::from([("c1".to_string(), c1), ("c2".to_string(), c2)]);
let children_of =
HashMap::from([("p".to_string(), vec!["c1".to_string(), "c2".to_string()])]);
let projs = build_projections(&nodes_by_id, &children_of);
let p = projs.get("p").expect("projection for p");
match &**p {
Projection::Paths(paths) => {
assert!(paths.contains(&vec!["id".to_string()]));
assert!(paths.contains(&vec!["user".to_string(), "name".to_string()]));
assert!(paths.contains(&vec!["email".to_string()]));
assert!(
!paths.iter().any(|p| p == &vec!["x".to_string()]),
"a ref to a different parent must not be captured under p"
);
}
Projection::Full => panic!("expected Paths, got Full"),
}
}
#[test]
fn build_projections_whole_record_ref_is_full() {
use crate::config::ConnectorSpec;
use crate::expand::{DeferredRef, ExpandedNode, NodeRole};
let c = ExpandedNode {
id: "c".into(),
row_index: 0,
role: NodeRole::Child {
parent_id: "p".into(),
parent_key: "id".into(),
},
source: ConnectorSpec {
kind: "csv".into(),
config: json!({}),
transforms: None,
inherit_transforms: true,
},
sink: ConnectorSpec {
kind: "jsonl".into(),
config: json!({}),
transforms: None,
inherit_transforms: true,
},
transforms: Vec::new(),
state: None,
dlq: None,
delivery: faucet_core::DeliveryMode::AtLeastOnce,
delivery_guarantee: faucet_core::DeliveryGuarantee::AtLeastOnce,
#[cfg(feature = "quality")]
quality: None,
#[cfg(feature = "contract")]
contract: None,
#[cfg(feature = "masking")]
masking: None,
sink_ref: "default".into(),
schema: None,
depends_on: Vec::new(),
deferred_refs: vec![DeferredRef {
referenced_id: "p".into(),
dotted_path: "".into(),
token: "${p}".into(),
}],
source_override: None,
};
let nodes_by_id = HashMap::from([("c".to_string(), c)]);
let children_of = HashMap::from([("p".to_string(), vec!["c".to_string()])]);
let projs = build_projections(&nodes_by_id, &children_of);
assert!(matches!(&**projs.get("p").unwrap(), Projection::Full));
}
fn opts(name: &str) -> ExecuteOptions {
ExecuteOptions {
pipeline_name: name.into(),
execution: None,
dry_run: false,
limit: None,
state_path_override: None,
shard: None,
auth: Default::default(),
clock: chrono::Utc::now().fixed_offset(),
cancel: None,
resilience: None,
sla: None,
#[cfg(feature = "lineage")]
lineage: None,
#[cfg(feature = "lineage")]
lineage_cfg: None,
#[cfg(feature = "notify")]
notifier: None,
#[cfg(feature = "catalog")]
catalog: None,
}
}
#[tokio::test]
async fn dry_run_counts_records_without_writing_sink_file() {
let dir = tempfile::tempdir().unwrap();
let input = dir.path().join("in.csv");
let output = dir.path().join("out.jsonl");
std::fs::write(&input, "name\nalice\nbob\ncarol\n").unwrap();
let cfg = cfg_csv_to_jsonl(&input, &output);
let nodes = expand(&cfg).unwrap();
let mut o = opts("dry");
o.dry_run = true;
let summary = run_expanded(nodes, o).await.unwrap();
assert_eq!(summary.invocations.len(), 1);
assert_eq!(summary.invocations[0].records_written, 3);
assert!(!summary.had_failures());
assert!(
!output.exists(),
"dry-run must not create the real sink file"
);
}
#[tokio::test]
async fn limit_caps_records_written_across_the_run() {
let dir = tempfile::tempdir().unwrap();
let input = dir.path().join("in.csv");
let output = dir.path().join("out.jsonl");
std::fs::write(&input, "name\na\nb\nc\nd\ne\n").unwrap();
let cfg = cfg_csv_to_jsonl(&input, &output);
let nodes = expand(&cfg).unwrap();
let mut o = opts("lim");
o.limit = Some(2);
let summary = run_expanded(nodes, o).await.unwrap();
assert_eq!(summary.invocations[0].records_written, 2);
let body = std::fs::read_to_string(&output).unwrap();
assert_eq!(body.lines().count(), 2, "only the first 2 rows are written");
}
#[tokio::test]
async fn duplicate_state_key_among_siblings_is_rejected() {
let dir = tempfile::tempdir().unwrap();
let parent_csv = dir.path().join("parents.csv");
let child_csv = dir.path().join("child.csv");
std::fs::write(&parent_csv, "id\ndup\ndup\n").unwrap();
std::fs::write(&child_csv, "x\nA\n").unwrap();
let parent_out = dir.path().join("parents.jsonl");
let child_out = dir.path().join("child.jsonl");
let yaml = format!(
r#"version: 1
pipeline:
source: {{ type: csv, config: {{ path: {parent} }} }}
sink: {{ type: jsonl, config: {{ path: {parent_out} }} }}
state: {{ type: memory }}
matrix:
- id: parents
- id: child
parent: parents
source: {{ config: {{ path: {child} }} }}
sink: {{ config: {{ path: {child_out} }} }}
"#,
parent = parent_csv.display(),
parent_out = parent_out.display(),
child = child_csv.display(),
child_out = child_out.display(),
);
let cfg = crate::config::parse_with_extension(&yaml, "yaml").unwrap();
let nodes = expand(&cfg).unwrap();
let err = run_expanded(nodes, opts("dupkey"))
.await
.expect_err("colliding sibling state keys must be rejected");
match err {
CliError::DuplicateStateKey { id, state_key } => {
assert_eq!(id, "child");
assert_eq!(state_key, "dupkey::child::dup");
}
other => panic!("expected DuplicateStateKey, got {other:?}"),
}
}
#[tokio::test]
async fn state_path_override_writes_bookmark_file() {
let dir = tempfile::tempdir().unwrap();
let input = dir.path().join("in.csv");
let output = dir.path().join("out.jsonl");
let state_dir = dir.path().join("state");
std::fs::write(&input, "name\nalice\n").unwrap();
let cfg = cfg_csv_to_jsonl(&input, &output);
let nodes = expand(&cfg).unwrap();
let mut o = opts("statepath");
o.state_path_override = Some(state_dir.clone());
let summary = run_expanded(nodes, o).await.unwrap();
assert!(!summary.had_failures());
assert_eq!(summary.invocations[0].records_written, 1);
}
#[tokio::test]
async fn build_dlq_config_maps_spec_fields() {
use crate::config::{ConnectorSpec, DlqSpec, OnBatchErrorSpec};
let dir = tempfile::tempdir().unwrap();
let dlq_out = dir.path().join("dlq.jsonl");
let spec = DlqSpec {
sink: ConnectorSpec {
kind: "jsonl".into(),
config: json!({ "path": dlq_out.to_str().unwrap() }),
transforms: None,
inherit_transforms: true,
},
on_batch_error: OnBatchErrorSpec::DlqAll,
max_failures_per_page: Some(7),
max_failures_total: Some(42),
include_original_payload: false,
};
let cfg = build_dlq_config(&spec).await.unwrap();
assert!(matches!(cfg.on_batch_error, OnBatchError::DlqAll));
assert_eq!(cfg.max_failures_per_page, Some(7));
assert_eq!(cfg.max_failures_total, Some(42));
assert!(!cfg.include_original_payload);
}
#[tokio::test]
async fn build_state_for_node_arms() {
let dir = tempfile::tempdir().unwrap();
let node = stub_node(None);
assert!(build_state_for_node(&node, None).await.unwrap().is_none());
let p = dir.path().join("s1");
assert!(
build_state_for_node(&node, Some(&p))
.await
.unwrap()
.is_some()
);
let node_mem = stub_node(Some(crate::config::StateStoreSpec {
kind: "memory".into(),
config: json!({}),
}));
assert!(
build_state_for_node(&node_mem, None)
.await
.unwrap()
.is_some()
);
let node_file = stub_node(Some(crate::config::StateStoreSpec {
kind: "file".into(),
config: json!({ "path": dir.path().join("orig").to_str().unwrap() }),
}));
let p2 = dir.path().join("override2");
assert!(
build_state_for_node(&node_file, Some(&p2))
.await
.unwrap()
.is_some()
);
let node_mem2 = stub_node(Some(crate::config::StateStoreSpec {
kind: "memory".into(),
config: json!({}),
}));
let p3 = dir.path().join("override3");
assert!(
build_state_for_node(&node_mem2, Some(&p3))
.await
.unwrap()
.is_some()
);
}
fn stub_node(state: Option<crate::config::StateStoreSpec>) -> ExpandedNode {
use crate::config::ConnectorSpec;
ExpandedNode {
id: "n".into(),
row_index: 0,
role: NodeRole::Root,
source: ConnectorSpec {
kind: "csv".into(),
config: json!({}),
transforms: None,
inherit_transforms: true,
},
sink: ConnectorSpec {
kind: "jsonl".into(),
config: json!({}),
transforms: None,
inherit_transforms: true,
},
transforms: Vec::new(),
state,
dlq: None,
delivery: faucet_core::DeliveryMode::AtLeastOnce,
delivery_guarantee: faucet_core::DeliveryGuarantee::AtLeastOnce,
#[cfg(feature = "quality")]
quality: None,
#[cfg(feature = "contract")]
contract: None,
#[cfg(feature = "masking")]
masking: None,
sink_ref: "default".into(),
schema: None,
depends_on: Vec::new(),
deferred_refs: Vec::new(),
source_override: None,
}
}
#[tokio::test]
async fn state_key_override_delegates_and_overrides_key() {
let dir = tempfile::tempdir().unwrap();
let input = dir.path().join("in.csv");
std::fs::write(&input, "name\nz\n").unwrap();
let inner = build_source(
"csv",
json!({"path": input.to_str().unwrap()}),
&AuthCatalog::new(),
None,
)
.await
.unwrap();
let inner_name = inner.connector_name();
let ov = StateKeyOverride {
inner,
key: "my::custom::key".into(),
};
assert_eq!(ov.state_key(), Some("my::custom::key".to_string()));
assert_eq!(ov.connector_name(), inner_name);
let rows = ov.fetch_with_context(&HashMap::new()).await.unwrap();
assert_eq!(rows.len(), 1);
ov.apply_start_bookmark(json!({"any": "bookmark"}))
.await
.unwrap();
assert!(!ov.supports_exactly_once());
assert_eq!(
ov.replay_guarantee(),
faucet_core::ReplayGuarantee::NonDeterministic
);
assert_eq!(ov.capture_resume_position().await.unwrap(), None);
}
#[tokio::test]
async fn state_key_override_forwards_native_stream_pages() {
struct PerPageBookmarkSource;
#[async_trait]
impl Source for PerPageBookmarkSource {
async fn fetch_with_context(
&self,
_ctx: &HashMap<String, Value>,
) -> Result<Vec<Value>, FaucetError> {
Ok(vec![json!({"id": 1}), json!({"id": 2})])
}
fn stream_pages<'a>(
&'a self,
_ctx: &'a HashMap<String, Value>,
_batch_size: usize,
) -> std::pin::Pin<
Box<
dyn faucet_core::Stream<Item = Result<faucet_core::StreamPage, FaucetError>>
+ Send
+ 'a,
>,
> {
Box::pin(faucet_core::async_stream::try_stream! {
yield faucet_core::StreamPage {
records: vec![json!({"id": 1})],
bookmark: Some(json!("bm-1")),
};
yield faucet_core::StreamPage {
records: vec![json!({"id": 2})],
bookmark: Some(json!("bm-2")),
};
})
}
fn state_key(&self) -> Option<String> {
Some("native".into())
}
}
use futures::StreamExt;
let ov = StateKeyOverride {
inner: Box::new(PerPageBookmarkSource),
key: "override".into(),
};
let ctx = HashMap::new();
let pages: Vec<_> = ov
.stream_pages(&ctx, 1000)
.collect::<Vec<_>>()
.await
.into_iter()
.collect::<Result<Vec<_>, _>>()
.unwrap();
assert_eq!(pages.len(), 2, "native page boundaries survive the wrap");
assert_eq!(pages[0].bookmark, Some(json!("bm-1")));
assert_eq!(pages[1].bookmark, Some(json!("bm-2")));
}
#[tokio::test]
async fn capturing_sink_forwards_capabilities_and_captures_idempotent_writes() {
struct IdemSink;
#[async_trait]
impl Sink for IdemSink {
async fn write_batch(&self, records: &[Value]) -> Result<usize, FaucetError> {
Ok(records.len())
}
fn connector_name(&self) -> &'static str {
"idem"
}
fn supports_idempotent_writes(&self) -> bool {
true
}
fn dedups_by_key(&self) -> bool {
true
}
fn supported_write_modes(&self) -> &'static [faucet_core::WriteMode] {
&[
faucet_core::WriteMode::Append,
faucet_core::WriteMode::Upsert,
]
}
async fn write_batch_idempotent(
&self,
records: &[Value],
_scope: &str,
_token: &str,
) -> Result<usize, FaucetError> {
Ok(records.len())
}
async fn last_committed_token(
&self,
_scope: &str,
) -> Result<Option<String>, FaucetError> {
Ok(Some("tok".into()))
}
}
let captured = Arc::new(Mutex::new(Vec::new()));
let sink = CapturingSink::wrap(
Box::new(IdemSink),
Arc::clone(&captured),
Arc::new(Projection::Full),
);
assert!(sink.supports_idempotent_writes());
assert!(sink.dedups_by_key());
assert_eq!(
sink.sink_guarantee(),
faucet_core::SinkGuarantee::AtomicWatermark
);
assert!(
sink.supported_write_modes()
.contains(&faucet_core::WriteMode::Upsert)
);
assert_eq!(
sink.last_committed_token("k").await.unwrap(),
Some("tok".into())
);
assert_eq!(sink.current_schema().await.unwrap(), None);
assert!(!sink.supports_schema_evolution());
let n = sink
.write_batch_idempotent(&[json!({"id": 7})], "k", "t")
.await
.unwrap();
assert_eq!(n, 1);
assert_eq!(*captured.lock().await, vec![json!({"id": 7})]);
}
#[tokio::test]
async fn orphaned_child_surfaces_executor_deadlock() {
use crate::config::ConnectorSpec;
let orphan = ExpandedNode {
id: "orphan".into(),
row_index: 0,
role: NodeRole::Child {
parent_id: "missing-parent".into(),
parent_key: "id".into(),
},
source: ConnectorSpec {
kind: "csv".into(),
config: json!({}),
transforms: None,
inherit_transforms: true,
},
sink: ConnectorSpec {
kind: "jsonl".into(),
config: json!({}),
transforms: None,
inherit_transforms: true,
},
transforms: Vec::new(),
state: None,
dlq: None,
delivery: faucet_core::DeliveryMode::AtLeastOnce,
delivery_guarantee: faucet_core::DeliveryGuarantee::AtLeastOnce,
#[cfg(feature = "quality")]
quality: None,
#[cfg(feature = "contract")]
contract: None,
#[cfg(feature = "masking")]
masking: None,
sink_ref: "default".into(),
schema: None,
depends_on: Vec::new(),
deferred_refs: Vec::new(),
source_override: None,
};
let err = run_expanded(vec![orphan], opts("deadlock"))
.await
.expect_err("an orphaned child must surface as an executor deadlock");
match err {
CliError::Internal(msg) => {
assert!(msg.contains("executor deadlock"), "{msg}");
assert!(msg.contains("orphan"), "{msg}");
}
other => panic!("expected Internal deadlock error, got {other:?}"),
}
}
#[test]
fn value_to_string_brief_unquotes_strings_only() {
assert_eq!(value_to_string_brief(&json!("hello")), "hello");
assert_eq!(value_to_string_brief(&json!(42)), "42");
assert_eq!(value_to_string_brief(&json!(true)), "true");
assert_eq!(value_to_string_brief(&json!(null)), "null");
assert_eq!(value_to_string_brief(&json!({"a": 1})), "{\"a\":1}");
}
#[test]
fn build_state_key_with_and_without_parent() {
assert_eq!(build_state_key("pipe", "row", None), "pipe::row");
assert_eq!(build_state_key("pipe", "row", Some("k")), "pipe::row::k");
}
#[test]
fn resolve_parent_key_walks_objects_arrays_and_misses() {
let r = json!({"user": {"name": "ada"}, "tags": ["x", "y"]});
assert_eq!(resolve_parent_key(&r, "user.name"), Some(json!("ada")));
assert_eq!(resolve_parent_key(&r, "tags.1"), Some(json!("y")));
assert_eq!(resolve_parent_key(&r, "user.age"), None);
assert_eq!(resolve_parent_key(&r, "user.name.deep"), None);
assert_eq!(resolve_parent_key(&r, "tags.notanindex"), None);
}
#[tokio::test]
async fn cooperative_cancel_returns_partial_ok() {
let dir = tempfile::tempdir().unwrap();
let input = dir.path().join("in.csv");
let output = dir.path().join("out.jsonl");
std::fs::write(&input, "name\nalice\nbob\n").unwrap();
let cfg = cfg_csv_to_jsonl(&input, &output);
let nodes = expand(&cfg).unwrap();
let token = CancellationToken::new();
token.cancel(); let mut o = opts("cancel");
o.cancel = Some(token);
let summary = run_expanded(nodes, o).await.unwrap();
assert_eq!(summary.invocations.len(), 1);
assert!(
!summary.had_failures(),
"a cooperatively-cancelled run is Ok, not a failure: {summary:?}"
);
}
#[tokio::test]
async fn fanout_projects_away_unreferenced_parent_fields() {
let dir = tempfile::tempdir().unwrap();
let parent_csv = dir.path().join("parents.csv");
let child_csv = dir.path().join("child.csv");
std::fs::write(&parent_csv, "id,payload\n1,aaaaaaaaaa\n2,bbbbbbbbbb\n").unwrap();
std::fs::write(&child_csv, "x\nA\n").unwrap();
let parent_out = dir.path().join("parents.jsonl");
let child_out_pattern = dir.path().join("child-${parents.id}.jsonl");
let yaml = format!(
r#"version: 1
pipeline:
source: {{ type: csv, config: {{ path: {parent} }} }}
sink: {{ type: jsonl, config: {{ path: {parent_out} }} }}
matrix:
- id: parents
- id: child
parent: parents
source: {{ config: {{ path: {child} }} }}
sink: {{ config: {{ path: "{child_out}" }} }}
"#,
parent = parent_csv.display(),
parent_out = parent_out.display(),
child = child_csv.display(),
child_out = child_out_pattern.display(),
);
let cfg = crate::config::parse_with_extension(&yaml, "yaml").unwrap();
let nodes = expand(&cfg).unwrap();
let summary = run_expanded(
nodes,
ExecuteOptions {
pipeline_name: "projtest".into(),
execution: None,
dry_run: false,
limit: None,
state_path_override: None,
shard: None,
auth: Default::default(),
clock: chrono::Utc::now().fixed_offset(),
cancel: None,
resilience: None,
sla: None,
#[cfg(feature = "lineage")]
lineage: None,
#[cfg(feature = "lineage")]
lineage_cfg: None,
#[cfg(feature = "notify")]
notifier: None,
#[cfg(feature = "catalog")]
catalog: None,
},
)
.await
.unwrap();
assert_eq!(summary.invocations.len(), 3, "{summary:?}");
assert!(!summary.had_failures(), "{summary:?}");
assert!(dir.path().join("child-1.jsonl").exists());
assert!(dir.path().join("child-2.jsonl").exists());
}
}