Skip to content
1 change: 1 addition & 0 deletions crates/ourios-core/src/alias.rs
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,7 @@ impl AliasMap {
// unknown kinds by construction.
AuditPayload::Template { .. }
| AuditPayload::Compaction { .. }
| AuditPayload::RecordQuarantined { .. }
| AuditPayload::Unknown { .. } => {}
}
}
Expand Down
23 changes: 23 additions & 0 deletions crates/ourios-core/src/audit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,20 @@ pub enum AuditPayload {
/// rows, the conserved count (RFC0009.2).
rows: u64,
},
/// A permanently-rejected record was diverted out of the ingest
/// sink's partition buffer instead of wedging it (RFC 0025
/// §3.3). System-scoped like [`Self::Compaction`]; carries no
/// template identity. The WAL still holds the record — this
/// event is the operator's pointer to it.
RecordQuarantined {
/// The data partition whose buffer held the record, as the
/// canonical `year=…/month=…/day=…/hour=…` key under the
/// event's `tenant_id` (RFC 0005 §3.4).
partition: String,
/// The permanent encode error's rendering — why this record
/// can never be written.
error: String,
},
}

/// Stable on-disk `event_kind` ordinals (RFC 0005 §3.7 mapping).
Expand All @@ -242,6 +256,10 @@ pub const EVENT_KIND_ALIAS_RETRACTED: u8 = 5;
/// an **append-only** addition (next free ordinal, no renumber): old readers
/// surface it via the [`AuditPayload::Unknown`] tolerance path (RFC 0005 §3.7).
pub const EVENT_KIND_TEMPLATE_CREATED: u8 = 6;
/// See [`EVENT_KIND_TEMPLATE_WIDENED`]. RFC 0025 §3.3 sink quarantine —
/// append-only addition; old readers surface it via the
/// [`AuditPayload::Unknown`] tolerance path.
pub const EVENT_KIND_RECORD_QUARANTINED: u8 = 7;

/// Canonical `event_type` strings paired with the ordinals above
/// (RFC 0005 §3.7 / RFC 0001 §6.4 / RFC 0009 §3.6).
Expand All @@ -259,6 +277,8 @@ pub const EVENT_TYPE_ALIAS_ASSERTED: &str = "alias_asserted";
pub const EVENT_TYPE_ALIAS_RETRACTED: &str = "alias_retracted";
/// See [`EVENT_TYPE_TEMPLATE_WIDENED`]. RFC 0017 §3.1 leaf-creation audit.
pub const EVENT_TYPE_TEMPLATE_CREATED: &str = "template_created";
/// See [`EVENT_TYPE_TEMPLATE_WIDENED`]. RFC 0025 §3.3 sink quarantine.
pub const EVENT_TYPE_RECORD_QUARANTINED: &str = "record_quarantined";

/// The `template_version` a leaf is born at (RFC 0017 §3.1). The
/// [`TemplateChange::Created`] variant omits a version field — the invariant
Expand All @@ -284,6 +304,7 @@ impl AuditPayload {
Self::AliasAsserted { .. } => EVENT_KIND_ALIAS_ASSERTED,
Self::AliasRetracted { .. } => EVENT_KIND_ALIAS_RETRACTED,
Self::Compaction { .. } => EVENT_KIND_COMPACTION,
Self::RecordQuarantined { .. } => EVENT_KIND_RECORD_QUARANTINED,
Self::Unknown { event_kind, .. } => *event_kind,
}
}
Expand All @@ -306,6 +327,7 @@ impl AuditPayload {
Self::AliasAsserted { .. } => EVENT_TYPE_ALIAS_ASSERTED,
Self::AliasRetracted { .. } => EVENT_TYPE_ALIAS_RETRACTED,
Self::Compaction { .. } => EVENT_TYPE_COMPACTION,
Self::RecordQuarantined { .. } => EVENT_TYPE_RECORD_QUARANTINED,
Self::Unknown { event_type, .. } => event_type,
}
}
Expand All @@ -325,6 +347,7 @@ impl AuditPayload {
Self::AliasAsserted { .. }
| Self::AliasRetracted { .. }
| Self::Compaction { .. }
| Self::RecordQuarantined { .. }
| Self::Unknown { .. } => false,
}
}
Expand Down
10 changes: 8 additions & 2 deletions crates/ourios-ingester/src/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -397,8 +397,14 @@ impl SinkMetrics {

/// A failed partition flush (encode or store error); the buffer is
/// retained and retried (the WAL is the durability of record).
pub fn record_flush_error(&self) {
self.flush_errors.add(1, &[]);
/// `error_type` carries the permanent-rejection class for
/// quarantines (RFC 0025 §3.3, the `error.type` convention);
/// transient store failures pass `None`.
pub fn record_flush_error(&self, error_type: Option<&'static str>) {
match error_type {
Some(t) => self.flush_errors.add(1, &[KeyValue::new(ERROR_TYPE, t)]),
None => self.flush_errors.add(1, &[]),
}
}

/// A record dropped from the sink because its partition key could not
Expand Down
210 changes: 194 additions & 16 deletions crates/ourios-ingester/src/record_sink.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,12 @@ pub struct ParquetRecordSink {
/// atomic w.r.t. ingest. `None` (the RFC 0014 default + the record-sink unit
/// tests) leaves the inline publish unconstrained.
audit_barrier: Option<Box<dyn FnMut() -> bool + Send>>,
/// RFC 0025 §3.3 quarantine destination: permanently-rejected
/// records emit a `record_quarantined` audit event here before
/// being dropped from the buffer (the WAL still holds them).
/// `None` (tests / minimal wiring) quarantines silently to the
/// counter only.
audit: Option<Box<dyn ourios_core::audit::AuditSink + Send>>,
/// RFC 0014 §6.3 instruments (flush throughput/latency by trigger,
/// errors, buffer occupancy). No-op when no meter provider is installed.
metrics: SinkMetrics,
Expand All @@ -133,6 +139,50 @@ fn estimate_bytes(r: &MinedRecord) -> usize {
+ (r.attributes.len() + r.resource_attributes.len()) * 48
}

/// Whether `e` condemns a specific record (RFC 0025 §3.3 quarantine
/// territory) rather than signalling an internal invariant violation.
/// `Arrow` means *our* batch-building broke — quarantining on it
/// would drop data on our own bug; those retain the buffer for retry
/// and investigation like any other non-record failure.
fn is_per_record_rejection(e: &ourios_parquet::BatchError) -> bool {
!matches!(e, ourios_parquet::BatchError::Arrow(_))
}

/// Bisect `records` into `(encodable, permanently rejected)` using
/// the batch conversion as the probe — `BatchError` is deterministic,
/// so a failing subset always shrinks to its poison records.
/// O(k·log n) probes for k poison records.
fn split_poisoned(
records: Vec<ourios_core::record::MinedRecord>,
promoted: &ourios_parquet::PromotedAttributes,
) -> (
Vec<ourios_core::record::MinedRecord>,
Vec<(ourios_core::record::MinedRecord, ourios_parquet::BatchError)>,
) {
match ourios_parquet::mined_records_to_batch_with_promoted(&records, promoted) {
Ok(_) => (records, Vec::new()),
Err(error) => {
if records.len() == 1 {
if !is_per_record_rejection(&error) {
// Internal invariant violation, not this record's
// fault — keep it; the flush will fail and retain.
return (records, Vec::new());
}
let record = records.into_iter().next().expect("len checked");
return (Vec::new(), vec![(record, error)]);
}
let mid = records.len() / 2;
let mut left = records;
let right = left.split_off(mid);
let (mut kept, mut poisoned) = split_poisoned(left, promoted);
let (kept_r, poisoned_r) = split_poisoned(right, promoted);
kept.extend(kept_r);
poisoned.extend(poisoned_r);
(kept, poisoned)
}
}
}

/// `/`-delimited object key for a partition's flushed file: the RFC 0005 §3.4
/// Hive path (relative to the store root) plus a `UUIDv7` name. Mirrors
/// `ourios_parquet::Writer`'s key; object keys are `/`-delimited on every host.
Expand Down Expand Up @@ -160,6 +210,7 @@ impl ParquetRecordSink {
flush_errors: 0,
derive_errors: 0,
audit_barrier: None,
audit: None,
metrics: SinkMetrics::new(),
promoted: PromotedAttributes::default(),
}
Expand All @@ -173,6 +224,15 @@ impl ParquetRecordSink {
self
}

/// Install the RFC 0025 §3.3 quarantine audit destination:
/// permanently-rejected records emit a `record_quarantined`
/// event here before being dropped from the buffer.
#[must_use]
pub fn with_audit_sink(mut self, sink: Box<dyn ourios_core::audit::AuditSink + Send>) -> Self {
self.audit = Some(sink);
self
}

/// Install the audit-durability barrier (issue #302 fix #2): a closure run
/// before any inline size/ceiling publish that flushes the audit sink and
/// returns whether it fully drained. When it returns `false` the inline
Expand Down Expand Up @@ -259,12 +319,42 @@ impl ParquetRecordSink {
) -> Result<(), FlushError> {
let flush_start = Instant::now();
let bytes = match self.buffers.get(key) {
Some(buf) if !buf.records.is_empty() => encode_records_to_parquet_with_promoted(
&buf.records,
DEFAULT_ZSTD_LEVEL,
&self.promoted,
)
.map_err(FlushError::Encode)?,
Some(buf) if !buf.records.is_empty() => {
match encode_records_to_parquet_with_promoted(
&buf.records,
DEFAULT_ZSTD_LEVEL,
&self.promoted,
) {
Ok(bytes) => bytes,
Err(WriterError::Batch(e)) if is_per_record_rejection(&e) => {
// A permanent per-record rejection (RFC 0025
// §3.3): retrying the whole buffer would wedge
// the partition forever (#362). Quarantine the
// poisoned record(s) and encode the remainder;
// the WAL keeps the originals.
self.quarantine_poisoned(key);
match self.buffers.get(key) {
Some(buf) if !buf.records.is_empty() => {
encode_records_to_parquet_with_promoted(
&buf.records,
DEFAULT_ZSTD_LEVEL,
&self.promoted,
)
.map_err(FlushError::Encode)?
}
_ => {
// Every record quarantined: drop the
// emptied entry and release its byte
// accounting, or the ceiling logic and
// buffer gauge drift forever.
self.drop_emptied_buffer(key);
return Ok(());
}
}
}
Err(e) => return Err(FlushError::Encode(e)),
}
}
_ => return Ok(()),
};
self.store
Expand All @@ -283,14 +373,82 @@ impl ParquetRecordSink {
Ok(())
}

/// Remove `key`'s (empty) buffer entry and release its byte
/// accounting — the flush-success bookkeeping minus the flush
/// counters (nothing was published).
fn drop_emptied_buffer(&mut self, key: &PartitionKey) {
if let Some(buf) = self.buffers.remove(key) {
debug_assert!(buf.records.is_empty(), "only for emptied buffers");
self.total_bytes = self.total_bytes.saturating_sub(buf.est_bytes);
self.metrics
.add_buffered(-i64::try_from(buf.est_bytes).unwrap_or(i64::MAX));
}
}

/// Split `key`'s buffer into encodable records and permanently
/// rejected ones; emit a `record_quarantined` audit event and the
/// `error.type`-attributed flush-error count for each rejection,
/// then drop the poison from the buffer and release its byte
/// accounting (RFC 0025 §3.3 — the WAL remains the durability of
/// record; the audit event is the operator's pointer for replay
/// after a fix).
fn quarantine_poisoned(&mut self, key: &PartitionKey) {
let records = match self.buffers.get_mut(key) {
Some(buf) => std::mem::take(&mut buf.records),
None => return,
};
let before: usize = records.iter().map(estimate_bytes).sum();
let kept = self.quarantine_owned(key, records);
let after: usize = kept.iter().map(estimate_bytes).sum();
// Release the dropped records' share of the byte accounting
// (same estimator as emit) so ceiling triggers and the buffer
// gauge track what is actually buffered.
let freed = before.saturating_sub(after);
self.total_bytes = self.total_bytes.saturating_sub(freed);
self.metrics
.add_buffered(-i64::try_from(freed).unwrap_or(i64::MAX));
if let Some(buf) = self.buffers.get_mut(key) {
buf.est_bytes = buf.est_bytes.saturating_sub(freed);
buf.records = kept;
}
}

/// [`Self::quarantine_poisoned`] over an owned batch (the
/// cadence-drain path) — returns the encodable remainder.
fn quarantine_owned(
&mut self,
key: &PartitionKey,
records: Vec<MinedRecord>,
) -> Vec<MinedRecord> {
let (kept, poisoned) = split_poisoned(records, &self.promoted);
let partition = format!(
"year={:04}/month={:02}/day={:02}/hour={:02}",
key.year, key.month, key.day, key.hour
);
for (record, error) in poisoned {
self.metrics.record_flush_error(Some(error.error_type()));
if let Some(audit) = &mut self.audit {
audit.emit(ourios_core::audit::AuditEvent {
tenant_id: record.tenant_id.clone(),
timestamp: std::time::SystemTime::now(),
payload: ourios_core::audit::AuditPayload::RecordQuarantined {
partition: partition.clone(),
error: error.to_string(),
},
});
}
}
kept
}

/// [`Self::flush_partition`] for the infallible `emit` / tick / rotation
/// paths: a failed flush retains the buffer (the WAL is the durability of
/// record) and is counted for observability. `trigger` records *why* the
/// flush happened (RFC 0014 §3.2).
fn flush_partition_swallow(&mut self, key: &PartitionKey, trigger: &'static str) {
if self.flush_partition(key, trigger).is_err() {
self.flush_errors += 1;
self.metrics.record_flush_error();
self.metrics.record_flush_error(None);
}
}

Expand All @@ -311,7 +469,7 @@ impl ParquetRecordSink {
true
} else {
self.flush_errors += 1;
self.metrics.record_flush_error();
self.metrics.record_flush_error(None);
false
}
}
Expand Down Expand Up @@ -401,7 +559,7 @@ impl ParquetRecordSink {
/// requeued by the caller).
pub fn note_flush_error(&mut self) {
self.flush_errors += 1;
self.metrics.record_flush_error();
self.metrics.record_flush_error(None);
}

/// A clone of the data store, for the coordinator's off-lock publish.
Expand Down Expand Up @@ -545,13 +703,33 @@ impl SharedParquetSink {
let mut all_published = true;
for (key, records) in batches {
let start = Instant::now();
if publish_partition(&store, &key, &records, &promoted).is_ok() {
self.lock()
.note_published(records.len(), start.elapsed(), trigger);
} else {
self.lock().note_flush_error();
requeue.push((key, records));
all_published = false;
match publish_partition(&store, &key, &records, &promoted) {
Ok(()) => {
self.lock()
.note_published(records.len(), start.elapsed(), trigger);
}
Err(FlushError::Encode(WriterError::Batch(e))) if is_per_record_rejection(&e) => {
// Permanent per-record rejection: requeueing would
// re-fail forever (#362 via the cadence path).
// Quarantine and publish the remainder once.
let kept = self.lock().quarantine_owned(&key, records);
if kept.is_empty() {
continue;
}
if publish_partition(&store, &key, &kept, &promoted).is_ok() {
self.lock()
.note_published(kept.len(), start.elapsed(), trigger);
} else {
self.lock().note_flush_error();
requeue.push((key, kept));
all_published = false;
}
}
Comment thread
jensholdgaard marked this conversation as resolved.
Resolved
Err(_) => {
self.lock().note_flush_error();
requeue.push((key, records));
all_published = false;
}
}
}
if !requeue.is_empty() {
Expand Down
2 changes: 1 addition & 1 deletion crates/ourios-ingester/tests/perf_metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ async fn ingest_and_sink_metrics_export_under_their_registry_names() {
ingest.record_batch(10, 0, Duration::from_millis(2));
sink.record_flush("size", 5, Duration::from_millis(7));
sink.record_flush("rotation", 3, Duration::from_millis(9));
sink.record_flush_error();
sink.record_flush_error(None);
sink.record_derive_error();
sink.add_buffered(100);
sink.add_buffered(-40);
Expand Down
Loading