Skip to main content

faucet_core/
traits.rs

1//! Shared traits for faucet sources and sinks.
2
3use crate::error::FaucetError;
4use crate::pipeline::StreamPage;
5use async_trait::async_trait;
6use futures_core::Stream;
7use serde_json::Value;
8use std::pin::Pin;
9
10/// A source fetches records from an external system.
11#[async_trait]
12pub trait Source: Send + Sync {
13    /// Primary fetch method. Receives context from a parent source's records.
14    ///
15    /// An empty context map means this is a root source (no parent).
16    /// Connectors that support being a child should use
17    /// [`substitute_context()`](crate::util::substitute_context) to resolve
18    /// `{placeholder}` tokens in their URL path, query parameters, headers,
19    /// or body. Connectors that don't need parent context ignore the map.
20    async fn fetch_with_context(
21        &self,
22        context: &std::collections::HashMap<String, Value>,
23    ) -> Result<Vec<Value>, FaucetError>;
24
25    /// Convenience: fetch with no parent context.
26    async fn fetch_all(&self) -> Result<Vec<Value>, FaucetError> {
27        self.fetch_with_context(&std::collections::HashMap::new())
28            .await
29    }
30
31    /// Incremental fetch with parent context support.
32    ///
33    /// Returns the records and an optional bookmark value for incremental
34    /// replication. The default delegates to `fetch_with_context` and
35    /// returns `None` for the bookmark.
36    async fn fetch_with_context_incremental(
37        &self,
38        context: &std::collections::HashMap<String, Value>,
39    ) -> Result<(Vec<Value>, Option<Value>), FaucetError> {
40        let records = self.fetch_with_context(context).await?;
41        Ok((records, None))
42    }
43
44    /// Convenience: incremental fetch with no parent context.
45    async fn fetch_all_incremental(&self) -> Result<(Vec<Value>, Option<Value>), FaucetError> {
46        self.fetch_with_context_incremental(&std::collections::HashMap::new())
47            .await
48    }
49
50    /// Stream records page-by-page so the pipeline can write to the sink as
51    /// pages arrive instead of buffering the full result set.
52    ///
53    /// `batch_size` is the *hint* the pipeline passes down; sources are free
54    /// to use a larger or smaller native chunk (e.g. one page per HTTP
55    /// response, one row-group per Parquet file) but should approximate it
56    /// where feasible. The special value `batch_size = 0` means "do not
57    /// batch — emit the entire result set in a single page." Sources that
58    /// stream natively should treat `0` as "skip the chunking layer and
59    /// yield one page after the underlying read completes" (useful for
60    /// small lookup tables or for sinks like SQL `COPY` / BigQuery load
61    /// jobs that prefer one large request).
62    ///
63    /// The default implementation fetches the full result set via
64    /// [`fetch_with_context_incremental`](Self::fetch_with_context_incremental)
65    /// and chunks it in memory by `batch_size`. The bookmark (when present)
66    /// is attached to the *final* page so the pipeline only persists after
67    /// the entire fetch has been written. Sources that can stream natively
68    /// override this method and may emit per-page bookmarks (e.g. CDC).
69    ///
70    /// An empty result with a `Some(bookmark)` still yields one empty page
71    /// carrying the bookmark, so incremental runs that produce no records
72    /// still advance their checkpoint.
73    fn stream_pages<'a>(
74        &'a self,
75        context: &'a std::collections::HashMap<String, Value>,
76        batch_size: usize,
77    ) -> Pin<Box<dyn Stream<Item = Result<StreamPage, FaucetError>> + Send + 'a>> {
78        Box::pin(async_stream::try_stream! {
79            let (records, bookmark) = self
80                .fetch_with_context_incremental(context)
81                .await?;
82            let total = records.len();
83            // batch_size == 0 means "no batching" — emit all records as one
84            // page. Otherwise chunk into pages of size `batch_size`.
85            let chunk = if batch_size == 0 { usize::MAX } else { batch_size };
86
87            if total == 0 {
88                if bookmark.is_some() {
89                    yield StreamPage {
90                        records: Vec::new(),
91                        bookmark,
92                    };
93                }
94                return;
95            }
96
97            let mut iter = records.into_iter();
98            let mut consumed = 0usize;
99            loop {
100                let batch: Vec<Value> = iter.by_ref().take(chunk).collect();
101                if batch.is_empty() {
102                    break;
103                }
104                consumed += batch.len();
105                let page_bookmark = if consumed >= total {
106                    bookmark.clone()
107                } else {
108                    None
109                };
110                yield StreamPage {
111                    records: batch,
112                    bookmark: page_bookmark,
113                };
114            }
115        })
116    }
117
118    /// Whether this source can emit **columnar** ([`ColumnarPage`](crate::columnar::ColumnarPage))
119    /// pages via [`stream_batches`](Self::stream_batches). Default: `false`.
120    ///
121    /// The pipeline uses the columnar fast path only when *both* the source and
122    /// sink return `true` here (and no `Value`-shaped stage needs to observe the
123    /// records), so an Arrow-native `parquet → parquet` chain never materializes
124    /// `Value`. Opt-in and additive — see [`crate::columnar`] (RFC 0002 / #375).
125    #[cfg(feature = "arrow")]
126    fn supports_columnar(&self) -> bool {
127        false
128    }
129
130    /// Stream the source natively as Arrow
131    /// [`ColumnarPage`](crate::columnar::ColumnarPage)s.
132    ///
133    /// Only invoked when [`supports_columnar`](Self::supports_columnar) returns
134    /// `true`; the default yields a single typed "unsupported" error so a source
135    /// that advertises support but forgets to override this fails loudly rather
136    /// than silently. Each page's `bookmark` carries the same checkpoint
137    /// semantics as [`StreamPage`].
138    #[cfg(feature = "arrow")]
139    fn stream_batches<'a>(
140        &'a self,
141        context: &'a std::collections::HashMap<String, Value>,
142        batch_size: usize,
143    ) -> Pin<Box<dyn Stream<Item = Result<crate::columnar::ColumnarPage, FaucetError>> + Send + 'a>>
144    {
145        let _ = (context, batch_size);
146        let name = self.connector_name();
147        let err: Result<crate::columnar::ColumnarPage, FaucetError> = Err(FaucetError::Source(
148            format!("source '{name}' does not support columnar streaming (stream_batches)"),
149        ));
150        Box::pin(futures::stream::once(async move { err }))
151    }
152
153    /// Wire formats this source can emit as raw bytes for the **native
154    /// byte-passthrough** fast path (#633), in preference order (first = best).
155    /// Default: `&[]` (no native fast path).
156    ///
157    /// The pipeline uses the path only when this returns a non-empty slice, a
158    /// sink advertises a matching [`NativeLoadCapability`](crate::NativeLoadCapability),
159    /// and every prerequisite holds (see [`plan_native_transfer`](crate::plan_native_transfer)).
160    /// A [`TransformingSource`](crate::TransformingSource) deliberately does not
161    /// override this, so any attached transform disables the fast path.
162    fn native_output_formats(&self) -> &'static [crate::native::NativeFormat] {
163        &[]
164    }
165
166    /// Stream the source natively as byte batches in `format` (#633).
167    ///
168    /// Only invoked after the pipeline negotiated `format` — one this source
169    /// advertised via [`native_output_formats`](Self::native_output_formats). The
170    /// default yields a single typed "unsupported" error so a source that
171    /// advertises support but forgets to override this fails loudly. Each batch's
172    /// `bookmark` carries the same checkpoint semantics as [`StreamPage`].
173    fn stream_native<'a>(
174        &'a self,
175        context: &'a std::collections::HashMap<String, Value>,
176        format: crate::native::NativeFormat,
177        batch_size: usize,
178    ) -> Pin<Box<dyn Stream<Item = Result<crate::native::NativeBatch, FaucetError>> + Send + 'a>>
179    {
180        let _ = (context, batch_size, format);
181        let name = self.connector_name();
182        let err: Result<crate::native::NativeBatch, FaucetError> = Err(FaucetError::Source(
183            format!("source '{name}' does not support native byte streaming (stream_native)"),
184        ));
185        Box::pin(futures::stream::once(async move { err }))
186    }
187
188    /// Return a JSON Schema describing the configuration this source accepts.
189    fn config_schema(&self) -> Value {
190        serde_json::json!({"type": "object", "properties": {}})
191    }
192
193    /// Stable key under which this source's incremental-replication bookmark
194    /// should be persisted in a [`StateStore`](crate::state::StateStore).
195    ///
196    /// Returning `Some(key)` opts this source into resumable runs: when the
197    /// pipeline is configured with a state store via
198    /// [`Pipeline::with_state_store`](crate::Pipeline::with_state_store), it
199    /// reads the bookmark at `key` before fetching and writes the new
200    /// bookmark back only after the sink confirms the batch was written.
201    ///
202    /// The default returns `None`, meaning the source is not persisted.
203    /// Keys must satisfy [`validate_state_key`](crate::state::validate_state_key).
204    fn state_key(&self) -> Option<String> {
205        None
206    }
207
208    /// Apply a bookmark loaded from a [`StateStore`](crate::state::StateStore)
209    /// as this run's starting point.
210    ///
211    /// The default implementation ignores the value, which keeps existing
212    /// sources backwards-compatible. Sources that support incremental
213    /// replication override this — typically by storing the value behind
214    /// interior mutability and consulting it inside
215    /// `fetch_with_context_incremental`.
216    async fn apply_start_bookmark(&self, _bookmark: Value) -> Result<(), FaucetError> {
217        Ok(())
218    }
219
220    /// Capture the source's current replication position **without consuming
221    /// any changes**, ensuring any server-side resource (e.g. a logical
222    /// replication slot) needed to later resume from that position exists.
223    ///
224    /// Returns the position as a bookmark [`Value`] — the same shape
225    /// [`apply_start_bookmark`](Self::apply_start_bookmark) accepts — or `None`
226    /// if this source does not support position capture.
227    ///
228    /// Used by the snapshot→CDC replication orchestrator (`faucet replicate`)
229    /// to anchor the CDC stream at-or-before the bulk snapshot's read point so
230    /// the handoff has no gap. The default returns `None`.
231    async fn capture_resume_position(&self) -> Result<Option<Value>, FaucetError> {
232        Ok(None)
233    }
234
235    /// How far this source is behind its head (#733) — unread WAL bytes, binlog
236    /// distance, unconsumed messages, or the age of the oldest unread change.
237    ///
238    /// The pipeline polls it at page boundaries and exports
239    /// `faucet_source_lag_{bytes,events,seconds}`; `faucet status --probe`
240    /// asks for it on demand after applying the stored bookmark. It must be a
241    /// cheap, read-only query. An `Err` is logged once and reported as no lag;
242    /// it never fails a run. Default: `Ok(None)` (no notion of a head).
243    /// Decorators must forward this.
244    async fn lag(&self) -> Result<Option<crate::lag::SourceLag>, FaucetError> {
245        Ok(None)
246    }
247
248    /// The version of this source's bookmark shape (#736). Stored state carries
249    /// it; bump it whenever the shape changes and teach
250    /// [`migrate_state`](Self::migrate_state) the step. Default `0`. Decorators
251    /// must forward this.
252    fn state_schema(&self) -> u32 {
253        0
254    }
255
256    /// Bring a bookmark stored at shape version `from` up to
257    /// [`state_schema`](Self::state_schema) (#736). Must be pure — the
258    /// migrated value is only persisted by the next bookmark write, so a crash
259    /// in between re-runs it. The default knows only its own version. Decorators
260    /// must forward this.
261    fn migrate_state(&self, from: u32, data: Value) -> Result<Value, FaucetError> {
262        if from == self.state_schema() {
263            Ok(data)
264        } else {
265            Err(FaucetError::State(format!(
266                "{} has no migration from bookmark schema {from} to {}",
267                self.connector_name(),
268                self.state_schema()
269            )))
270        }
271    }
272
273    /// Whether this source **deterministically replays** the same page sequence
274    /// from a given bookmark — the requirement for the atomic-watermark
275    /// effectively-once path (a non-deterministic replay could cause the pipeline
276    /// to skip a page whose contents differ from the one already committed).
277    /// Default: `false`.
278    ///
279    /// Sources with a durable monotonic position and per-page bookmarks (CDC)
280    /// override this to return `true`. The pipeline rejects
281    /// `DeliveryMode::ExactlyOnce` against a source that returns `false`.
282    fn supports_exactly_once(&self) -> bool {
283        false
284    }
285
286    /// Whether reading from this source **removes data from its backend** —
287    /// a queue source that acks, deletes or settles messages as the pipeline
288    /// moves past each page (SQS, Pub/Sub, JetStream, RabbitMQ). Such a source
289    /// relies on the linear pipeline writing and flushing a page before it is
290    /// polled again; anything that reads without durably writing (a preview, a
291    /// dry run, a `--limit` run, a plan sample) or that polls ahead of its
292    /// sinks (a topology graph) would lose those messages for good, so callers
293    /// refuse it. Default `false`.
294    fn consumes_destructively(&self) -> bool {
295        false
296    }
297
298    /// The typed replay capability this source advertises — see
299    /// [`ReplayGuarantee`](crate::ReplayGuarantee).
300    ///
301    /// The default derives from [`supports_exactly_once`](Self::supports_exactly_once)
302    /// (the boolean stays the back-compat primitive: existing connectors that
303    /// override only the boolean automatically advertise `Deterministic`
304    /// here). Override this directly only to *diverge* from the boolean —
305    /// there is currently no reason to.
306    fn replay_guarantee(&self) -> crate::idempotency::ReplayGuarantee {
307        if self.supports_exactly_once() {
308            crate::idempotency::ReplayGuarantee::Deterministic
309        } else {
310            crate::idempotency::ReplayGuarantee::NonDeterministic
311        }
312    }
313
314    /// What this source can do (RFC 0013, #876). The default derives every
315    /// field from the per-capability methods above
316    /// ([`Capabilities::of_source`](crate::Capabilities::of_source)); override
317    /// it to declare a capability no method expresses (range digests, lag),
318    /// keeping the connector's [`ConnectorDescriptor`](crate::ConnectorDescriptor)
319    /// in agreement. Decorators must forward this.
320    fn capabilities(&self) -> crate::capabilities::Capabilities {
321        crate::capabilities::Capabilities::of_source(self)
322    }
323
324    /// Whether this source can split its work into independent shards for
325    /// clustered (Mode B) execution. Default: `false` (single whole-dataset
326    /// shard). Sources with a natural partition (object-store prefixes, table
327    /// primary-key ranges) override this to `true` and implement
328    /// [`enumerate_shards`](Self::enumerate_shards) +
329    /// [`apply_shard`](Self::apply_shard).
330    fn is_shardable(&self) -> bool {
331        false
332    }
333
334    /// Enumerate the shards this source splits into, aiming for roughly `target`
335    /// of them (a hint — the source may return fewer, e.g. when the dataset is
336    /// small, or one per natural partition regardless of `target`).
337    ///
338    /// Called **once per run** by the cluster coordinator; enumeration must be
339    /// deterministic enough that re-enumeration yields a compatible set (stable
340    /// shard ids), since it may run on more than one instance and is reconciled
341    /// by idempotent insert. May perform read-only I/O (a `LIST`, a `MIN/MAX`
342    /// query). The default returns a single whole-dataset shard
343    /// ([`ShardSpec::whole`](crate::ShardSpec::whole)), preserving today's
344    /// single-worker behavior.
345    async fn enumerate_shards(
346        &self,
347        _target: usize,
348    ) -> Result<Vec<crate::shard::ShardSpec>, FaucetError> {
349        Ok(vec![crate::shard::ShardSpec::whole()])
350    }
351
352    /// Narrow this source instance to a single shard before streaming.
353    ///
354    /// Called on the worker that claims `shard`, after construction and before
355    /// any `stream_pages` call. Like [`apply_start_bookmark`](Self::apply_start_bookmark)
356    /// this takes `&self` and is expected to record the shard behind interior
357    /// mutability (the source consults it when building its query / listing).
358    /// The default ignores the shard — a non-shardable source only ever receives
359    /// [`ShardSpec::whole`](crate::ShardSpec::whole), so ignoring it streams the
360    /// whole dataset. Implementations should accept the whole shard as a no-op.
361    async fn apply_shard(&self, _shard: &crate::shard::ShardSpec) -> Result<(), FaucetError> {
362        Ok(())
363    }
364
365    /// Compute a [`ServerDigest`](crate::diff::ServerDigest) of the rows in
366    /// `range` **inside the backend**, so a matching range ships no rows
367    /// (#701). `columns` are the compared columns; `key` the integer key the
368    /// range is over. Default `Ok(None)`: not supported, the verifier streams
369    /// the range instead. Two digests compare only when both sides report the
370    /// same `algorithm`.
371    async fn range_digest(
372        &self,
373        range: &crate::diff::KeyRange,
374        key: &str,
375        columns: &[String],
376    ) -> Result<Option<crate::diff::ServerDigest>, FaucetError> {
377        let _ = (range, key, columns);
378        Ok(None)
379    }
380
381    /// Whether this source can enumerate the datasets behind its connection
382    /// via [`discover`](Self::discover). Default: `false`. Sources backed by
383    /// an introspectable catalog (database `information_schema`, MongoDB
384    /// collections, Elasticsearch indices, object-store prefixes) override
385    /// this to `true`.
386    fn supports_discover(&self) -> bool {
387        false
388    }
389
390    /// Enumerate the datasets living behind this source's connection — one
391    /// [`DatasetDescriptor`](crate::discover::DatasetDescriptor) per table /
392    /// collection / index / prefix, each carrying a partial config override
393    /// that selects it (used by `faucet discover` to scaffold one matrix row
394    /// per dataset).
395    ///
396    /// Must be **read-only and cheap**: catalog metadata queries and listings
397    /// only, never a data scan. Descriptors must never embed credentials.
398    /// The default returns a typed "unsupported" error; override it (and
399    /// return `true` from [`supports_discover`](Self::supports_discover))
400    /// only for sources with a real catalog to introspect.
401    async fn discover(&self) -> Result<Vec<crate::discover::DatasetDescriptor>, FaucetError> {
402        Err(FaucetError::Source(format!(
403            "source '{}' does not support dataset discovery",
404            self.connector_name()
405        )))
406    }
407
408    /// The dataset (table / collection) a change record belongs to, for a
409    /// change stream that carries several tables (#731). A multi-table
410    /// `faucet mirror` runs one stream and routes each record to its table's
411    /// pipeline by this name, which must match the name the paired bulk
412    /// source's [`discover`](Self::discover) reports (e.g. `public.orders`).
413    /// `None` means the record belongs to no table (a DDL / control event) —
414    /// and is the default, so a source that does not override this cannot be
415    /// used for a multi-table mirror.
416    fn record_table(&self, _record: &Value) -> Option<String> {
417        None
418    }
419
420    /// Order two of this source's bookmarks (#731): `Some(true)` when stream
421    /// position `a` is at or before `b` (every change up to `a` is also covered
422    /// by `b`), `Some(false)` when it is not, and `None` when the source cannot
423    /// tell (the default, or two positions it cannot relate). A multi-table
424    /// mirror uses it to resume one shared stream from the earliest table and
425    /// skip, per table, pages that table has already committed.
426    fn position_le(&self, _a: &Value, _b: &Value) -> Option<bool> {
427        None
428    }
429
430    /// Whether the stream had already delivered `record`'s change at stream
431    /// position `position` (#854): `Some(true)` when a run resumed from
432    /// `position` would not deliver it again, `Some(false)` when it would, and
433    /// `None` when the source cannot tell (the default). A multi-table mirror
434    /// resumes one shared stream from the earliest table, so a replayed page
435    /// can straddle another table's committed position; this per-record test
436    /// drops the records that table already applied, which a per-page
437    /// [`position_le`](Self::position_le) check cannot when the replay cuts its
438    /// pages at different points than the run that committed them.
439    fn record_covered(&self, _record: &Value, _position: &Value) -> Option<bool> {
440        None
441    }
442
443    /// The signal through which this source reports, during a run, that it is
444    /// reading its **whole dataset** (see [`crate::cleanup`]). After such a
445    /// run the pipeline may delete destination rows the run did not write.
446    /// Default `None`: the source never makes that claim.
447    fn read_completeness(&self) -> Option<crate::cleanup::ReadCompleteness> {
448        None
449    }
450
451    /// The earliest stream position every one of `positions` can resume from
452    /// (#731): the shared change stream restarts there and each table skips
453    /// what it has already applied. The default picks the position that
454    /// [`position_le`](Self::position_le) orders at or before all the others,
455    /// and `None` when there is none (an empty slice, or positions this source
456    /// cannot order). Sources whose positions are only partially ordered (one
457    /// cursor per capture instance, say) override it with a component-wise
458    /// minimum.
459    fn position_min(&self, positions: &[Value]) -> Option<Value> {
460        let first = positions.first()?;
461        if positions.iter().all(|p| p == first) {
462            return Some(first.clone());
463        }
464        positions
465            .iter()
466            .find(|cand| {
467                positions
468                    .iter()
469                    .all(|other| self.position_le(cand, other) == Some(true))
470            })
471            .cloned()
472    }
473
474    /// Stable identifier used as the `connector` label on metrics and the
475    /// `connector` attribute on spans. Defaults to the final segment of
476    /// `std::any::type_name::<Self>()`, e.g. `"RestSource"`. Built-in
477    /// connectors override with a short, friendly snake_case name (e.g.
478    /// `"rest"`). Must return a non-empty string; observability decorators
479    /// fall back to `"unknown"` in release builds if it is empty (and
480    /// `debug_assert!` in debug builds).
481    fn connector_name(&self) -> &'static str {
482        crate::observability::strip_type_name(std::any::type_name::<Self>())
483    }
484
485    /// Receive a pre-labelled handle for counting **upstream round trips**
486    /// (#638) — calls this connector makes to its own backend.
487    ///
488    /// The pipeline calls this once before streaming, because it is the only
489    /// place that knows the `pipeline` / `row` / `connector` labels every other
490    /// metric carries. A connector opts in by storing the handle behind
491    /// interior mutability (the pattern the REST source already uses for
492    /// `runtime_start`) and calling `recorder.record("<op>")` at each real
493    /// backend call — including retries, which are real round trips.
494    ///
495    /// Defaulted to a no-op: an uninstrumented connector emits nothing, so
496    /// instrumentation lands connector by connector with no behaviour change
497    /// in between, and a third-party connector is unaffected.
498    fn set_roundtrip_recorder(
499        &self,
500        _recorder: std::sync::Arc<crate::observability::RoundtripRecorder>,
501    ) {
502    }
503
504    /// Receive the run clock (#769): the instant `${now.*}` renders from —
505    /// `faucet run --clock`, a schedule tick, a backfill unit's start — so a
506    /// source that bounds reads by "now" (REST window slicing) reproduces the
507    /// run as of that instant rather than the wall clock.
508    ///
509    /// Called once before streaming. Defaulted to a no-op; a connector opts in
510    /// by storing the instant behind interior mutability.
511    fn set_run_clock(&self, _now: chrono::DateTime<chrono::Utc>) {}
512
513    /// Receive the run's [`CallContext`](crate::io::CallContext) (#880): the
514    /// cancel token, the round-trip recorder and any deadline every backend
515    /// call should honour. Called once before streaming.
516    ///
517    /// A connector stores it in a [`CallSlot`](crate::io::CallSlot) and runs
518    /// its backend calls through [`CallSlot::call`](crate::io::CallSlot::call),
519    /// which layers the connector's own timeout and retry settings over it.
520    /// Defaulted to a no-op; a wrapping source forwards it.
521    fn set_call_context(&self, _ctx: crate::io::CallContext) {}
522
523    /// Receive the run's cancellation token ([`Pipeline::with_cancel`](crate::Pipeline::with_cancel)),
524    /// installed once before streaming.
525    ///
526    /// Return `true` when the source handles the cancel itself: it stops
527    /// reading, yields the records it has buffered and ends its stream
528    /// promptly. The pipeline then keeps polling the stream to its end instead
529    /// of stopping at the next page boundary, so that buffered tail is
530    /// written. A source that buffers records it cannot re-read (a live feed)
531    /// opts in; the default ignores the token and returns `false`. A wrapping
532    /// source forwards the call and returns the inner source's answer.
533    fn set_cancel(&self, _cancel: tokio_util::sync::CancellationToken) -> bool {
534        false
535    }
536
537    /// Logical dataset identity for lineage emission, following OpenLineage
538    /// naming conventions (<https://openlineage.io/docs/spec/naming>).
539    ///
540    /// The default returns `"<connector_name>://unknown"`. Built-in connectors
541    /// override with a credential-free URI derived from their config. Strip any
542    /// credentials with [`redact_uri_credentials`](crate::redact_uri_credentials).
543    /// Informational metadata only — never used for I/O.
544    fn dataset_uri(&self) -> String {
545        format!("{}://unknown", self.connector_name())
546    }
547
548    /// Run a fast, non-mutating preflight probe (used by `faucet doctor`).
549    ///
550    /// The default pulls a **single page** via
551    /// [`stream_pages`](Self::stream_pages) and reports success/failure — it
552    /// exercises the real read path (DNS, TLS, auth, the first request, the
553    /// first-record decode) but never paginates the full dataset and never
554    /// repeats. The page stream is dropped immediately after the first page.
555    ///
556    /// Sources whose first page *blocks* waiting for inbound data (webhook,
557    /// websocket) or has *side effects* (CDC consuming WAL) override this with a
558    /// cheaper, side-effect-free probe. Probe-level failures are returned as a
559    /// [`ProbeStatus::Fail`](crate::check::ProbeStatus) inside `Ok(report)`.
560    async fn check(
561        &self,
562        ctx: &crate::check::CheckContext,
563    ) -> Result<crate::check::CheckReport, FaucetError> {
564        use crate::check::{CheckReport, Probe};
565        use futures::StreamExt;
566
567        let empty = std::collections::HashMap::new();
568        let start = std::time::Instant::now();
569        let mut pages = self.stream_pages(&empty, 1);
570        let probe = match tokio::time::timeout(ctx.timeout, pages.next()).await {
571            Err(_) => Probe::fail("read", start.elapsed(), "timed out fetching first page"),
572            Ok(None) | Ok(Some(Ok(_))) => Probe::pass("read", start.elapsed()),
573            Ok(Some(Err(e))) => Probe::fail("read", start.elapsed(), e.to_string()),
574        };
575        Ok(CheckReport::single(probe))
576    }
577}
578
579/// Per-row outcome from [`Sink::write_batch_partial`].
580///
581/// `Ok(())` — the row was durably written to the sink.
582/// `Err(_)` — the row failed; the pipeline will route it to the DLQ when
583/// one is configured.
584pub type RowOutcome = Result<(), FaucetError>;
585
586/// A sink writes records to an external system.
587#[async_trait]
588pub trait Sink: Send + Sync {
589    /// Write a batch of records to the destination.
590    ///
591    /// Returns the number of records successfully written.
592    async fn write_batch(&self, records: &[Value]) -> Result<usize, FaucetError>;
593
594    /// Flush any buffered data to the destination.
595    ///
596    /// The default implementation is a no-op (suitable for sinks that
597    /// write immediately in `write_batch`).
598    async fn flush(&self) -> Result<(), FaucetError> {
599        Ok(())
600    }
601
602    /// Write a batch and report per-row outcomes.
603    ///
604    /// Sinks whose underlying API exposes per-row results (BigQuery
605    /// `insertAll`, Elasticsearch `_bulk`) override this. The default
606    /// implementation delegates to [`Self::write_batch`] and maps a single success
607    /// onto a uniform all-`Ok(())` vector. An outer failure is bubbled up
608    /// unchanged so the pipeline's DLQ router can apply its `on_batch_error`
609    /// policy at a single decision point.
610    ///
611    /// The default checks the write's [`WriteReport`](crate::WriteReport)
612    /// (#879): rows it neither wrote nor reported as coalesced fail the batch
613    /// with [`FaucetError::RowsUnaccounted`] instead of being reported `Ok`.
614    async fn write_batch_partial(&self, records: &[Value]) -> Result<Vec<RowOutcome>, FaucetError> {
615        self.write_batch_reported(records)
616            .await?
617            .check(records.len())?;
618        Ok(records.iter().map(|_| Ok(())).collect())
619    }
620
621    /// Write a batch and report what happened to every row offered (#879).
622    ///
623    /// The pipeline calls this instead of [`Self::write_batch`] and checks that
624    /// `accepted + coalesced + skipped` covers the page; a shortfall fails the
625    /// page with [`FaucetError::RowsUnaccounted`]. The default wraps
626    /// `write_batch`'s count; for a sink configured to merge rows by key
627    /// ([`Self::dedups_by_key`] — keyed upsert / delete, last write wins) it
628    /// counts the rows the count falls short by as
629    /// [`coalesced`](crate::WriteReport::coalesced). A sink that declines rows
630    /// by design of its configuration overrides this and reports them as
631    /// [`skipped`](crate::WriteReport::skipped).
632    async fn write_batch_reported(
633        &self,
634        records: &[Value],
635    ) -> Result<crate::accounting::WriteReport, FaucetError> {
636        let n = self.write_batch(records).await?;
637        Ok(if self.dedups_by_key() {
638            crate::accounting::WriteReport::keyed(records.len(), n)
639        } else {
640            crate::accounting::WriteReport::accepted(n)
641        })
642    }
643
644    /// Write a page the engine governed (RFC 0014): it went through masking,
645    /// quality, contract and schema drift, so the records are exactly what
646    /// may reach the destination. The engine's plain write path calls this.
647    ///
648    /// The default delegates to [`write_batch_reported`](Self::write_batch_reported)
649    /// with the page's records, so existing sinks behave as before. A
650    /// [`GovernedPage`](crate::governance::GovernedPage) cannot be built
651    /// outside [`governance`](crate::governance), so a sink that overrides
652    /// this receives only governed data. Decorators forward it.
653    async fn write_governed(
654        &self,
655        page: &crate::governance::GovernedPage<'_>,
656    ) -> Result<crate::accounting::WriteReport, FaucetError> {
657        self.write_batch_reported(page.records()).await
658    }
659
660    /// What a failed batch write leaves behind (#737): nothing
661    /// ([`Atomic`](crate::BatchAtomicity::Atomic)), per-row outcomes with
662    /// nothing committed on an outer `Err`
663    /// ([`PerRow`](crate::BatchAtomicity::PerRow)), or possibly some rows
664    /// ([`BestEffort`](crate::BatchAtomicity::BestEffort), the default).
665    ///
666    /// `on_batch_error: dlq_all` is refused on a best-effort sink unless it
667    /// writes by key or the user opts in to the duplicates. Decorators must
668    /// forward this.
669    fn batch_atomicity(&self) -> crate::dlq::BatchAtomicity {
670        crate::dlq::BatchAtomicity::BestEffort
671    }
672
673    /// Called with a whole page before the pipeline splits it into adaptive
674    /// sub-batches. A sink enforcing a ceiling that must hold for the page as
675    /// a unit (a run budget) refuses here, so no sub-batch of a refused page
676    /// lands. Default: accept. Decorators must forward this.
677    async fn admit_page(&self, records: &[Value]) -> Result<(), FaucetError> {
678        let _ = records;
679        Ok(())
680    }
681
682    /// Whether this sink can consume **columnar** (`arrow::RecordBatch`) writes
683    /// via [`write_batch_columnar`](Self::write_batch_columnar) without first
684    /// converting to `Value`. Default: `false`.
685    ///
686    /// The pipeline takes the columnar fast path only when *both* the source and
687    /// sink return `true` (RFC 0002 / #375).
688    #[cfg(feature = "arrow")]
689    fn supports_columnar(&self) -> bool {
690        false
691    }
692
693    /// Write a columnar `RecordBatch` to the destination, returning the number of
694    /// rows written.
695    ///
696    /// The default converts the batch to `Value` rows via the
697    /// [`columnar`](crate::columnar) shim and delegates to
698    /// [`write_batch`](Self::write_batch), so every sink participates correctly
699    /// even without a native columnar path. Sinks that write Arrow/Parquet
700    /// directly override this — and return `true` from
701    /// [`supports_columnar`](Self::supports_columnar) — to skip the conversion.
702    #[cfg(feature = "arrow")]
703    async fn write_batch_columnar(
704        &self,
705        batch: &arrow::array::RecordBatch,
706    ) -> Result<usize, FaucetError> {
707        let rows = crate::columnar::record_batch_to_values(batch)?;
708        self.write_batch(&rows).await
709    }
710
711    /// Native byte-passthrough load mechanisms this sink offers, each naming
712    /// the wire format and the write modes it can honor (#633). Default:
713    /// `vec![]` (no fast path; use [`write_batch`](Self::write_batch)).
714    ///
715    /// The pipeline takes the native path only when a source advertises a
716    /// format this returns and the run passes the pipeline-owned gates — no
717    /// transforms, no quality/contract/masking pass, no DLQ, at-least-once
718    /// delivery, no upsert/delete `write_mode`, and (for overwrite) an
719    /// all-or-nothing load session finalized by a single terminal `flush` —
720    /// see [`plan_native_transfer`](crate::plan_native_transfer). A capability
721    /// cannot waive those gates.
722    fn native_load_capabilities(&self) -> Vec<crate::native::NativeLoadCapability> {
723        Vec::new()
724    }
725
726    /// Bulk-load one native-format byte batch directly (#633), returning the
727    /// number of rows written.
728    ///
729    /// Only invoked when the pipeline negotiated one of this sink's
730    /// [`native_load_capabilities`](Self::native_load_capabilities) and the
731    /// pipeline-owned gates passed. `ctx.first_batch` lets an overwrite sink
732    /// truncate on the first load and append thereafter. The default returns a
733    /// typed "unsupported" error so a sink that advertises a capability but
734    /// forgets to override this fails loudly.
735    ///
736    /// **Contract:** an **empty payload must be a successful no-op** returning
737    /// `Ok(0)` — sources emit a trailing empty batch to carry the final
738    /// bookmark, and an error here would break bookmark persistence. Under
739    /// `Overwrite`, nothing may become visible in the destination until the
740    /// terminal [`flush`](Self::flush) — the pipeline flushes exactly once, on
741    /// success only, so a mechanism that commits per batch must omit
742    /// `Overwrite` from its capability's `write_modes`.
743    async fn load_native(
744        &self,
745        batch: crate::native::NativeBatch,
746        scope: &str,
747        ctx: crate::native::NativeLoadContext,
748    ) -> Result<usize, FaucetError> {
749        let _ = (batch, scope, ctx);
750        Err(FaucetError::Sink(format!(
751            "sink '{}' does not support native byte loading (load_native)",
752            self.connector_name()
753        )))
754    }
755
756    /// Whether this sink can durably commit a page's rows **and** a commit token
757    /// in a single atomic transaction. Default: `false` (at-least-once only).
758    ///
759    /// Only return `true` from a sink that genuinely commits both atomically —
760    /// see [`write_batch_idempotent`](Self::write_batch_idempotent). The pipeline
761    /// rejects `DeliveryMode::ExactlyOnce` against a sink that returns `false`.
762    fn supports_idempotent_writes(&self) -> bool {
763        false
764    }
765
766    /// The strongest delivery guarantee this sink can uphold — see
767    /// [`SinkGuarantee`](crate::SinkGuarantee).
768    ///
769    /// The default derives from the two back-compat primitives:
770    /// [`supports_idempotent_writes`](Self::supports_idempotent_writes) →
771    /// `AtomicWatermark`, else an upsert-capable
772    /// [`supported_write_modes`](Self::supported_write_modes) → `KeyedUpsert`,
773    /// else `AtLeastOnce`. Existing connectors that override only the
774    /// primitives automatically advertise the right capability here.
775    fn sink_guarantee(&self) -> crate::idempotency::SinkGuarantee {
776        if self.supports_idempotent_writes() {
777            crate::idempotency::SinkGuarantee::AtomicWatermark
778        } else if self
779            .supported_write_modes()
780            .contains(&crate::write_mode::WriteMode::Upsert)
781        {
782            crate::idempotency::SinkGuarantee::KeyedUpsert
783        } else {
784            crate::idempotency::SinkGuarantee::AtLeastOnce
785        }
786    }
787
788    /// What this sink can do (RFC 0013, #876). The default derives every field
789    /// from the per-capability methods
790    /// ([`Capabilities::of_sink`](crate::Capabilities::of_sink)); override it
791    /// to declare a capability no method expresses (how unknown fields are
792    /// treated, scoped overwrite), keeping the connector's
793    /// [`ConnectorDescriptor`](crate::ConnectorDescriptor) in agreement.
794    /// Decorators must forward this.
795    fn capabilities(&self) -> crate::capabilities::Capabilities {
796        crate::capabilities::Capabilities::of_sink(self)
797    }
798
799    /// Whether a **plain [`write_batch`](Self::write_batch) is safe to replay**
800    /// — i.e. re-sending the same page after an ambiguous failure converges
801    /// instead of duplicating rows. Default: `false`.
802    ///
803    /// This is the property the pipeline needs before it may retry a
804    /// non-idempotent write, and it is **not** the same as
805    /// [`supports_idempotent_writes`](Self::supports_idempotent_writes), which
806    /// promises only that rows *and a commit token* can be committed in one
807    /// transaction (the [`write_batch_idempotent`](Self::write_batch_idempotent)
808    /// path). A sink can offer that token protocol and still have a plain
809    /// `write_batch` that is a bare multi-row `INSERT` — replaying it after the
810    /// server committed but the response was lost duplicates every row, which
811    /// is this repo's worst bug class (F29/F32).
812    ///
813    /// The default implementation is therefore conservative and derives from
814    /// the live config: a keyed upsert/delete converges on replay, anything
815    /// else does not. Override only for a sink whose plain write is genuinely
816    /// replay-safe by construction.
817    fn write_batch_is_replay_safe(&self) -> bool {
818        self.dedups_by_key()
819    }
820
821    /// Whether this sink instance is **configured** to dedup by key — i.e.
822    /// `write_mode: upsert` (or `delete`) with a non-empty `key`, so
823    /// re-applying a record with the same key converges instead of
824    /// duplicating. Default: `false`.
825    ///
826    /// Distinct from [`sink_guarantee`](Self::sink_guarantee) (capability):
827    /// this reflects the *live config*. Sinks that flatten a
828    /// [`WriteSpec`](crate::write_mode::WriteSpec) into their config override
829    /// it as `self.config.write.dedups_by_key()`. The pipeline consults it to
830    /// derive the keyed-upsert effectively-once mechanism at run time.
831    fn dedups_by_key(&self) -> bool {
832        false
833    }
834
835    /// Write modes this sink can apply. Default: append-only. Sinks that
836    /// implement key-based merge override this to include
837    /// [`WriteMode::Upsert`](crate::write_mode::WriteMode) /
838    /// [`WriteMode::Delete`](crate::write_mode::WriteMode). The CLI rejects a
839    /// configured mode that is not in this set at config-load time.
840    fn supported_write_modes(&self) -> &'static [crate::write_mode::WriteMode] {
841        &[crate::write_mode::WriteMode::Append]
842    }
843
844    /// The sink's live destination schema as an `infer_schema`-shaped object
845    /// (`{"type":"object","properties":{ <col>: <type-fragment>, … }}`), or
846    /// `None` for a schemaless sink or a target that does not exist yet.
847    ///
848    /// Used by the schema-drift policy to diff each page's shape against the
849    /// real destination. Default: `Ok(None)` (drift handling is inert).
850    async fn current_schema(&self) -> Result<Option<Value>, FaucetError> {
851        Ok(None)
852    }
853
854    /// Whether this sink can apply additive/widening DDL via
855    /// [`evolve_schema`](Self::evolve_schema). Default: `false`. The CLI rejects
856    /// `on_drift: evolve` against a sink that returns `false` at config-load.
857    fn supports_schema_evolution(&self) -> bool {
858        false
859    }
860
861    /// Apply an additive schema evolution (new columns, lossless widenings,
862    /// nullability relaxations) to the destination. MUST be idempotent
863    /// (`ADD COLUMN IF NOT EXISTS` semantics) so concurrent runs converge.
864    ///
865    /// Default: a typed "unsupported" error. Override only when the backend
866    /// supports in-place additive DDL (and return `true` from
867    /// `supports_schema_evolution`).
868    async fn evolve_schema(
869        &self,
870        evolution: &crate::drift::SchemaEvolution,
871    ) -> Result<(), FaucetError> {
872        let _ = evolution;
873        Err(FaucetError::Sink(format!(
874            "sink '{}' does not support schema evolution",
875            self.connector_name()
876        )))
877    }
878
879    /// Whether this sink can delete a scoped set of rows for scoped cleanup
880    /// (#478). Default `false`; the upsert-capable sinks override it.
881    fn supports_cleanup(&self) -> bool {
882        false
883    }
884
885    /// Whether this sink can bulk-load via an object-store stage — write the
886    /// page to S3/GCS/Azure, then pull it with the warehouse's native load
887    /// command (`COPY` / `COPY INTO` / `s3()` table function) (#528). Default
888    /// `false`; warehouse sinks that honour a [`StagingSpec`](crate::StagingSpec)
889    /// override it. Object-safe (no args, no generics) so `Box<dyn Sink>` is
890    /// unaffected.
891    fn supports_staged_load(&self) -> bool {
892        false
893    }
894
895    /// Delete rows matching `scope` whose key is **not** in `seen`.
896    ///
897    /// Called at most once per invocation, only after the run completed
898    /// successfully and uncancelled — see [`crate::cleanup`] for why the timing
899    /// is load-bearing. `scope` is a set of equality predicates in destination
900    /// column terms, AND-ed together; `seen` holds the key tuples this run wrote.
901    /// An **empty** `scope` is the whole destination: a complete-read cleanup
902    /// ([`CleanupPolicy::for_complete_read`](crate::CleanupPolicy::for_complete_read)).
903    ///
904    /// Returns the number of rows deleted. Implementations **must** be
905    /// all-or-nothing where the backend allows it: a partial delete would remove
906    /// rows the run actually wrote.
907    ///
908    /// The default is a typed "unsupported" error, so no existing or third-party
909    /// connector breaks.
910    #[deprecated(
911        since = "1.14.0",
912        note = "implement `faucet_core::driver::CleanupDriver` on a family driver; see RFC 0014"
913    )]
914    async fn cleanup_scope(
915        &self,
916        scope: &std::collections::BTreeMap<String, Value>,
917        seen: &crate::cleanup::SeenKeys,
918    ) -> Result<u64, FaucetError> {
919        let _ = (scope, seen);
920        Err(FaucetError::Sink(format!(
921            "sink '{}' does not support scoped cleanup",
922            self.connector_name()
923        )))
924    }
925
926    /// Write `records` AND durably record `token` for `scope`, atomically.
927    ///
928    /// `scope` namespaces the watermark (the pipeline passes the per-row state
929    /// key, e.g. `"{name}::{row_id}"`). `token` is a monotonic, fixed-width
930    /// string (see [`format_token`](crate::format_token)).
931    ///
932    /// The default is **not** idempotent: it ignores the token and delegates to
933    /// [`write_batch`](Self::write_batch). Override only when the commit is
934    /// genuinely atomic (and return `true` from `supports_idempotent_writes`).
935    #[deprecated(
936        since = "1.14.0",
937        note = "implement `faucet_core::driver::CommitTokenDriver` on a family driver; see RFC 0014"
938    )]
939    async fn write_batch_idempotent(
940        &self,
941        records: &[Value],
942        scope: &str,
943        token: &str,
944    ) -> Result<usize, FaucetError> {
945        let _ = (scope, token);
946        self.write_batch(records).await
947    }
948
949    /// [`write_batch_idempotent`](Self::write_batch_idempotent) with a
950    /// [`WriteReport`](crate::accounting::WriteReport): the exactly-once path
951    /// calls this, and a page whose report does not account for every row it
952    /// offered fails with [`FaucetError::RowsUnaccounted`] before its bookmark
953    /// is persisted (#879). Override it when the sink declines rows by design
954    /// inside the atomic commit (a record without a key under a skip policy)
955    /// and report them as `skipped`.
956    ///
957    /// The default credits the rows `write_batch_idempotent` returns — as
958    /// coalesced-by-key when [`dedups_by_key`](Self::dedups_by_key) — so a
959    /// sink that silently writes fewer rows than it was offered fails the page.
960    #[deprecated(
961        since = "1.14.0",
962        note = "implement `faucet_core::driver::CommitTokenDriver` on a family driver; see RFC 0014"
963    )]
964    #[allow(deprecated)] // drives the 1.x lifecycle hook until faucet-core 2.0 (RFC 0014)
965    async fn write_batch_idempotent_reported(
966        &self,
967        records: &[Value],
968        scope: &str,
969        token: &str,
970    ) -> Result<crate::accounting::WriteReport, FaucetError> {
971        let n = self.write_batch_idempotent(records, scope, token).await?;
972        Ok(if self.dedups_by_key() {
973            crate::accounting::WriteReport::keyed(records.len(), n)
974        } else {
975            crate::accounting::WriteReport::accepted(n)
976        })
977    }
978
979    /// The last token durably committed for `scope`, or `None` if this sink has
980    /// never committed under that scope. Default: `None`.
981    #[deprecated(
982        since = "1.14.0",
983        note = "implement `faucet_core::driver::CommitTokenDriver` on a family driver; see RFC 0014"
984    )]
985    async fn last_committed_token(&self, scope: &str) -> Result<Option<String>, FaucetError> {
986        let _ = scope;
987        Ok(None)
988    }
989
990    /// Whether this sink instance is configured for full-destination
991    /// replacement ([`WriteMode::Overwrite`](crate::write_mode::WriteMode)).
992    ///
993    /// The pipeline consults this to drive the overwrite lifecycle:
994    /// [`begin_overwrite`](Self::begin_overwrite) before the first page, then
995    /// [`commit_overwrite`](Self::commit_overwrite) once the run finishes
996    /// successfully, or [`abort_overwrite`](Self::abort_overwrite) on
997    /// failure/cancel. Sinks that flatten a [`WriteSpec`](crate::write_mode::WriteSpec)
998    /// into their config return `self.config.write.is_overwrite()`. Default `false`.
999    fn is_overwrite(&self) -> bool {
1000        false
1001    }
1002
1003    /// Prepare a staging target for an overwrite run.
1004    ///
1005    /// Called once, before the first [`write_batch`](Self::write_batch), only
1006    /// when [`is_overwrite`](Self::is_overwrite) is true. The sink stages this
1007    /// run's writes (a temp table / new index / temp prefix) so the existing
1008    /// destination is untouched until the run succeeds. Subsequent
1009    /// `write_batch` calls for this sink must land in the staging target.
1010    ///
1011    /// Default: a typed "unsupported" error, so a sink that advertises
1012    /// `WriteMode::Overwrite` but forgets to implement the lifecycle fails
1013    /// loudly rather than silently appending. Never called for sinks whose
1014    /// `is_overwrite()` is false.
1015    #[deprecated(
1016        since = "1.14.0",
1017        note = "implement `faucet_core::driver::StagingDriver` on a family driver; see RFC 0014"
1018    )]
1019    async fn begin_overwrite(&self) -> Result<(), FaucetError> {
1020        Err(FaucetError::Sink(format!(
1021            "sink '{}' does not support write_mode: overwrite",
1022            self.connector_name()
1023        )))
1024    }
1025
1026    /// Atomically replace the destination with the staged data.
1027    ///
1028    /// Called **once, only after the run completed successfully and
1029    /// uncancelled**. Implementations MUST swap staging → destination
1030    /// atomically (or as close as the backend allows) so a reader never sees a
1031    /// half-replaced dataset, and MUST NOT have destroyed the prior contents
1032    /// before this point — a failed run leaves the old data in place.
1033    ///
1034    /// Default: a typed "unsupported" error (unreachable for a correct sink
1035    /// whose `is_overwrite()` is false).
1036    #[deprecated(
1037        since = "1.14.0",
1038        note = "implement `faucet_core::driver::StagingDriver` on a family driver; see RFC 0014"
1039    )]
1040    async fn commit_overwrite(&self) -> Result<(), FaucetError> {
1041        Err(FaucetError::Sink(format!(
1042            "sink '{}' does not support write_mode: overwrite",
1043            self.connector_name()
1044        )))
1045    }
1046
1047    /// Whether this sink can undo a run it wrote (#706) through
1048    /// [`rollback_run`](Self::rollback_run). Default `false`.
1049    fn supports_rollback(&self) -> bool {
1050        false
1051    }
1052
1053    /// Undo everything `run_id` wrote to this destination, per
1054    /// `opts.mode`: delete the run's rows (append), restore journaled
1055    /// before-images (upsert / delete), or swap the kept previous table back
1056    /// (overwrite). Must be all-or-nothing per destination where the backend
1057    /// allows it, and must leave the destination untouched when `opts.dry_run`
1058    /// is set or when conflicts block it (see
1059    /// [`RollbackOutcome`](crate::rollback::RollbackOutcome)).
1060    ///
1061    /// Default: a typed "unsupported" error.
1062    async fn rollback_run(
1063        &self,
1064        run_id: &str,
1065        opts: &crate::rollback::RollbackOptions,
1066    ) -> Result<crate::rollback::RollbackOutcome, FaucetError> {
1067        let _ = (run_id, opts);
1068        Err(FaucetError::Sink(format!(
1069            "sink '{}' does not support rollback",
1070            self.connector_name()
1071        )))
1072    }
1073
1074    /// Drop whatever this sink kept to make `run_id` undoable (journal rows, a
1075    /// previous table) once the run is past the retention window. Default:
1076    /// no-op.
1077    async fn forget_run(&self, run_id: &str) -> Result<(), FaucetError> {
1078        let _ = run_id;
1079        Ok(())
1080    }
1081
1082    /// Rewind the exactly-once watermark for `scope` to `token` (`None` clears
1083    /// it), so a rolled-back run's pages are not skipped on the next run.
1084    /// Default: a typed "unsupported" error.
1085    async fn rewind_commit_token(
1086        &self,
1087        scope: &str,
1088        token: Option<&str>,
1089    ) -> Result<(), FaucetError> {
1090        let _ = (scope, token);
1091        Err(FaucetError::Sink(format!(
1092            "sink '{}' does not support rewinding its commit token",
1093            self.connector_name()
1094        )))
1095    }
1096
1097    /// A source `(kind, config)` that reads this destination back — what
1098    /// `faucet verify` (#701) compares the pipeline's source against. Default
1099    /// `None`: the user names the destination reader in `verify.destination`.
1100    /// The config must not need a credential the sink config lacks.
1101    fn readback_source(&self) -> Option<(String, Value)> {
1102        None
1103    }
1104
1105    /// Discard the staging target after a failed or cancelled overwrite run.
1106    ///
1107    /// Called (best-effort) when an overwrite run does not reach
1108    /// [`commit_overwrite`](Self::commit_overwrite). The destination must be
1109    /// left exactly as it was before the run. Default: no-op — a leftover
1110    /// staging object is untidy but never data loss, so a sink may skip it.
1111    #[deprecated(
1112        since = "1.14.0",
1113        note = "implement `faucet_core::driver::StagingDriver` on a family driver; see RFC 0014"
1114    )]
1115    async fn abort_overwrite(&self) -> Result<(), FaucetError> {
1116        Ok(())
1117    }
1118
1119    /// Finalize this run's output after [`Pipeline::run`](crate::Pipeline::run)
1120    /// finished **successfully and uncancelled**, on every transfer path
1121    /// (`Value`, columnar, native), after the terminal flush.
1122    ///
1123    /// A sink whose destination must reflect *this* run even when it wrote
1124    /// nothing uses it: the file sinks with `append: false` truncate (or, for
1125    /// a fixed-path Parquet file, remove) the previous run's output here when
1126    /// no record arrived, so a source that became empty never leaves stale
1127    /// rows presented as current (#753). Never called after a failed or
1128    /// cancelled run, so the previous good output survives those. Decorators
1129    /// must forward it. Default: no-op.
1130    async fn complete_run(&self) -> Result<(), FaucetError> {
1131        Ok(())
1132    }
1133
1134    /// Whether an overwrite staging object (the `…__faucet_ovw` table or
1135    /// collection a [`begin_overwrite`](Self::begin_overwrite) creates) exists
1136    /// right now — a read-only probe used by `faucet status --probe` to report
1137    /// staging a crashed or aborted overwrite left behind.
1138    ///
1139    /// `Ok(None)` means the sink cannot tell (the default); overwrite-capable
1140    /// sinks return `Ok(Some(_))`.
1141    #[deprecated(
1142        since = "1.14.0",
1143        note = "implement `faucet_core::driver::StagingDriver` on a family driver; see RFC 0014"
1144    )]
1145    async fn overwrite_staging_exists(&self) -> Result<Option<bool>, FaucetError> {
1146        Ok(None)
1147    }
1148
1149    /// Return a JSON Schema describing the configuration this sink accepts.
1150    ///
1151    /// The schema is auto-generated from the config struct using `schemars`.
1152    /// Callers can inspect it to discover required fields, types, defaults,
1153    /// and descriptions before constructing the sink.
1154    ///
1155    /// The default returns an empty object schema.
1156    fn config_schema(&self) -> Value {
1157        serde_json::json!({"type": "object", "properties": {}})
1158    }
1159
1160    /// Stable identifier used as the `connector` label on metrics and the
1161    /// `connector` attribute on spans. See `Source::connector_name`.
1162    fn connector_name(&self) -> &'static str {
1163        crate::observability::strip_type_name(std::any::type_name::<Self>())
1164    }
1165
1166    /// Receive a pre-labelled handle for counting **upstream round trips**
1167    /// (#638). See [`Source::set_roundtrip_recorder`]; defaulted to a no-op.
1168    fn set_roundtrip_recorder(
1169        &self,
1170        _recorder: std::sync::Arc<crate::observability::RoundtripRecorder>,
1171    ) {
1172    }
1173
1174    /// Receive the run's [`CallContext`](crate::io::CallContext) (#880). See
1175    /// [`Source::set_call_context`]. A sink's context never carries the run's
1176    /// cancel token — a cancelled run still flushes its sinks — nor a retry
1177    /// policy: writes are retried page by page under ADR 0007. Defaulted to a
1178    /// no-op; a wrapping sink forwards it.
1179    fn set_call_context(&self, _ctx: crate::io::CallContext) {}
1180
1181    /// Logical dataset identity for lineage emission, following OpenLineage
1182    /// naming conventions (<https://openlineage.io/docs/spec/naming>).
1183    ///
1184    /// The default returns `"<connector_name>://unknown"`. Built-in connectors
1185    /// override with a credential-free URI derived from their config. Strip any
1186    /// credentials with [`redact_uri_credentials`](crate::redact_uri_credentials).
1187    /// Informational metadata only — never used for I/O.
1188    fn dataset_uri(&self) -> String {
1189        format!("{}://unknown", self.connector_name())
1190    }
1191
1192    /// The concrete **local files** this sink instance opened during the run.
1193    ///
1194    /// The provenance record faucet's local-output retention GC (#587) deletes
1195    /// from: it may only remove files faucet recorded here, never a glob or a
1196    /// directory. A sink that writes local files (jsonl, csv, parquet to a local
1197    /// destination) accumulates a
1198    /// [`LocalOutputLog`](crate::local_outputs::LocalOutputLog) as it opens them
1199    /// and returns its snapshot; every other sink keeps the empty default, which
1200    /// simply means "nothing local to collect".
1201    ///
1202    /// Two properties the GC depends on, so an implementation must preserve them:
1203    ///
1204    /// 1. **Every file, individually named.** A rolling parquet sink returns one
1205    ///    entry per UUID-named part — the directory itself is not an output.
1206    /// 2. **[`LocalOutput::pre_existing`](crate::local_outputs::LocalOutput) is
1207    ///    honest**, captured before the first open. A file faucet appended to but
1208    ///    did not create is never collected.
1209    ///
1210    /// Called after the run (and by `faucet cleanup`), never on the data path, so
1211    /// an implementation may take a lock. Decorating sinks **must forward** this
1212    /// to their inner sink, exactly as they do
1213    /// [`dataset_uri`](Self::dataset_uri) — a decorator that returns the default
1214    /// hides its inner sink's files from the GC and they are never reclaimed.
1215    async fn local_outputs(&self) -> Vec<crate::local_outputs::LocalOutput> {
1216        Vec::new()
1217    }
1218
1219    /// Run a fast, non-mutating preflight probe (used by `faucet doctor`).
1220    ///
1221    /// Unlike sources, a sink has no non-mutating "first page" equivalent
1222    /// (`write_batch` mutates the destination), so the default returns
1223    /// [`CheckReport::not_implemented`](crate::check::CheckReport::not_implemented).
1224    /// Built-in sinks override this with a connect / auth / metadata probe.
1225    ///
1226    /// The probe **MUST be idempotent and side-effect-free** — no inserts, no
1227    /// residual rows or objects — and must never put credentials or connection
1228    /// strings in a probe `reason`/`hint`.
1229    async fn check(
1230        &self,
1231        _ctx: &crate::check::CheckContext,
1232    ) -> Result<crate::check::CheckReport, FaucetError> {
1233        Ok(crate::check::CheckReport::not_implemented())
1234    }
1235}
1236
1237#[allow(deprecated)] // the tests drive the 1.x lifecycle hooks directly (RFC 0014)
1238#[cfg(test)]
1239mod tests {
1240    use super::*;
1241    use serde_json::json;
1242
1243    // ── Mock Source ──────────────────────────────────────────────────────────
1244
1245    struct MockSource {
1246        records: Vec<Value>,
1247    }
1248
1249    #[async_trait]
1250    impl Source for MockSource {
1251        async fn fetch_with_context(
1252            &self,
1253            _context: &std::collections::HashMap<String, Value>,
1254        ) -> Result<Vec<Value>, FaucetError> {
1255            Ok(self.records.clone())
1256        }
1257    }
1258
1259    #[test]
1260    fn default_migrate_state_accepts_only_its_own_schema() {
1261        let src = MockSource { records: vec![] };
1262        assert_eq!(src.state_schema(), 0);
1263        assert_eq!(
1264            src.migrate_state(0, json!({"id": 1})).unwrap(),
1265            json!({"id": 1})
1266        );
1267        let err = src.migrate_state(3, json!({})).unwrap_err().to_string();
1268        assert!(
1269            err.contains("no migration from bookmark schema 3 to 0"),
1270            "{err}"
1271        );
1272    }
1273
1274    #[test]
1275    fn default_multi_table_hooks_route_nothing_and_order_nothing() {
1276        let src = MockSource { records: vec![] };
1277        assert_eq!(src.record_table(&json!({"table": "t"})), None);
1278        assert_eq!(src.position_le(&json!(1), &json!(2)), None);
1279        assert_eq!(src.record_covered(&json!({}), &json!(1)), None);
1280        assert_eq!(src.position_min(&[]), None);
1281        assert_eq!(src.position_min(&[json!(3), json!(3)]), Some(json!(3)));
1282        assert_eq!(src.position_min(&[json!(1), json!(2)]), None);
1283    }
1284
1285    #[tokio::test]
1286    async fn ordered_double_fetches_nothing() {
1287        use crate::Source as _;
1288        assert!(
1289            OrderedSource
1290                .fetch_with_context(&Default::default())
1291                .await
1292                .unwrap()
1293                .is_empty()
1294        );
1295    }
1296
1297    struct OrderedSource;
1298
1299    #[async_trait]
1300    impl Source for OrderedSource {
1301        async fn fetch_with_context(
1302            &self,
1303            _context: &std::collections::HashMap<String, Value>,
1304        ) -> Result<Vec<Value>, FaucetError> {
1305            Ok(vec![])
1306        }
1307
1308        fn position_le(&self, a: &Value, b: &Value) -> Option<bool> {
1309            Some(a.as_u64()? <= b.as_u64()?)
1310        }
1311    }
1312
1313    #[test]
1314    fn default_position_min_uses_position_le() {
1315        let src = OrderedSource;
1316        assert_eq!(
1317            src.position_min(&[json!(5), json!(2), json!(9)]),
1318            Some(json!(2))
1319        );
1320        assert_eq!(src.position_min(&[json!(5), json!("x")]), None);
1321    }
1322
1323    struct IncrementalSource {
1324        records: Vec<Value>,
1325        bookmark: Value,
1326    }
1327
1328    #[async_trait]
1329    impl Source for IncrementalSource {
1330        async fn fetch_with_context(
1331            &self,
1332            _context: &std::collections::HashMap<String, Value>,
1333        ) -> Result<Vec<Value>, FaucetError> {
1334            Ok(self.records.clone())
1335        }
1336
1337        async fn fetch_with_context_incremental(
1338            &self,
1339            _context: &std::collections::HashMap<String, Value>,
1340        ) -> Result<(Vec<Value>, Option<Value>), FaucetError> {
1341            Ok((self.records.clone(), Some(self.bookmark.clone())))
1342        }
1343    }
1344
1345    struct FailingSource;
1346
1347    #[async_trait]
1348    impl Source for FailingSource {
1349        async fn fetch_with_context(
1350            &self,
1351            _context: &std::collections::HashMap<String, Value>,
1352        ) -> Result<Vec<Value>, FaucetError> {
1353            Err(FaucetError::Auth("no credentials".into()))
1354        }
1355    }
1356
1357    // ── Mock Sink ───────────────────────────────────────────────────────────
1358
1359    struct MockSink {
1360        written: std::sync::Mutex<Vec<Value>>,
1361    }
1362
1363    impl MockSink {
1364        fn new() -> Self {
1365            Self {
1366                written: std::sync::Mutex::new(Vec::new()),
1367            }
1368        }
1369    }
1370
1371    #[async_trait]
1372    impl Sink for MockSink {
1373        async fn write_batch(&self, records: &[Value]) -> Result<usize, FaucetError> {
1374            let mut w = self.written.lock().unwrap();
1375            w.extend(records.iter().cloned());
1376            Ok(records.len())
1377        }
1378    }
1379
1380    struct FailingSink;
1381
1382    #[async_trait]
1383    impl Sink for FailingSink {
1384        async fn write_batch(&self, _records: &[Value]) -> Result<usize, FaucetError> {
1385            Err(FaucetError::Sink("write failed".into()))
1386        }
1387    }
1388
1389    // ── Native byte-passthrough defaults (#633) ──────────────────────────────
1390
1391    /// A source/sink pair that advertises nothing native, so the defaulted
1392    /// trait methods are what answer.
1393    struct PlainSink;
1394
1395    #[async_trait]
1396    impl Sink for PlainSink {
1397        async fn write_batch(&self, records: &[Value]) -> Result<usize, FaucetError> {
1398            Ok(records.len())
1399        }
1400    }
1401
1402    #[tokio::test]
1403    async fn native_defaults_advertise_nothing_and_fail_loudly() {
1404        use futures::StreamExt as _;
1405
1406        // A source that never overrides the native methods advertises no
1407        // formats, so the pipeline can never negotiate the byte path…
1408        let src = MockSource { records: vec![] };
1409        assert!(src.native_output_formats().is_empty());
1410        // …and calling it anyway yields one typed error rather than silently
1411        // producing an empty stream (which would look like "no rows").
1412        let ctx = std::collections::HashMap::new();
1413        let mut batches = src.stream_native(&ctx, crate::native::NativeFormat::NdJson, 10);
1414        let err = batches
1415            .next()
1416            .await
1417            .expect("one item")
1418            .expect_err("default must error");
1419        assert!(
1420            err.to_string()
1421                .contains("does not support native byte streaming"),
1422            "{err}"
1423        );
1424        assert!(batches.next().await.is_none(), "exactly one item");
1425
1426        // Same on the sink side: no capabilities, and `load_native` is a typed
1427        // error so a sink that advertises but forgets to implement is obvious.
1428        let sink = PlainSink;
1429        assert!(sink.native_load_capabilities().is_empty());
1430        let err = sink
1431            .load_native(
1432                crate::native::NativeBatch::bytes(
1433                    crate::native::NativeFormat::NdJson,
1434                    b"{}\n".to_vec(),
1435                ),
1436                "scope",
1437                crate::native::NativeLoadContext {
1438                    write_mode: crate::write_mode::WriteMode::Append,
1439                    first_batch: true,
1440                },
1441            )
1442            .await
1443            .expect_err("default must error");
1444        assert!(
1445            err.to_string()
1446                .contains("does not support native byte loading"),
1447            "{err}"
1448        );
1449    }
1450
1451    #[tokio::test]
1452    async fn default_rollback_and_readback_hooks() {
1453        let sink = MockSink::new();
1454        assert!(!sink.supports_rollback());
1455        let opts = crate::rollback::RollbackOptions {
1456            run_id_column: "_faucet_run_id".into(),
1457            mode: crate::rollback::RollbackMode::Append,
1458            force: false,
1459            dry_run: false,
1460            later_runs: false,
1461        };
1462        let err = sink.rollback_run("r1", &opts).await.unwrap_err();
1463        assert!(
1464            err.to_string().contains("does not support rollback"),
1465            "{err}"
1466        );
1467        assert!(sink.forget_run("r1").await.is_ok());
1468        let err = sink.rewind_commit_token("s", None).await.unwrap_err();
1469        assert!(err.to_string().contains("commit token"), "{err}");
1470        assert!(sink.readback_source().is_none());
1471        let source = MockSource { records: vec![] };
1472        let digest = source
1473            .range_digest(&crate::diff::KeyRange::ALL, "id", &["v".into()])
1474            .await
1475            .unwrap();
1476        assert!(digest.is_none(), "not supported by default");
1477    }
1478
1479    #[tokio::test]
1480    async fn default_overwrite_methods_reject_or_noop() {
1481        // A sink that does not opt into overwrite (MockSink uses the defaults):
1482        // `is_overwrite` is false, begin/commit return the typed "unsupported"
1483        // error, and abort is a no-op success.
1484        let sink = MockSink::new();
1485        assert!(!sink.is_overwrite());
1486        assert!(sink.begin_overwrite().await.is_err());
1487        assert!(sink.commit_overwrite().await.is_err());
1488        assert!(sink.abort_overwrite().await.is_ok());
1489        assert_eq!(sink.overwrite_staging_exists().await.unwrap(), None);
1490    }
1491
1492    // ── Source tests ────────────────────────────────────────────────────────
1493
1494    #[tokio::test]
1495    async fn source_fetch_all_returns_records() {
1496        let source = MockSource {
1497            records: vec![json!({"id": 1}), json!({"id": 2})],
1498        };
1499        let records = source.fetch_all().await.unwrap();
1500        assert_eq!(records.len(), 2);
1501        assert_eq!(records[0]["id"], 1);
1502    }
1503
1504    #[tokio::test]
1505    async fn source_fetch_all_empty() {
1506        let source = MockSource { records: vec![] };
1507        let records = source.fetch_all().await.unwrap();
1508        assert!(records.is_empty());
1509    }
1510
1511    #[tokio::test]
1512    async fn source_default_incremental_returns_none_bookmark() {
1513        let source = MockSource {
1514            records: vec![json!({"id": 1})],
1515        };
1516        let (records, bookmark) = source.fetch_all_incremental().await.unwrap();
1517        assert_eq!(records.len(), 1);
1518        assert!(bookmark.is_none());
1519    }
1520
1521    #[tokio::test]
1522    async fn source_custom_incremental_returns_bookmark() {
1523        let source = IncrementalSource {
1524            records: vec![json!({"id": 1})],
1525            bookmark: json!("2024-12-01"),
1526        };
1527        let (records, bookmark) = source.fetch_all_incremental().await.unwrap();
1528        assert_eq!(records.len(), 1);
1529        assert_eq!(bookmark, Some(json!("2024-12-01")));
1530    }
1531
1532    #[tokio::test]
1533    async fn source_error_propagates() {
1534        let source = FailingSource;
1535        let result = source.fetch_all().await;
1536        assert!(result.is_err());
1537        assert!(matches!(result, Err(FaucetError::Auth(_))));
1538    }
1539
1540    #[tokio::test]
1541    async fn source_as_trait_object() {
1542        let source: Box<dyn Source> = Box::new(MockSource {
1543            records: vec![json!({"id": 42})],
1544        });
1545        let records = source.fetch_all().await.unwrap();
1546        assert_eq!(records[0]["id"], 42);
1547    }
1548
1549    // ── Sink tests ──────────────────────────────────────────────────────────
1550
1551    #[tokio::test]
1552    async fn sink_write_batch_returns_count() {
1553        let sink = MockSink::new();
1554        let records = vec![json!({"id": 1}), json!({"id": 2}), json!({"id": 3})];
1555        let count = sink.write_batch(&records).await.unwrap();
1556        assert_eq!(count, 3);
1557    }
1558
1559    #[tokio::test]
1560    async fn sink_write_batch_empty() {
1561        let sink = MockSink::new();
1562        let count = sink.write_batch(&[]).await.unwrap();
1563        assert_eq!(count, 0);
1564    }
1565
1566    #[tokio::test]
1567    async fn sink_accumulates_records() {
1568        let sink = MockSink::new();
1569        sink.write_batch(&[json!({"a": 1})]).await.unwrap();
1570        sink.write_batch(&[json!({"b": 2})]).await.unwrap();
1571        let written = sink.written.lock().unwrap();
1572        assert_eq!(written.len(), 2);
1573    }
1574
1575    #[tokio::test]
1576    async fn sink_default_flush_is_noop() {
1577        let sink = MockSink::new();
1578        assert!(sink.flush().await.is_ok());
1579    }
1580
1581    #[tokio::test]
1582    async fn sink_error_propagates() {
1583        let sink = FailingSink;
1584        let result = sink.write_batch(&[json!({"id": 1})]).await;
1585        assert!(result.is_err());
1586        assert!(matches!(result, Err(FaucetError::Sink(_))));
1587    }
1588
1589    #[tokio::test]
1590    async fn sink_as_trait_object() {
1591        let sink: Box<dyn Sink> = Box::new(MockSink::new());
1592        let count = sink.write_batch(&[json!({"id": 1})]).await.unwrap();
1593        assert_eq!(count, 1);
1594    }
1595
1596    // ── stream_pages tests ──────────────────────────────────────────────────
1597
1598    use crate::pipeline::DEFAULT_BATCH_SIZE;
1599    use futures::StreamExt;
1600
1601    #[tokio::test]
1602    async fn default_stream_pages_chunks_records() {
1603        let source = MockSource {
1604            records: (0..5).map(|i| json!({"i": i})).collect(),
1605        };
1606        let ctx = std::collections::HashMap::new();
1607        let mut pages = source.stream_pages(&ctx, 2);
1608        let mut all = Vec::new();
1609        while let Some(page) = pages.next().await {
1610            all.push(page.unwrap());
1611        }
1612        // 5 records, batch_size=2 → pages of [2, 2, 1]
1613        assert_eq!(all.len(), 3);
1614        assert_eq!(all[0].records.len(), 2);
1615        assert_eq!(all[1].records.len(), 2);
1616        assert_eq!(all[2].records.len(), 1);
1617    }
1618
1619    #[tokio::test]
1620    async fn default_stream_pages_attaches_bookmark_to_final_page_only() {
1621        let source = IncrementalSource {
1622            records: (0..5).map(|i| json!({"i": i})).collect(),
1623            bookmark: json!("v1"),
1624        };
1625        let ctx = std::collections::HashMap::new();
1626        let mut pages = source.stream_pages(&ctx, 2);
1627        let mut collected = Vec::new();
1628        while let Some(page) = pages.next().await {
1629            collected.push(page.unwrap());
1630        }
1631        assert_eq!(collected.len(), 3);
1632        assert!(collected[0].bookmark.is_none());
1633        assert!(collected[1].bookmark.is_none());
1634        assert_eq!(collected[2].bookmark, Some(json!("v1")));
1635    }
1636
1637    #[tokio::test]
1638    async fn default_stream_pages_single_page_when_batch_size_exceeds_total() {
1639        let source = MockSource {
1640            records: vec![json!({"id": 1}), json!({"id": 2})],
1641        };
1642        let ctx = std::collections::HashMap::new();
1643        let mut pages = source.stream_pages(&ctx, 100);
1644        let mut collected = Vec::new();
1645        while let Some(page) = pages.next().await {
1646            collected.push(page.unwrap());
1647        }
1648        assert_eq!(collected.len(), 1);
1649        assert_eq!(collected[0].records.len(), 2);
1650    }
1651
1652    #[tokio::test]
1653    async fn default_stream_pages_batch_size_zero_emits_single_page() {
1654        // batch_size = 0 is the "no batching" sentinel — yields every record
1655        // in one page regardless of total count.
1656        let source = MockSource {
1657            records: (0..50_000).map(|i| json!({"i": i})).collect(),
1658        };
1659        let ctx = std::collections::HashMap::new();
1660        let mut pages = source.stream_pages(&ctx, 0);
1661        let mut collected = Vec::new();
1662        while let Some(page) = pages.next().await {
1663            collected.push(page.unwrap());
1664        }
1665        assert_eq!(
1666            collected.len(),
1667            1,
1668            "batch_size=0 must emit exactly one page"
1669        );
1670        assert_eq!(collected[0].records.len(), 50_000);
1671    }
1672
1673    #[tokio::test]
1674    async fn default_stream_pages_batch_size_zero_attaches_bookmark_to_sole_page() {
1675        let source = IncrementalSource {
1676            records: (0..3).map(|i| json!({"i": i})).collect(),
1677            bookmark: json!("v1"),
1678        };
1679        let ctx = std::collections::HashMap::new();
1680        let mut pages = source.stream_pages(&ctx, 0);
1681        let page = pages.next().await.unwrap().unwrap();
1682        assert_eq!(page.records.len(), 3);
1683        assert_eq!(page.bookmark, Some(json!("v1")));
1684        assert!(pages.next().await.is_none());
1685    }
1686
1687    #[tokio::test]
1688    async fn default_stream_pages_empty_source_yields_no_pages() {
1689        let source = MockSource { records: vec![] };
1690        let ctx = std::collections::HashMap::new();
1691        let mut pages = source.stream_pages(&ctx, DEFAULT_BATCH_SIZE);
1692        assert!(pages.next().await.is_none());
1693    }
1694
1695    #[tokio::test]
1696    async fn default_stream_pages_empty_source_with_bookmark_yields_single_empty_page() {
1697        let source = IncrementalSource {
1698            records: vec![],
1699            bookmark: json!("v0"),
1700        };
1701        let ctx = std::collections::HashMap::new();
1702        let mut pages = source.stream_pages(&ctx, DEFAULT_BATCH_SIZE);
1703        let mut collected = Vec::new();
1704        while let Some(page) = pages.next().await {
1705            collected.push(page.unwrap());
1706        }
1707        // One empty-records page that carries the bookmark, so the pipeline
1708        // still persists progress on otherwise-empty incremental runs.
1709        assert_eq!(collected.len(), 1);
1710        assert!(collected[0].records.is_empty());
1711        assert_eq!(collected[0].bookmark, Some(json!("v0")));
1712    }
1713
1714    #[tokio::test]
1715    async fn default_stream_pages_propagates_fetch_errors() {
1716        let source = FailingSource;
1717        let ctx = std::collections::HashMap::new();
1718        let mut pages = source.stream_pages(&ctx, DEFAULT_BATCH_SIZE);
1719        let first = pages.next().await.unwrap();
1720        assert!(matches!(first, Err(FaucetError::Auth(_))));
1721    }
1722
1723    #[test]
1724    fn source_default_connector_name_is_stripped_type_name() {
1725        // MockSource lives at `faucet_core::traits::tests::MockSource`; the
1726        // stripped type_name yields the trailing segment.
1727        let source = MockSource { records: vec![] };
1728        assert_eq!(source.connector_name(), "MockSource");
1729    }
1730
1731    #[test]
1732    fn sink_default_connector_name_is_stripped_type_name() {
1733        let sink = MockSink::new();
1734        assert_eq!(sink.connector_name(), "MockSink");
1735    }
1736
1737    #[test]
1738    fn source_default_dataset_uri_uses_connector_name() {
1739        let source = MockSource { records: vec![] };
1740        assert_eq!(source.dataset_uri(), "MockSource://unknown");
1741    }
1742
1743    #[test]
1744    fn sink_default_dataset_uri_uses_connector_name() {
1745        let sink = MockSink::new();
1746        assert_eq!(sink.dataset_uri(), "MockSink://unknown");
1747    }
1748
1749    // ── write_batch_partial tests ───────────────────────────────────────────
1750
1751    #[tokio::test]
1752    async fn default_write_batch_partial_success_returns_all_ok() {
1753        let sink = MockSink::new();
1754        let records = vec![json!({"id": 1}), json!({"id": 2}), json!({"id": 3})];
1755        let outcomes = sink.write_batch_partial(&records).await.unwrap();
1756        assert_eq!(outcomes.len(), 3);
1757        assert!(outcomes.iter().all(|o| o.is_ok()));
1758        assert_eq!(sink.written.lock().unwrap().len(), 3);
1759    }
1760
1761    #[tokio::test]
1762    async fn default_write_batch_partial_bubbles_outer_err() {
1763        let sink = FailingSink;
1764        let records = vec![json!({"id": 1}), json!({"id": 2})];
1765        let result = sink.write_batch_partial(&records).await;
1766        assert!(matches!(result, Err(FaucetError::Sink(_))));
1767    }
1768
1769    #[tokio::test]
1770    async fn default_write_batch_partial_empty_returns_empty_vec() {
1771        let sink = MockSink::new();
1772        let outcomes = sink.write_batch_partial(&[]).await.unwrap();
1773        assert!(outcomes.is_empty());
1774    }
1775
1776    #[tokio::test]
1777    async fn default_write_batch_partial_callable_through_trait_object() {
1778        let sink: Box<dyn Sink> = Box::new(MockSink::new());
1779        let records = vec![json!({"id": 1}), json!({"id": 2})];
1780        let outcomes = sink.write_batch_partial(&records).await.unwrap();
1781        assert_eq!(outcomes.len(), 2);
1782        assert!(outcomes.iter().all(|o| o.is_ok()));
1783    }
1784
1785    // ── check() tests ─────────────────────────────────────────────────────────
1786
1787    #[tokio::test]
1788    async fn source_default_check_pulls_first_page_and_passes() {
1789        let source = MockSource {
1790            records: vec![json!({"id": 1}), json!({"id": 2})],
1791        };
1792        let report = source
1793            .check(&crate::check::CheckContext::default())
1794            .await
1795            .unwrap();
1796        assert_eq!(report.failed_count(), 0);
1797        assert!(
1798            report
1799                .probes
1800                .iter()
1801                .any(|p| p.name == "read" && matches!(p.status, crate::check::ProbeStatus::Pass))
1802        );
1803    }
1804
1805    #[tokio::test]
1806    async fn source_default_check_passes_on_empty_source() {
1807        let source = MockSource { records: vec![] };
1808        let report = source
1809            .check(&crate::check::CheckContext::default())
1810            .await
1811            .unwrap();
1812        // Reachable but empty is still a healthy source.
1813        assert_eq!(report.failed_count(), 0);
1814    }
1815
1816    #[tokio::test]
1817    async fn source_default_check_fails_when_fetch_errors() {
1818        let source = FailingSource;
1819        let report = source
1820            .check(&crate::check::CheckContext::default())
1821            .await
1822            .unwrap();
1823        assert_eq!(report.failed_count(), 1);
1824        assert!(report.probes.iter().any(
1825            |p| p.name == "read" && matches!(p.status, crate::check::ProbeStatus::Fail { .. })
1826        ));
1827    }
1828
1829    #[tokio::test]
1830    async fn sink_default_check_is_not_implemented_skip() {
1831        let sink = MockSink::new();
1832        let report = sink
1833            .check(&crate::check::CheckContext::default())
1834            .await
1835            .unwrap();
1836        assert_eq!(report.probes.len(), 1);
1837        assert!(matches!(
1838            report.probes[0].status,
1839            crate::check::ProbeStatus::Skip { .. }
1840        ));
1841    }
1842
1843    #[tokio::test]
1844    async fn source_check_callable_through_trait_object() {
1845        let source: Box<dyn Source> = Box::new(MockSource {
1846            records: vec![json!({"id": 1})],
1847        });
1848        let report = source
1849            .check(&crate::check::CheckContext::default())
1850            .await
1851            .unwrap();
1852        assert_eq!(report.failed_count(), 0);
1853    }
1854
1855    // ── idempotent-write / exactly-once capability tests ──────────────────────
1856
1857    #[tokio::test]
1858    async fn sink_default_is_not_idempotent() {
1859        let sink = MockSink::new();
1860        assert!(!sink.supports_idempotent_writes());
1861        // Default write_batch_idempotent ignores the token and delegates.
1862        let n = sink
1863            .write_batch_idempotent(&[json!({"id": 1})], "scope::a", "00000000000000000001")
1864            .await
1865            .unwrap();
1866        assert_eq!(n, 1);
1867        assert_eq!(sink.last_committed_token("scope::a").await.unwrap(), None);
1868        assert_eq!(sink.written.lock().unwrap().len(), 1);
1869    }
1870
1871    #[test]
1872    fn source_default_does_not_support_exactly_once() {
1873        let source = MockSource { records: vec![] };
1874        assert!(!source.supports_exactly_once());
1875    }
1876
1877    #[test]
1878    fn sink_default_supported_write_modes_is_append_only() {
1879        use crate::write_mode::WriteMode;
1880        let sink = MockSink::new();
1881        assert_eq!(sink.supported_write_modes(), &[WriteMode::Append]);
1882    }
1883
1884    #[test]
1885    fn supported_write_modes_callable_through_trait_object() {
1886        use crate::write_mode::WriteMode;
1887        let sink: Box<dyn Sink> = Box::new(MockSink::new());
1888        assert!(sink.supported_write_modes().contains(&WriteMode::Append));
1889    }
1890
1891    #[tokio::test]
1892    async fn sink_default_current_schema_is_none() {
1893        let sink = MockSink::new();
1894        assert_eq!(sink.current_schema().await.unwrap(), None);
1895    }
1896
1897    #[test]
1898    fn sink_default_does_not_support_schema_evolution() {
1899        let sink = MockSink::new();
1900        assert!(!sink.supports_schema_evolution());
1901    }
1902
1903    #[tokio::test]
1904    async fn sink_default_evolve_schema_is_unsupported_error() {
1905        let sink = MockSink::new();
1906        let evo = crate::drift::SchemaEvolution::default();
1907        let err = sink.evolve_schema(&evo).await.unwrap_err();
1908        assert!(matches!(err, FaucetError::Sink(_)));
1909        assert!(err.to_string().contains("schema evolution"));
1910    }
1911
1912    #[tokio::test]
1913    async fn source_default_capture_resume_position_is_none() {
1914        let source = MockSource { records: vec![] };
1915        assert_eq!(source.capture_resume_position().await.unwrap(), None);
1916    }
1917
1918    #[tokio::test]
1919    async fn capture_resume_position_callable_through_trait_object() {
1920        let source: Box<dyn Source> = Box::new(MockSource { records: vec![] });
1921        assert!(source.capture_resume_position().await.unwrap().is_none());
1922    }
1923
1924    #[tokio::test]
1925    async fn source_default_does_not_support_discover() {
1926        let source: Box<dyn Source> = Box::new(MockSource { records: vec![] });
1927        assert!(!source.supports_discover());
1928        let err = source.discover().await.unwrap_err();
1929        assert!(matches!(err, FaucetError::Source(_)));
1930        assert!(
1931            err.to_string().contains("dataset discovery"),
1932            "typed unsupported error: {err}"
1933        );
1934    }
1935
1936    #[tokio::test]
1937    async fn source_default_is_not_shardable() {
1938        let source: Box<dyn Source> = Box::new(MockSource { records: vec![] });
1939        assert!(!source.is_shardable());
1940    }
1941
1942    #[tokio::test]
1943    async fn source_default_enumerates_single_whole_shard() {
1944        // A non-shardable source enumerates to exactly one whole-dataset shard,
1945        // regardless of the requested target — preserving single-worker behavior.
1946        let source: Box<dyn Source> = Box::new(MockSource { records: vec![] });
1947        let shards = source.enumerate_shards(8).await.unwrap();
1948        assert_eq!(shards.len(), 1);
1949        assert!(shards[0].is_whole());
1950    }
1951
1952    #[tokio::test]
1953    async fn source_default_apply_shard_is_noop() {
1954        let source: Box<dyn Source> = Box::new(MockSource { records: vec![] });
1955        // Applying the whole shard is a no-op and must not error.
1956        source
1957            .apply_shard(&crate::shard::ShardSpec::whole())
1958            .await
1959            .unwrap();
1960    }
1961}