reddb-io-server 1.12.0

RedDB server-side engine: storage, runtime, replication, MCP, AI, and the gRPC/HTTP/RedWire/PG-wire dispatchers. Re-exported by the umbrella `reddb` crate.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! Commit policy resolution for multi-writer clusters (issue #1001, PRD #987).
//!
//! A cluster has one global default [`CommitPolicy`], and a collection may
//! declare a stricter or looser override when its model semantics justify it
//! (see the [clustering glossary](../../../.red/context/clustering.md) entries
//! *Commit policy* and *Ephemeral-local commit*). This module is the single
//! deterministic place that combines those two inputs into the **effective**
//! policy a write actually commits under, and enforces the one safety rule that
//! the raw [`CommitPolicy`] type cannot express on its own:
//!
//! > Durable transactional, queue, audit, config, and vault collections must not
//! > *silently* use local-only acknowledgement once HA intent is declared.
//! > Only collections explicitly declared ephemeral/cache-like may opt into
//! > `local` commit, and they do so with documented failover semantics.
//!
//! ## Why a resolver rather than a field on the collection
//!
//! The effective policy is a function of three independent inputs — the cluster
//! default, the per-collection override, and whether the deployment has declared
//! HA intent — and the guardrail couples all three. Resolving them ad hoc at each
//! call site (write admission *and* failover eligibility both need the answer)
//! would let the two paths drift, so a misconfigured durable collection could be
//! admitted with `local` on the write path while failover still believed it was
//! quorum-durable. A single pure resolver keeps both paths reading the same
//! decision and makes the guardrail testable in isolation.
//!
//! ## Resolution
//!
//! 1. The effective policy is the collection override if present, otherwise the
//!    cluster default ([`ResolutionSource`] records which won).
//! 2. If the effective policy is local-only acknowledgement (`Local`, or the
//!    degenerate `AckN(0)` which [the policy docs](super::super::replication::commit_policy)
//!    define as equivalent to `Local`) **and** HA intent is declared:
//!    - a **durable** model ([`CollectionDataModel::is_durable`]) is rejected with
//!      [`CommitPolicyViolation::DurableLocalUnderHa`] — fail closed, the caller
//!      must not admit writes under a silently-degraded policy.
//!    - an **ephemeral/cache-like** model is allowed, tagged
//!      [`GuardrailDisposition::EphemeralLocalAllowed`] so the decision is
//!      explicit in the audit trail.
//! 3. Otherwise the resolution succeeds; the guardrail is
//!    [`GuardrailDisposition::Satisfied`] for a durable model under declared HA
//!    intent (the effective policy is genuinely durable), or
//!    [`GuardrailDisposition::NotApplicable`] when HA intent is not declared.
//!
//! The resolved policy also reports its **failover eligibility**
//! ([`CommitPolicyResolution::failover_eligibility`]): a durable policy means a
//! candidate may be promoted only if its log covers the range commit watermark,
//! while a local-ack policy carries an explicit data-loss window — the documented
//! failover semantics ephemeral/cache collections accept in exchange for `local`.

use crate::replication::CommitPolicy;

/// The durability model a collection declares for itself. The first five are
/// **durable** models whose data must survive a single-node loss; the last two
/// are explicitly **local-eligible** — losing their most recent unreplicated
/// writes on failover is an accepted trade for lower write latency.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CollectionDataModel {
    /// Durable transactional records — the default model for user data.
    Transactional,
    /// Durable work-queue collection (at-least-once delivery semantics).
    Queue,
    /// Append-only audit log.
    Audit,
    /// Cluster/application configuration.
    Config,
    /// Secret/credential material.
    Vault,
    /// Explicitly ephemeral data with no durability expectation.
    Ephemeral,
    /// Cache-like data that can be rebuilt from a source of truth.
    Cache,
}

impl CollectionDataModel {
    /// `true` for models whose data must survive a single-node loss and so may
    /// never silently acknowledge a write locally under declared HA intent.
    pub fn is_durable(self) -> bool {
        match self {
            Self::Transactional | Self::Queue | Self::Audit | Self::Config | Self::Vault => true,
            Self::Ephemeral | Self::Cache => false,
        }
    }

    /// `true` for the explicitly local-eligible models (`Ephemeral`, `Cache`)
    /// that may opt into local commit even under declared HA intent.
    pub fn allows_ephemeral_local(self) -> bool {
        !self.is_durable()
    }

    pub fn label(self) -> &'static str {
        match self {
            Self::Transactional => "transactional",
            Self::Queue => "queue",
            Self::Audit => "audit",
            Self::Config => "config",
            Self::Vault => "vault",
            Self::Ephemeral => "ephemeral",
            Self::Cache => "cache",
        }
    }
}

/// Whether the deployment has declared HA intent. The guardrail only restricts
/// local-only acknowledgement once intent is [`Declared`](Self::Declared); a
/// single-writer / non-HA deployment resolves policies without restriction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum HaIntent {
    /// Multi-writer HA mode: durable models may not silently use `local`.
    Declared,
    /// No HA intent declared — the guardrail does not apply.
    #[default]
    None,
}

impl HaIntent {
    pub fn is_declared(self) -> bool {
        matches!(self, Self::Declared)
    }

    /// Parse from `RED_CLUSTER_HA_INTENT`. Truthy (`true`/`1`/`yes`/`declared`)
    /// means [`Declared`](Self::Declared); anything else (including unset) means
    /// [`None`](Self::None) so the guardrail stays off unless opted into.
    pub fn from_env() -> Self {
        match std::env::var("RED_CLUSTER_HA_INTENT") {
            Ok(raw) => Self::parse(raw.trim()),
            Err(_) => Self::None,
        }
    }

    pub fn parse(raw: &str) -> Self {
        let t = raw.trim();
        if t.eq_ignore_ascii_case("true")
            || t == "1"
            || t.eq_ignore_ascii_case("yes")
            || t.eq_ignore_ascii_case("declared")
        {
            Self::Declared
        } else {
            Self::None
        }
    }
}

/// Which input supplied the effective policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResolutionSource {
    /// No collection override; the cluster global default applied.
    ClusterDefault,
    /// The collection's own override applied.
    CollectionOverride,
}

impl ResolutionSource {
    pub fn label(self) -> &'static str {
        match self {
            Self::ClusterDefault => "cluster_default",
            Self::CollectionOverride => "collection_override",
        }
    }
}

/// How the ephemeral-local guardrail dispositioned a successful resolution.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GuardrailDisposition {
    /// HA intent not declared — the guardrail did not run.
    NotApplicable,
    /// Durable model under declared HA intent with a genuinely durable effective
    /// policy: the guardrail ran and was satisfied.
    Satisfied,
    /// Ephemeral/cache-like model explicitly permitted to use local commit under
    /// declared HA intent (documented failover semantics apply).
    EphemeralLocalAllowed,
}

/// Failover implication of a resolved commit policy. Consumed by failover
/// eligibility: a durable policy gates promotion on watermark coverage, while a
/// local-ack policy admits an explicit data-loss window on the promoted node.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FailoverEligibility {
    /// The effective policy is durable: a candidate may be promoted only if its
    /// applied log covers the range commit watermark.
    RequiresWatermarkCoverage,
    /// The effective policy is local-only: a promoted candidate may not have the
    /// failed owner's most recent local-only writes — an accepted, documented
    /// loss window for ephemeral/cache-like data.
    LocalAckDataLossWindow,
}

/// The deterministic outcome of resolving a cluster default + collection
/// override + HA intent against a collection's data model.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CommitPolicyResolution {
    /// The policy the write actually commits under.
    pub effective: CommitPolicy,
    /// Which input supplied [`effective`](Self::effective).
    pub source: ResolutionSource,
    /// How the guardrail dispositioned this resolution.
    pub guardrail: GuardrailDisposition,
}

impl CommitPolicyResolution {
    /// `true` when the effective policy requires durability beyond the local WAL,
    /// i.e. failover must gate promotion on range-commit-watermark coverage.
    pub fn requires_durable_watermark(&self) -> bool {
        !is_local_ack(self.effective)
    }

    /// Failover implication of the resolved policy. See [`FailoverEligibility`].
    pub fn failover_eligibility(&self) -> FailoverEligibility {
        if self.requires_durable_watermark() {
            FailoverEligibility::RequiresWatermarkCoverage
        } else {
            FailoverEligibility::LocalAckDataLossWindow
        }
    }
}

/// Rejection raised when resolution would silently degrade a durable model to
/// local-only acknowledgement under declared HA intent. The caller must fail
/// closed rather than admit writes under the degraded policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CommitPolicyViolation {
    /// A durable model resolved to local-only acknowledgement under declared HA
    /// intent. `source` records whether the offending policy came from the
    /// cluster default or the collection's own override.
    DurableLocalUnderHa {
        model: CollectionDataModel,
        source: ResolutionSource,
    },
}

impl CommitPolicyViolation {
    pub fn message(&self) -> String {
        match self {
            Self::DurableLocalUnderHa { model, source } => format!(
                "durable collection model '{}' may not use local-only commit acknowledgement \
                 under declared HA intent (policy source: {})",
                model.label(),
                source.label()
            ),
        }
    }
}

impl std::fmt::Display for CommitPolicyViolation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.message())
    }
}

impl std::error::Error for CommitPolicyViolation {}

/// `true` when `policy` acknowledges a commit on local WAL durability alone:
/// `Local`, or the degenerate `AckN(0)` the policy docs define as equivalent.
pub fn is_local_ack(policy: CommitPolicy) -> bool {
    matches!(policy, CommitPolicy::Local | CommitPolicy::AckN(0))
}

/// Deterministically resolve the effective commit policy for one collection.
///
/// `cluster_default` is the global default; `collection_override` is the
/// collection's declared override (if any); `model` is the collection's
/// durability model; `ha_intent` is whether the deployment declared HA intent.
///
/// Returns the resolved policy, or [`CommitPolicyViolation`] when the guardrail
/// rejects a durable model degraded to local-only acknowledgement under HA
/// intent. The function is pure and side-effect free.
pub fn resolve_commit_policy(
    cluster_default: CommitPolicy,
    collection_override: Option<CommitPolicy>,
    model: CollectionDataModel,
    ha_intent: HaIntent,
) -> Result<CommitPolicyResolution, CommitPolicyViolation> {
    let (effective, source) = match collection_override {
        Some(p) => (p, ResolutionSource::CollectionOverride),
        None => (cluster_default, ResolutionSource::ClusterDefault),
    };

    let guardrail = if !ha_intent.is_declared() {
        // No HA intent: the guardrail does not constrain the resolution.
        GuardrailDisposition::NotApplicable
    } else if is_local_ack(effective) {
        if model.is_durable() {
            return Err(CommitPolicyViolation::DurableLocalUnderHa { model, source });
        }
        // Ephemeral/cache-like: explicitly permitted to opt into local commit.
        GuardrailDisposition::EphemeralLocalAllowed
    } else {
        // Durable model under declared HA intent with a genuinely durable policy.
        GuardrailDisposition::Satisfied
    };

    Ok(CommitPolicyResolution {
        effective,
        source,
        guardrail,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    const DURABLE: [CollectionDataModel; 5] = [
        CollectionDataModel::Transactional,
        CollectionDataModel::Queue,
        CollectionDataModel::Audit,
        CollectionDataModel::Config,
        CollectionDataModel::Vault,
    ];
    const LOCAL_ELIGIBLE: [CollectionDataModel; 2] =
        [CollectionDataModel::Ephemeral, CollectionDataModel::Cache];

    #[test]
    fn data_model_durability_partition() {
        for m in DURABLE {
            assert!(m.is_durable(), "{} should be durable", m.label());
            assert!(!m.allows_ephemeral_local());
        }
        for m in LOCAL_ELIGIBLE {
            assert!(!m.is_durable(), "{} should not be durable", m.label());
            assert!(m.allows_ephemeral_local());
        }
    }

    #[test]
    fn is_local_ack_treats_ack0_as_local() {
        assert!(is_local_ack(CommitPolicy::Local));
        assert!(is_local_ack(CommitPolicy::AckN(0)));
        assert!(!is_local_ack(CommitPolicy::AckN(1)));
        assert!(!is_local_ack(CommitPolicy::Quorum));
        assert!(!is_local_ack(CommitPolicy::RemoteWal));
    }

    // AC: default quorum behavior — cluster default applies with no override.
    #[test]
    fn cluster_default_quorum_applies_without_override() {
        let r = resolve_commit_policy(
            CommitPolicy::Quorum,
            None,
            CollectionDataModel::Transactional,
            HaIntent::Declared,
        )
        .expect("quorum default is durable under HA");
        assert_eq!(r.effective, CommitPolicy::Quorum);
        assert_eq!(r.source, ResolutionSource::ClusterDefault);
        assert_eq!(r.guardrail, GuardrailDisposition::Satisfied);
        assert_eq!(
            r.failover_eligibility(),
            FailoverEligibility::RequiresWatermarkCoverage
        );
    }

    // AC: collection override — a stricter/looser override beats the default.
    #[test]
    fn collection_override_beats_cluster_default() {
        let r = resolve_commit_policy(
            CommitPolicy::AckN(1),
            Some(CommitPolicy::Quorum),
            CollectionDataModel::Audit,
            HaIntent::Declared,
        )
        .expect("override quorum is durable");
        assert_eq!(r.effective, CommitPolicy::Quorum);
        assert_eq!(r.source, ResolutionSource::CollectionOverride);
        assert_eq!(r.guardrail, GuardrailDisposition::Satisfied);
    }

    // AC: local commit allowed for ephemeral/cache-like data under HA intent.
    #[test]
    fn local_commit_allowed_for_ephemeral_cache_under_ha() {
        for m in LOCAL_ELIGIBLE {
            // via cluster default
            let r = resolve_commit_policy(CommitPolicy::Local, None, m, HaIntent::Declared)
                .unwrap_or_else(|e| panic!("{} local should be allowed: {e}", m.label()));
            assert_eq!(r.effective, CommitPolicy::Local);
            assert_eq!(r.guardrail, GuardrailDisposition::EphemeralLocalAllowed);
            assert_eq!(
                r.failover_eligibility(),
                FailoverEligibility::LocalAckDataLossWindow
            );
            assert!(!r.requires_durable_watermark());

            // via explicit override, and the AckN(0) degenerate form
            let r = resolve_commit_policy(
                CommitPolicy::Quorum,
                Some(CommitPolicy::AckN(0)),
                m,
                HaIntent::Declared,
            )
            .expect("ack_n=0 is local-eligible for ephemeral/cache");
            assert_eq!(r.guardrail, GuardrailDisposition::EphemeralLocalAllowed);
        }
    }

    // AC: local commit rejected for durable models under HA intent.
    #[test]
    fn local_commit_rejected_for_durable_models_under_ha() {
        for m in DURABLE {
            // via cluster default
            let err = resolve_commit_policy(CommitPolicy::Local, None, m, HaIntent::Declared)
                .expect_err("durable local must be rejected under HA");
            assert_eq!(
                err,
                CommitPolicyViolation::DurableLocalUnderHa {
                    model: m,
                    source: ResolutionSource::ClusterDefault,
                }
            );
            assert!(err.message().contains(m.label()));

            // via override, including the AckN(0) degenerate form
            let err = resolve_commit_policy(
                CommitPolicy::Quorum,
                Some(CommitPolicy::AckN(0)),
                m,
                HaIntent::Declared,
            )
            .expect_err("durable ack_n=0 override must be rejected under HA");
            assert_eq!(
                err,
                CommitPolicyViolation::DurableLocalUnderHa {
                    model: m,
                    source: ResolutionSource::CollectionOverride,
                }
            );
        }
    }

    // Guardrail only bites under declared HA intent: a non-HA deployment may use
    // local commit for any model.
    #[test]
    fn local_commit_allowed_for_durable_when_ha_not_declared() {
        for m in DURABLE {
            let r = resolve_commit_policy(CommitPolicy::Local, None, m, HaIntent::None)
                .expect("guardrail off without HA intent");
            assert_eq!(r.effective, CommitPolicy::Local);
            assert_eq!(r.guardrail, GuardrailDisposition::NotApplicable);
        }
    }

    // AC: failover watermark implications follow the resolved policy.
    #[test]
    fn failover_watermark_implications_track_resolved_policy() {
        // Durable resolved policy → promotion gated on watermark coverage.
        let durable = resolve_commit_policy(
            CommitPolicy::AckN(2),
            None,
            CollectionDataModel::Queue,
            HaIntent::Declared,
        )
        .unwrap();
        assert!(durable.requires_durable_watermark());
        assert_eq!(
            durable.failover_eligibility(),
            FailoverEligibility::RequiresWatermarkCoverage
        );

        // Local resolved policy (ephemeral) → explicit data-loss window.
        let local = resolve_commit_policy(
            CommitPolicy::Local,
            None,
            CollectionDataModel::Cache,
            HaIntent::Declared,
        )
        .unwrap();
        assert!(!local.requires_durable_watermark());
        assert_eq!(
            local.failover_eligibility(),
            FailoverEligibility::LocalAckDataLossWindow
        );
    }

    #[test]
    fn resolution_is_deterministic() {
        let inputs = (
            CommitPolicy::AckN(1),
            Some(CommitPolicy::Quorum),
            CollectionDataModel::Vault,
            HaIntent::Declared,
        );
        let a = resolve_commit_policy(inputs.0, inputs.1, inputs.2, inputs.3);
        let b = resolve_commit_policy(inputs.0, inputs.1, inputs.2, inputs.3);
        assert_eq!(a, b);
    }

    #[test]
    fn ha_intent_parse() {
        assert_eq!(HaIntent::parse("true"), HaIntent::Declared);
        assert_eq!(HaIntent::parse("1"), HaIntent::Declared);
        assert_eq!(HaIntent::parse("YES"), HaIntent::Declared);
        assert_eq!(HaIntent::parse("declared"), HaIntent::Declared);
        assert_eq!(HaIntent::parse("false"), HaIntent::None);
        assert_eq!(HaIntent::parse(""), HaIntent::None);
        assert_eq!(HaIntent::parse("nonsense"), HaIntent::None);
        assert_eq!(HaIntent::default(), HaIntent::None);
    }

    #[test]
    fn source_and_disposition_labels() {
        assert_eq!(ResolutionSource::ClusterDefault.label(), "cluster_default");
        assert_eq!(
            ResolutionSource::CollectionOverride.label(),
            "collection_override"
        );
    }
}