use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;
use crate::broker::SealedCredential;
use crate::effects::{derive_effect_id, EffectId, ShadowRefusal};
use crate::error::Result;
use crate::learn::{canary_admits, CanaryBinding, CandidateId, EnvironmentTag, SurfaceKey};
use crate::memory::ProvenanceAuthor;
use crate::record::{sha256_hex, DecisionRole};
use crate::registry::PointerBinding;
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct RevisionId(String);
impl RevisionId {
pub fn as_str(&self) -> &str {
&self.0
}
}
impl std::fmt::Display for RevisionId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl From<String> for RevisionId {
fn from(digest: String) -> Self {
Self(digest)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RegistryPin {
pub surface: SurfaceKey,
pub candidate_id: CandidateId,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RevisionContent {
pub graph: String,
pub graph_hash: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub assistant: Option<String>,
pub source_environment: EnvironmentTag,
pub pins: Vec<RegistryPin>,
}
pub fn derive_revision_id(content: &RevisionContent) -> Result<RevisionId> {
Ok(RevisionId(sha256_hex(&serde_json::to_vec(content)?)))
}
pub fn pin_set_digest(pins: &[RegistryPin]) -> String {
let bytes = serde_json::to_vec(pins).expect("a pin list always serializes");
sha256_hex(&bytes)
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DeploymentRevision {
pub revision_id: RevisionId,
pub content: RevisionContent,
pub author: ProvenanceAuthor,
pub created_at: DateTime<Utc>,
}
impl DeploymentRevision {
pub fn new(
mut content: RevisionContent,
author: ProvenanceAuthor,
created_at: DateTime<Utc>,
) -> std::result::Result<Self, DeployError> {
if content.graph.is_empty() {
return Err(DeployError::InvalidRevision {
reason: "empty graph identity — a revision exists to name what serves",
});
}
content.pins.sort_by(|a, b| a.surface.cmp(&b.surface));
for pair in content.pins.windows(2) {
if pair[0].surface == pair[1].surface {
return Err(DeployError::DuplicatePin {
surface: pair[0].surface.clone(),
});
}
}
let revision_id = derive_revision_id(&content)
.map_err(|e| DeployError::UnaddressableContent(e.to_string()))?;
Ok(Self {
revision_id,
content,
author,
created_at,
})
}
pub fn verify_address(&self) -> std::result::Result<(), DeployError> {
let derived = derive_revision_id(&self.content)
.map_err(|e| DeployError::UnaddressableContent(e.to_string()))?;
if derived != self.revision_id {
return Err(DeployError::AddressMismatch {
declared: self.revision_id.clone(),
derived,
});
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GateDeclaration {
pub policy: String,
pub dataset_version: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Environment {
pub name: EnvironmentTag,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub gate: Option<GateDeclaration>,
#[serde(default)]
pub approval_required: bool,
pub created_by: ProvenanceAuthor,
pub created_at: DateTime<Utc>,
}
pub fn deployment_surface(environment: &EnvironmentTag) -> SurfaceKey {
SurfaceKey::new(format!("deployment:{environment}"))
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CanaryDeployment {
pub revision_id: RevisionId,
pub fraction: f64,
}
impl CanaryDeployment {
pub fn new(revision_id: RevisionId, fraction: f64) -> std::result::Result<Self, DeployError> {
if !(fraction > 0.0 && fraction <= 1.0) {
return Err(DeployError::InvalidFraction { fraction });
}
Ok(Self {
revision_id,
fraction,
})
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DeploymentPointer {
pub surface: SurfaceKey,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub active: Option<RevisionId>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub canary: Option<CanaryDeployment>,
}
impl DeploymentPointer {
pub fn new(surface: SurfaceKey) -> Self {
Self {
surface,
active: None,
canary: None,
}
}
pub fn promoted(&self, promotion: &RevisionPromotion) -> DeploymentPointer {
let mut next = self.clone();
next.active = Some(promotion.revision_id.clone());
next.canary = None;
next
}
pub fn rolled_back(&self, rollback: &RevisionRollback) -> DeploymentPointer {
let mut next = self.clone();
if self.active.as_ref() == Some(&rollback.from) {
next.active = rollback.to.clone();
}
if self
.canary
.as_ref()
.is_some_and(|canary| canary.revision_id == rollback.from)
{
next.canary = None;
}
next
}
}
pub fn deployment_admission(
pointer: &DeploymentPointer,
run_id: &str,
) -> Option<(RevisionId, PointerBinding)> {
if let Some(canary) = &pointer.canary {
let binding = CanaryBinding {
candidate_id: CandidateId::from(canary.revision_id.as_str().to_owned()),
fraction: canary.fraction,
};
if canary_admits(&binding, &pointer.surface, run_id) {
return Some((canary.revision_id.clone(), PointerBinding::Canary));
}
}
pointer
.active
.clone()
.map(|revision_id| (revision_id, PointerBinding::Active))
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RevisionRegistration {
pub tenant: String,
pub revision: DeploymentRevision,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EnvironmentDeclaration {
pub tenant: String,
pub environment: Environment,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RevisionPromotion {
pub tenant: String,
pub environment: EnvironmentTag,
pub revision_id: RevisionId,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub previous: Option<RevisionId>,
pub author: ProvenanceAuthor,
pub promoted_at: DateTime<Utc>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RevisionRollback {
pub tenant: String,
pub environment: EnvironmentTag,
pub from: RevisionId,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub to: Option<RevisionId>,
pub cause: String,
pub author: ProvenanceAuthor,
pub rolled_back_at: DateTime<Utc>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DeploymentResolved {
pub environment: EnvironmentTag,
pub revision_id: RevisionId,
pub pointer: PointerBinding,
pub pin_set_digest: String,
}
pub const MAX_SECRET_NAME_LEN: usize = 128;
pub fn scoped_secret_name(name: &str, environment: &EnvironmentTag) -> String {
format!("{name}@{environment}")
}
pub fn validate_secret_name(name: &str) -> std::result::Result<(), DeployError> {
let refuse = |reason: &'static str| DeployError::InvalidSecretName {
name: name.to_owned(),
reason,
};
if name.is_empty() {
return Err(refuse("empty — a secret exists to be named"));
}
if name.len() > MAX_SECRET_NAME_LEN {
return Err(refuse("over 128 bytes"));
}
if name != name.trim() {
return Err(refuse(
"leading or trailing whitespace — visually identical names would be distinct \
secrets, which is a misreview waiting to happen",
));
}
if name.chars().any(|c| c.is_control() || c == '@' || c == '/') {
return Err(refuse(
"carries a control character, `@`, or `/` — the scope separator and the tenant \
separator are structural, and control characters have no business in a key",
));
}
Ok(())
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EnvSecretRecord {
pub name: String,
pub environment: EnvironmentTag,
pub set_by: ProvenanceAuthor,
pub created_at: DateTime<Utc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rotated_at: Option<DateTime<Utc>>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StoredEnvSecret {
pub record: EnvSecretRecord,
pub envelope: SealedCredential,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EnvSecretAct {
pub tenant: String,
pub record: EnvSecretRecord,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EnvSecretRevocation {
pub tenant: String,
pub name: String,
pub environment: EnvironmentTag,
pub revoked_by: ProvenanceAuthor,
pub revoked_at: DateTime<Utc>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EnvSecretDenial {
pub tenant: String,
pub name: String,
pub requested_environment: EnvironmentTag,
pub held_environment: EnvironmentTag,
pub denied_at: DateTime<Utc>,
}
#[derive(Debug, Clone, PartialEq, Error)]
pub enum DeployError {
#[error("invalid revision: {reason}")]
InvalidRevision {
reason: &'static str,
},
#[error(
"pin set names surface `{surface}` twice — a revision pins one candidate per surface; \
a second naming is a configuration error, not a second pin"
)]
DuplicatePin {
surface: SurfaceKey,
},
#[error("revision content could not be addressed: {0}")]
UnaddressableContent(String),
#[error(
"revision declares id `{declared}` but its content addresses to `{derived}` — \
tampered evidence; refused, never served"
)]
AddressMismatch {
declared: RevisionId,
derived: RevisionId,
},
#[error(
"canary fraction {fraction} is outside (0, 1] — zero binds nothing (a cleared slot \
says that), and above one is not a fraction"
)]
InvalidFraction {
fraction: f64,
},
#[error("invalid secret name {name:?}: {reason}")]
InvalidSecretName {
name: String,
reason: &'static str,
},
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GateCheckRecord {
pub metric: String,
pub passed: bool,
pub observed: Value,
pub required: Value,
pub detail: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GateVerdict {
Allow,
Block,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GateEvaluation {
pub policy: String,
pub dataset_version: String,
pub outcome: GateVerdict,
pub checks: Vec<GateCheckRecord>,
}
impl GateEvaluation {
pub fn allowed(&self) -> bool {
self.outcome == GateVerdict::Allow && self.checks.iter().all(|check| check.passed)
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GateDecisionRecord {
pub tenant: String,
pub environment: EnvironmentTag,
pub revision_id: RevisionId,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub baseline_revision_id: Option<RevisionId>,
pub policy: String,
pub dataset_version: String,
pub outcome: GateVerdict,
pub checks: Vec<GateCheckRecord>,
pub decided_at: DateTime<Utc>,
}
#[async_trait]
pub trait RevisionGateEvaluator: Send + Sync + std::fmt::Debug {
async fn evaluate(
&self,
revision: &DeploymentRevision,
baseline: Option<&DeploymentRevision>,
gate: &GateDeclaration,
) -> Result<GateEvaluation>;
}
pub const REVISION_PROMOTION_EFFECT_KIND: &str = "revision_promotion";
pub fn revision_promotion_effect_id(
environment: &EnvironmentTag,
revision: &DeploymentRevision,
) -> EffectId {
derive_effect_id(
deployment_surface(environment).as_str(),
REVISION_PROMOTION_EFFECT_KIND,
revision.revision_id.as_str(),
Some(&format!("promotion:{}", revision.revision_id.as_str())),
)
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CanaryDeclaration {
pub tenant: String,
pub environment: EnvironmentTag,
pub revision_id: RevisionId,
pub fraction: f64,
pub author: ProvenanceAuthor,
pub declared_at: DateTime<Utc>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CanaryClearance {
pub tenant: String,
pub environment: EnvironmentTag,
pub cleared_revision_id: RevisionId,
pub author: ProvenanceAuthor,
pub cleared_at: DateTime<Utc>,
}
impl DeploymentPointer {
pub fn canaried(&self, declaration: &CanaryDeclaration) -> DeploymentPointer {
let mut next = self.clone();
next.canary = Some(CanaryDeployment {
revision_id: declaration.revision_id.clone(),
fraction: declaration.fraction,
});
next
}
pub fn cleared_canary(&self) -> DeploymentPointer {
let mut next = self.clone();
next.canary = None;
next
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ShadowRunStarted {
pub tenant: String,
pub shadow_run_id: String,
pub source_run_id: String,
pub revision_id: RevisionId,
pub role: DecisionRole,
pub author: ProvenanceAuthor,
pub started_at: DateTime<Utc>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ShadowRunOutcome {
Completed,
Failed {
error: String,
},
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ShadowVerdict {
pub tenant: String,
pub shadow_run_id: String,
pub source_run_id: String,
pub revision_id: RevisionId,
pub refusals: Vec<ShadowRefusal>,
pub matched: usize,
pub unserved: usize,
pub unrequested: Vec<String>,
pub outcome: ShadowRunOutcome,
pub completed_at: DateTime<Utc>,
}
#[cfg(test)]
mod tests {
use super::*;
use serde::Serialize;
use std::path::PathBuf;
fn golden_path(name: &str) -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("golden")
.join(name)
}
fn assert_golden(name: &str, value: &impl Serialize) {
let rendered = format!("{}\n", serde_json::to_string_pretty(value).unwrap());
let path = golden_path(name);
if std::env::var_os("UPDATE_GOLDEN").is_some() {
std::fs::write(&path, &rendered).unwrap();
return;
}
let expected = std::fs::read_to_string(&path)
.unwrap_or_else(|e| panic!("missing golden file `{}`: {e}", path.display()));
assert_eq!(
rendered,
expected,
"contract drift in `{}` — if intentional, re-run with UPDATE_GOLDEN=1 \
and review the diff",
path.display()
);
}
fn ts(millis: i64) -> DateTime<Utc> {
DateTime::<Utc>::from_timestamp_millis(millis).unwrap()
}
fn author() -> ProvenanceAuthor {
ProvenanceAuthor::Human {
human_id: "amjad".into(),
}
}
fn tag(name: &str) -> EnvironmentTag {
EnvironmentTag::new(name).unwrap()
}
fn candidate_id(seed: char) -> CandidateId {
CandidateId::from(seed.to_string().repeat(64))
}
fn revision(seed: char) -> DeploymentRevision {
DeploymentRevision::new(
RevisionContent {
graph: "pipeline".into(),
graph_hash: "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"
.into(),
assistant: Some("support-agent".into()),
source_environment: tag("staging"),
pins: vec![
RegistryPin {
surface: SurfaceKey::new("model_settings:primary"),
candidate_id: candidate_id(seed),
},
RegistryPin {
surface: SurfaceKey::new("prompt:system"),
candidate_id: candidate_id('p'),
},
],
},
author(),
ts(1_760_000_000_000),
)
.unwrap()
}
#[test]
fn content_addressing_converges_and_ignores_attribution() {
let first = revision('a');
let mut shuffled = first.content.clone();
shuffled.pins.reverse();
let second = DeploymentRevision::new(
shuffled,
ProvenanceAuthor::Human {
human_id: "someone-else".into(),
},
ts(1_760_000_999_000),
)
.unwrap();
assert_eq!(first.revision_id, second.revision_id);
assert_ne!(first.author, second.author, "attribution is not identity");
first.verify_address().unwrap();
}
#[test]
fn a_changed_declaration_is_a_new_id() {
let changed = DeploymentRevision::new(
RevisionContent {
graph_hash: "0".repeat(64),
..revision('a').content
},
author(),
ts(1_760_000_000_000),
)
.unwrap();
assert_ne!(changed.revision_id, revision('a').revision_id);
}
#[test]
fn duplicate_pins_and_empty_graphs_are_refused() {
let dup = DeploymentRevision::new(
RevisionContent {
pins: vec![
RegistryPin {
surface: SurfaceKey::new("prompt:system"),
candidate_id: candidate_id('a'),
},
RegistryPin {
surface: SurfaceKey::new("prompt:system"),
candidate_id: candidate_id('b'),
},
],
..revision('a').content
},
author(),
ts(1_760_000_000_000),
);
assert!(
matches!(dup, Err(DeployError::DuplicatePin { .. })),
"one surface pins one candidate"
);
let empty = DeploymentRevision::new(
RevisionContent {
graph: String::new(),
..revision('a').content
},
author(),
ts(1_760_000_000_000),
);
assert!(matches!(empty, Err(DeployError::InvalidRevision { .. })));
}
#[test]
fn verify_address_refuses_tampering() {
let mut tampered = revision('a');
tampered.content.graph_hash = "f".repeat(64);
assert!(matches!(
tampered.verify_address(),
Err(DeployError::AddressMismatch { .. })
));
}
#[test]
fn promotion_moves_active_and_clears_the_canary() {
let surface = deployment_surface(&tag("prod"));
let mut pointer = DeploymentPointer::new(surface.clone());
pointer.active = Some(RevisionId::from("a".repeat(64)));
pointer.canary =
Some(CanaryDeployment::new(RevisionId::from("b".repeat(64)), 0.1).unwrap());
let promotion = RevisionPromotion {
tenant: "default".into(),
environment: tag("prod"),
revision_id: RevisionId::from("b".repeat(64)),
previous: pointer.active.clone(),
author: author(),
promoted_at: ts(1_760_000_100_000),
};
let moved = pointer.promoted(&promotion);
assert_eq!(moved.active, Some(RevisionId::from("b".repeat(64))));
assert_eq!(
moved.canary, None,
"a full promotion supersedes its experiment"
);
}
#[test]
fn rollback_repoints_byte_exact() {
let surface = deployment_surface(&tag("prod"));
let mut pointer = DeploymentPointer::new(surface);
pointer.active = Some(RevisionId::from("b".repeat(64)));
let rollback = RevisionRollback {
tenant: "default".into(),
environment: tag("prod"),
from: RevisionId::from("b".repeat(64)),
to: Some(RevisionId::from("a".repeat(64))),
cause: "error rate".into(),
author: author(),
rolled_back_at: ts(1_760_000_200_000),
};
let moved = pointer.rolled_back(&rollback);
assert_eq!(
moved.active,
Some(RevisionId::from("a".repeat(64))),
"the restored revision is the one that served, not a reconstruction"
);
let stray = pointer.rolled_back(&RevisionRollback {
from: RevisionId::from("c".repeat(64)),
..rollback
});
assert_eq!(stray, pointer);
}
#[test]
fn canary_fraction_bounds_are_enforced() {
assert!(CanaryDeployment::new(RevisionId::from("a".repeat(64)), 0.0).is_err());
assert!(CanaryDeployment::new(RevisionId::from("a".repeat(64)), 1.0).is_ok());
assert!(CanaryDeployment::new(RevisionId::from("a".repeat(64)), 1.1).is_err());
}
#[test]
fn the_canary_draw_is_seeded_and_reproducible() {
let revision = RevisionId::from("a".repeat(64));
let mut pointer = DeploymentPointer::new(deployment_surface(&tag("staging")));
pointer.active = Some(RevisionId::from("f".repeat(64)));
pointer.canary = Some(CanaryDeployment::new(revision.clone(), 0.5).unwrap());
let first = deployment_admission(&pointer, "run-1");
let second = deployment_admission(&pointer, "run-1");
assert_eq!(
first, second,
"the draw is a pure function of journaled facts"
);
let prod_pointer =
DeploymentPointer::new(deployment_surface(&tag("prod"))).promoted(&RevisionPromotion {
tenant: "default".into(),
environment: tag("prod"),
revision_id: RevisionId::from("f".repeat(64)),
previous: None,
author: author(),
promoted_at: ts(1_760_000_000_000),
});
let mut prod_with_canary = prod_pointer;
prod_with_canary.canary = Some(CanaryDeployment::new(revision, 0.5).unwrap());
assert!(deployment_admission(&prod_with_canary, "run-1").is_some());
let empty = DeploymentPointer::new(deployment_surface(&tag("dev")));
assert_eq!(deployment_admission(&empty, "run-1"), None);
}
#[test]
fn secret_names_follow_the_registry_naming_rule() {
assert!(validate_secret_name("database-url").is_ok());
assert!(validate_secret_name("").is_err());
assert!(
validate_secret_name("db@prod").is_err(),
"the scope separator is structural"
);
assert!(
validate_secret_name("a/b").is_err(),
"the tenant separator is structural"
);
assert_eq!(
scoped_secret_name("database-url", &tag("staging")),
"database-url@staging"
);
}
#[test]
fn golden_deployment_event_kinds_shape() {
use crate::record::RunEventKind;
assert_golden(
"deployment_event_kinds.json",
&vec![
RunEventKind::DeploymentResolved,
RunEventKind::RevisionRegistered,
RunEventKind::RevisionPromoted,
RunEventKind::RevisionRolledBack,
RunEventKind::EnvironmentDeclared,
RunEventKind::EnvSecretSet,
RunEventKind::EnvSecretRevoked,
RunEventKind::EnvSecretDenied,
],
);
}
#[test]
fn golden_deployment_revision_shape() {
assert_golden("deployment_revision.json", &revision('a'));
}
#[test]
fn golden_environment_shape() {
let environment = Environment {
name: tag("prod"),
gate: Some(GateDeclaration {
policy: "r0.12-default".into(),
dataset_version: "support-v3".into(),
}),
approval_required: true,
created_by: author(),
created_at: ts(1_760_000_000_000),
};
assert_golden("environment.json", &environment);
}
#[test]
fn golden_deployment_pointer_shape() {
let mut pointer = DeploymentPointer::new(deployment_surface(&tag("staging")));
pointer.active = Some(RevisionId::from("a".repeat(64)));
pointer.canary =
Some(CanaryDeployment::new(RevisionId::from("b".repeat(64)), 0.1).unwrap());
assert_golden("deployment_pointer.json", &pointer);
}
#[test]
fn golden_deployment_resolved_shape() {
let resolved = DeploymentResolved {
environment: tag("staging"),
revision_id: revision('a').revision_id,
pointer: PointerBinding::Canary,
pin_set_digest: pin_set_digest(&revision('a').content.pins),
};
assert_golden("deployment_resolved.json", &resolved);
}
#[test]
fn golden_revision_registration_shape() {
assert_golden(
"revision_registration.json",
&RevisionRegistration {
tenant: "default".into(),
revision: revision('a'),
},
);
}
#[test]
fn golden_environment_declaration_shape() {
assert_golden(
"environment_declaration.json",
&EnvironmentDeclaration {
tenant: "default".into(),
environment: Environment {
name: tag("dev"),
gate: None,
approval_required: false,
created_by: author(),
created_at: ts(1_760_000_000_000),
},
},
);
}
#[test]
fn golden_revision_promotion_shape() {
assert_golden(
"revision_promotion.json",
&RevisionPromotion {
tenant: "default".into(),
environment: tag("prod"),
revision_id: revision('a').revision_id,
previous: Some(RevisionId::from("f".repeat(64))),
author: author(),
promoted_at: ts(1_760_000_100_000),
},
);
}
#[test]
fn golden_revision_rollback_shape() {
assert_golden(
"revision_rollback.json",
&RevisionRollback {
tenant: "default".into(),
environment: tag("prod"),
from: revision('a').revision_id,
to: Some(RevisionId::from("f".repeat(64))),
cause: "canary regression".into(),
author: author(),
rolled_back_at: ts(1_760_000_200_000),
},
);
}
#[test]
fn golden_env_secret_record_shape() {
assert_golden(
"env_secret_record.json",
&EnvSecretRecord {
name: "database-url".into(),
environment: tag("staging"),
set_by: author(),
created_at: ts(1_760_000_000_000),
rotated_at: Some(ts(1_760_000_500_000)),
},
);
}
#[test]
fn golden_stored_env_secret_shape() {
assert_golden(
"stored_env_secret.json",
&StoredEnvSecret {
record: EnvSecretRecord {
name: "database-url".into(),
environment: tag("prod"),
set_by: author(),
created_at: ts(1_760_000_000_000),
rotated_at: None,
},
envelope: SealedCredential {
format_version: 1,
key_id: "esk-0123456789abcdef".into(),
wrapped_data_key: "aa".repeat(48),
wrap_nonce: "bb".repeat(24),
nonce: "cc".repeat(24),
ciphertext: "dd".repeat(80),
sealed_at: ts(1_760_000_000_000),
},
},
);
}
#[test]
fn golden_env_secret_denial_shape() {
assert_golden(
"env_secret_denial.json",
&EnvSecretDenial {
tenant: "default".into(),
name: "database-url".into(),
requested_environment: tag("prod"),
held_environment: tag("staging"),
denied_at: ts(1_760_000_300_000),
},
);
}
fn gate_evaluation(outcome: GateVerdict, checks: Vec<GateCheckRecord>) -> GateEvaluation {
GateEvaluation {
policy: "r0.12-default".into(),
dataset_version: "support-v3".into(),
outcome,
checks,
}
}
fn passing_check() -> GateCheckRecord {
GateCheckRecord {
metric: "\"pass_rate\"".into(),
passed: true,
observed: serde_json::json!(0.91),
required: serde_json::json!(0.85),
detail: "pass rate clears the floor".into(),
}
}
#[test]
fn the_gate_allows_only_when_verdict_and_every_check_agree() {
assert!(gate_evaluation(GateVerdict::Allow, vec![passing_check()]).allowed());
assert!(!gate_evaluation(GateVerdict::Block, vec![passing_check()]).allowed());
let mut failing = passing_check();
failing.passed = false;
assert!(!gate_evaluation(GateVerdict::Allow, vec![passing_check(), failing]).allowed());
}
#[test]
fn canary_moves_keep_the_active_revision_serving() {
let pointer = DeploymentPointer {
canary: None,
..DeploymentPointer::new(deployment_surface(&tag("staging")))
};
let declaration = CanaryDeclaration {
tenant: "default".into(),
environment: tag("staging"),
revision_id: revision('b').revision_id.clone(),
fraction: 0.1,
author: author(),
declared_at: ts(1_760_000_100_000),
};
let canaried = pointer.canaried(&declaration);
assert_eq!(
canaried.canary,
Some(CanaryDeployment {
revision_id: revision('b').revision_id.clone(),
fraction: 0.1,
})
);
assert_eq!(
canaried.active, pointer.active,
"a canary moves nothing serving"
);
let cleared = canaried.cleared_canary();
assert_eq!(cleared, pointer, "clearing restores the pre-canary pointer");
}
#[test]
fn the_revision_promotion_effect_id_is_scoped_to_the_revision() {
let rev = revision('a');
let staging = tag("staging");
let id = revision_promotion_effect_id(&staging, &rev);
assert_eq!(id, revision_promotion_effect_id(&staging, &rev));
assert_ne!(
id,
revision_promotion_effect_id(&staging, &revision('b')),
"another revision is another approval"
);
assert_ne!(
id,
revision_promotion_effect_id(&tag("prod"), &rev),
"another environment is another approval"
);
}
fn gate_decision_record() -> GateDecisionRecord {
GateDecisionRecord {
tenant: "default".into(),
environment: tag("staging"),
revision_id: revision('b').revision_id.clone(),
baseline_revision_id: Some(revision('a').revision_id.clone()),
policy: "r0.12-default".into(),
dataset_version: "support-v3".into(),
outcome: GateVerdict::Allow,
checks: vec![passing_check()],
decided_at: ts(1_760_000_200_000),
}
}
fn shadow_refusal() -> ShadowRefusal {
ShadowRefusal {
kind: "charge".into(),
effect: crate::record::Effect::NonIdempotent,
effect_id: derive_effect_id(
"shadow-run-1",
"charge",
&sha256_hex(b"{\"tool\":\"charge\"}"),
Some("shadow-run-1:7"),
),
input_hash: sha256_hex(b"{\"tool\":\"charge\"}"),
served: true,
}
}
#[test]
fn golden_gate_event_kinds_shape() {
use crate::record::RunEventKind;
assert_golden(
"deployment_gate_event_kinds.json",
&vec![
RunEventKind::GateDecisionRecorded,
RunEventKind::CanaryDeclared,
RunEventKind::CanaryCleared,
RunEventKind::ShadowRunStarted,
RunEventKind::ShadowEffectRefused,
RunEventKind::ShadowVerdict,
],
);
}
#[test]
fn golden_gate_decision_record_shape() {
assert_golden("gate_decision_record.json", &gate_decision_record());
}
#[test]
fn golden_canary_declaration_shape() {
assert_golden(
"canary_declaration.json",
&CanaryDeclaration {
tenant: "default".into(),
environment: tag("staging"),
revision_id: revision('b').revision_id.clone(),
fraction: 0.1,
author: author(),
declared_at: ts(1_760_000_100_000),
},
);
}
#[test]
fn golden_canary_clearance_shape() {
assert_golden(
"canary_clearance.json",
&CanaryClearance {
tenant: "default".into(),
environment: tag("staging"),
cleared_revision_id: revision('b').revision_id.clone(),
author: author(),
cleared_at: ts(1_760_000_400_000),
},
);
}
#[test]
fn golden_shadow_run_started_shape() {
assert_golden(
"shadow_run_started.json",
&ShadowRunStarted {
tenant: "default".into(),
shadow_run_id: "shadow-run-1-abcdef123456-7f3a".into(),
source_run_id: "run-1".into(),
revision_id: revision('b').revision_id.clone(),
role: DecisionRole::Shadow,
author: author(),
started_at: ts(1_760_000_500_000),
},
);
}
#[test]
fn golden_shadow_effect_refusal_shape() {
assert_golden("shadow_effect_refusal.json", &shadow_refusal());
}
#[test]
fn golden_shadow_verdict_shape() {
assert_golden(
"shadow_verdict.json",
&ShadowVerdict {
tenant: "default".into(),
shadow_run_id: "shadow-run-1-abcdef123456-7f3a".into(),
source_run_id: "run-1".into(),
revision_id: revision('b').revision_id.clone(),
refusals: vec![shadow_refusal()],
matched: 1,
unserved: 0,
unrequested: vec!["lookup".into()],
outcome: ShadowRunOutcome::Completed,
completed_at: ts(1_760_000_600_000),
},
);
}
}