story 2-12-preview-partial-mode: implemented and reviewed via bmad-loop
This commit is contained in:
1 parent
d1ba0bd0e4
commit
ab35d67177
56 files changed
+5801
-376
No files matched your search
@@ -1,5 +1,8 @@
|
||||
mod catalog;
|
||||
mod legacy_auth;
|
||||
mod plan_apply;
|
||||
mod semantic;
|
||||
use semantic::plan_digest_from_payload;
|
||||
|
||||
use super::*;
|
||||
use crate::{
|
||||
@@ -14,7 +17,8 @@ const APPLICATION_RESULT_KEY: &str = "_crank_application_result";
|
||||
const IMPORT_JOB_CLEANUP_BATCH: u32 = 128;
|
||||
const MAX_IMPORT_JOB_DOCUMENTS: usize = 32;
|
||||
const MAX_IMPORT_PLAN_ID_BYTES: usize = 128;
|
||||
const MAX_IMPORT_PLAN_PAYLOAD_BYTES: usize = 4 * 1024 * 1024;
|
||||
const MAX_IMPORT_PLAN_PAYLOAD_BYTES: usize = 16 * 1024 * 1024;
|
||||
const MAX_LEGACY_IMPORT_PLAN_PAYLOAD_BYTES: usize = 4 * 1024 * 1024;
|
||||
const DANGLING_OPENAPI_SOURCE_GRACE: time::Duration = time::Duration::minutes(5);
|
||||
|
||||
impl PostgresRegistry {
|
||||
@@ -119,6 +123,25 @@ impl PostgresRegistry {
|
||||
});
|
||||
}
|
||||
let digest = plan_digest_from_payload(request.payload)?;
|
||||
let v2 = request
|
||||
.payload
|
||||
.get("schema_version")
|
||||
.and_then(Value::as_str)
|
||||
== Some("import-plan-v2");
|
||||
if v2 {
|
||||
semantic::validate_v2_metadata(request.payload)?;
|
||||
plan_apply::validate_v2_creation(&request, &digest)?;
|
||||
if request
|
||||
.payload
|
||||
.get("plan_reference")
|
||||
.and_then(Value::as_str)
|
||||
!= Some(request.id.as_str())
|
||||
|| request.payload.get("job_id").and_then(Value::as_str)
|
||||
!= Some(request.job_id.as_str())
|
||||
{
|
||||
return Err(RegistryError::InvalidImportPlan { field: "identity" });
|
||||
}
|
||||
}
|
||||
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
|
||||
@@ -195,12 +218,31 @@ impl PostgresRegistry {
|
||||
job_id: request.job_id.as_str().to_owned(),
|
||||
});
|
||||
}
|
||||
if v2 {
|
||||
semantic::validate_v2_sources(request.payload, &preview_payload)?;
|
||||
}
|
||||
|
||||
sqlx::query("select id from workspaces where id = $1 for update")
|
||||
.bind(request.workspace_id.as_str())
|
||||
.fetch_one(&mut *transaction)
|
||||
.await?;
|
||||
|
||||
if v2
|
||||
&& request
|
||||
.payload
|
||||
.get("catalog_revision")
|
||||
.and_then(Value::as_str)
|
||||
!= Some(
|
||||
catalog::catalog_revision(&mut *transaction, request.workspace_id, true)
|
||||
.await?
|
||||
.as_str(),
|
||||
)
|
||||
{
|
||||
return Err(RegistryError::ImportPlanFingerprintStale {
|
||||
plan_id: request.id.as_str().to_owned(),
|
||||
});
|
||||
}
|
||||
|
||||
// Authoritative re-check: any concurrent insert of this (workspace, id)
|
||||
// must also hold the workspace lock, so a winner cannot appear between
|
||||
// the fast-path check and the insert.
|
||||
@@ -878,22 +920,6 @@ fn map_import_plan(row: &PgRow) -> Result<ImportPlan, RegistryError> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Derives the canonical plan digest: the lowercase SHA-256 of the payload
|
||||
/// serialized to its deterministic byte form. `serde_json::Value` object keys
|
||||
/// are ordered (BTreeMap-backed map), so `to_vec` is stable across calls and
|
||||
/// platforms — the digest is therefore reproducible for byte-identical
|
||||
/// material without requiring a client-supplied digest.
|
||||
fn plan_digest_from_payload(payload: &Value) -> Result<String, RegistryError> {
|
||||
if !payload.is_object() {
|
||||
return Err(RegistryError::InvalidImportPlan { field: "payload" });
|
||||
}
|
||||
let canonical = serde_json::to_vec(payload)?;
|
||||
if canonical.len() > MAX_IMPORT_PLAN_PAYLOAD_BYTES {
|
||||
return Err(RegistryError::InvalidImportPlan { field: "payload" });
|
||||
}
|
||||
Ok(format!("{:x}", Sha256::digest(canonical)))
|
||||
}
|
||||
|
||||
fn validate_plan_id(id: &ImportPlanId) -> Result<(), RegistryError> {
|
||||
if !(1..=MAX_IMPORT_PLAN_ID_BYTES).contains(&id.as_str().len()) {
|
||||
return Err(RegistryError::InvalidImportPlan { field: "id" });
|
||||
@@ -936,6 +962,7 @@ fn plan_replay_outcome(
|
||||
) -> Result<ImportPlan, RegistryError> {
|
||||
let stored = map_import_plan(&existing)?;
|
||||
let replay = stored.digest == digest
|
||||
&& stored.payload == *request.payload
|
||||
&& stored.job_id == *request.job_id
|
||||
&& stored.created_at == created_at
|
||||
&& stored.expires_at == expires_at;
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
use super::*;
|
||||
|
||||
// A bounded metadata read, independent of the size of stored schemas/Drafts.
|
||||
const MAX_IMPORT_CATALOG_ENTRIES: i64 = 10_000;
|
||||
|
||||
impl PostgresRegistry {
|
||||
pub async fn list_import_catalog_names(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
) -> Result<Vec<String>, RegistryError> {
|
||||
let names = sqlx::query_scalar::<_, String>(
|
||||
"select name from operations where workspace_id = $1 order by name limit $2",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(MAX_IMPORT_CATALOG_ENTRIES + 1)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
if names.len() > MAX_IMPORT_CATALOG_ENTRIES as usize {
|
||||
return Err(RegistryError::InvalidImportPlan {
|
||||
field: "catalog_revision_limit",
|
||||
});
|
||||
}
|
||||
Ok(names)
|
||||
}
|
||||
/// Deterministic workspace catalog identity for naming and version targets.
|
||||
/// Referenced authentication state is separately bound in plan snapshots.
|
||||
pub async fn import_catalog_revision(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
) -> Result<String, RegistryError> {
|
||||
catalog_revision(&self.pool, workspace_id, false).await
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn catalog_revision<'c, E>(
|
||||
executor: E,
|
||||
workspace_id: &WorkspaceId,
|
||||
lock: bool,
|
||||
) -> Result<String, RegistryError>
|
||||
where
|
||||
E: Executor<'c, Database = Postgres>,
|
||||
{
|
||||
let query = if lock {
|
||||
"select jsonb_build_array(id, name, protocol, status, current_draft_version, latest_published_version) as metadata
|
||||
from operations where workspace_id = $1 order by id limit $2 for share"
|
||||
} else {
|
||||
"select jsonb_build_array(id, name, protocol, status, current_draft_version, latest_published_version) as metadata
|
||||
from operations where workspace_id = $1 order by id limit $2"
|
||||
};
|
||||
let rows = sqlx::query(query)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(MAX_IMPORT_CATALOG_ENTRIES + 1)
|
||||
.fetch_all(executor)
|
||||
.await?;
|
||||
if rows.len() > MAX_IMPORT_CATALOG_ENTRIES as usize {
|
||||
return Err(RegistryError::InvalidImportPlan {
|
||||
field: "catalog_revision_limit",
|
||||
});
|
||||
}
|
||||
let metadata = rows
|
||||
.iter()
|
||||
.map(|row| row.try_get::<Value, _>("metadata"))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
Ok(format!(
|
||||
"{:x}",
|
||||
Sha256::digest(serde_json::to_vec(&metadata)?)
|
||||
))
|
||||
}
|
||||
@@ -10,6 +10,7 @@ use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
mod material;
|
||||
mod mutations;
|
||||
mod revalidate;
|
||||
mod verify;
|
||||
|
||||
use material::*;
|
||||
@@ -20,7 +21,7 @@ const PLAN_PAYLOAD_SCHEMA_VERSION: &str = "import-plan-v1";
|
||||
const APPLY_REPORT_SCHEMA_VERSION: &str = "import-plan-apply-report-v1";
|
||||
/// Same upper bound as plan creation keeps the report compatible with every
|
||||
/// plan that was accepted: at most this many candidates / names / targets.
|
||||
const MAX_IMPORT_PLAN_KEYS: usize = 512;
|
||||
const MAX_IMPORT_PLAN_KEYS: usize = 2_000;
|
||||
const MAX_IMPORT_PLAN_KEY_BYTES: usize = 4_096;
|
||||
const MAX_IMPORT_PLAN_NAME_BYTES: usize = 256;
|
||||
const MAX_IMPORT_PLAN_ID_REF_BYTES: usize = 128;
|
||||
@@ -30,10 +31,38 @@ const MAX_IMPORT_PLAN_IDEMPOTENCY_KEY_BYTES: usize = 128;
|
||||
/// Bound for the serialized apply report. Must accommodate a full accepted
|
||||
/// plan: report entries carry only key/name/ids (already bounded) while the
|
||||
/// plan payload — which carries far more per candidate — is capped at
|
||||
/// `MAX_IMPORT_PLAN_PAYLOAD_BYTES` (4 MiB) at creation. This keeps every
|
||||
/// `MAX_IMPORT_PLAN_PAYLOAD_BYTES` (16 MiB) at creation. This keeps every
|
||||
/// accepted plan's exact outcomes inside the report without truncation.
|
||||
const MAX_IMPORT_PLAN_REPORT_BYTES: usize = MAX_IMPORT_PLAN_PAYLOAD_BYTES;
|
||||
|
||||
pub(super) fn validate_v2_creation(
|
||||
request: &CreateImportPlanRequest<'_>,
|
||||
digest: &str,
|
||||
) -> Result<(), RegistryError> {
|
||||
let fingerprint =
|
||||
request
|
||||
.payload
|
||||
.get("fingerprint")
|
||||
.ok_or(RegistryError::InvalidImportPlan {
|
||||
field: "fingerprint",
|
||||
})?;
|
||||
let validation = ApplyImportPlanRequest {
|
||||
workspace_id: request.workspace_id,
|
||||
plan_id: request.id,
|
||||
plan_digest: digest,
|
||||
idempotency_key: "creation-validation",
|
||||
verified_fingerprint: fingerprint,
|
||||
applied_at: request.created_at,
|
||||
};
|
||||
read_and_validate_plan_material(
|
||||
request.payload,
|
||||
&validation,
|
||||
digest,
|
||||
request.job_id.as_str(),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Failure of one apply transaction: a typed registry conflict, or the
|
||||
/// application-row uniqueness collision that must be reconciled after the
|
||||
/// transaction is rolled back.
|
||||
@@ -254,6 +283,20 @@ async fn apply_import_plan_transaction(
|
||||
.await
|
||||
.map_err(fail)?;
|
||||
|
||||
if plan.schema_version == "import-plan-v2"
|
||||
&& plan.catalog_revision.as_deref()
|
||||
!= Some(
|
||||
super::catalog::catalog_revision(&mut **tx, request.workspace_id, true)
|
||||
.await
|
||||
.map_err(fail)?
|
||||
.as_str(),
|
||||
)
|
||||
{
|
||||
return Err(fail(RegistryError::ImportPlanFingerprintStale {
|
||||
plan_id: plan_id.clone(),
|
||||
}));
|
||||
}
|
||||
|
||||
// Apply the selected candidates in deterministic order.
|
||||
let mut candidates: Vec<&StoredPlanCandidate> = plan.candidates.iter().collect();
|
||||
candidates.sort_by(|a, b| a.key.cmp(&b.key));
|
||||
|
||||
@@ -16,6 +16,16 @@ pub(super) struct StoredPlan {
|
||||
pub(crate) selection: StoredPlanSelection,
|
||||
pub(crate) counts: StoredPlanCounts,
|
||||
pub(crate) candidates: Vec<StoredPlanCandidate>,
|
||||
#[serde(default)]
|
||||
pub(crate) catalog_revision: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(crate) excluded_reasons: Vec<StoredExcludedReason>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(super) struct StoredExcludedReason {
|
||||
pub(crate) key: String,
|
||||
pub(crate) reason: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Deserialize)]
|
||||
@@ -172,18 +182,21 @@ pub(super) fn read_and_validate_plan_material(
|
||||
{
|
||||
return Err(corrupt());
|
||||
}
|
||||
let v2 = payload.get("schema_version").and_then(Value::as_str) == Some("import-plan-v2");
|
||||
let selected_limit = if v2 { MAX_IMPORT_PLAN_KEYS } else { 512 };
|
||||
let all_limit = if v2 { MAX_IMPORT_PLAN_KEYS } else { 1_024 };
|
||||
if payload
|
||||
.pointer("/selection/selected")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|items| items.len() > MAX_IMPORT_PLAN_KEYS)
|
||||
.is_some_and(|items| items.len() > selected_limit)
|
||||
|| payload
|
||||
.pointer("/selection/all")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|items| items.len() > MAX_IMPORT_PLAN_KEYS * 2)
|
||||
.is_some_and(|items| items.len() > all_limit)
|
||||
|| payload
|
||||
.pointer("/selection/excluded")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|items| items.len() > MAX_IMPORT_PLAN_KEYS)
|
||||
.is_some_and(|items| items.len() > selected_limit)
|
||||
{
|
||||
return Err(corrupt());
|
||||
}
|
||||
@@ -219,12 +232,17 @@ pub(super) fn read_and_validate_plan_material(
|
||||
let plan: StoredPlan = serde_json::from_value(payload.clone()).map_err(|_| corrupt())?;
|
||||
|
||||
// The typed material must agree with the request it is being applied for.
|
||||
if plan.schema_version.as_str() != PLAN_PAYLOAD_SCHEMA_VERSION
|
||||
|| plan.plan_reference.as_str() != request.plan_id.as_str()
|
||||
if !matches!(
|
||||
plan.schema_version.as_str(),
|
||||
PLAN_PAYLOAD_SCHEMA_VERSION | "import-plan-v2"
|
||||
) || plan.plan_reference.as_str() != request.plan_id.as_str()
|
||||
|| plan.job_id != stored_job_id
|
||||
{
|
||||
return Err(corrupt());
|
||||
}
|
||||
if plan.schema_version == "import-plan-v2" {
|
||||
super::super::semantic::validate_v2_metadata(payload).map_err(|_| corrupt())?;
|
||||
}
|
||||
|
||||
// Selection closure.
|
||||
if !matches!(plan.selection.mode.as_str(), "full" | "partial") {
|
||||
@@ -248,6 +266,30 @@ pub(super) fn read_and_validate_plan_material(
|
||||
let selected: BTreeSet<&String> = plan.selection.selected.iter().collect();
|
||||
let excluded: BTreeSet<&String> = plan.selection.excluded.iter().collect();
|
||||
let all: BTreeSet<&String> = plan.selection.all.iter().collect();
|
||||
if plan.schema_version == "import-plan-v2" {
|
||||
let findings = payload
|
||||
.pointer("/findings/candidates")
|
||||
.and_then(Value::as_array)
|
||||
.ok_or_else(corrupt)?;
|
||||
let keys = findings
|
||||
.iter()
|
||||
.map(|item| {
|
||||
if !item.get("findings").is_some_and(Value::is_array) {
|
||||
return Err(corrupt());
|
||||
}
|
||||
item.get("key").and_then(Value::as_str).ok_or_else(corrupt)
|
||||
})
|
||||
.collect::<Result<BTreeSet<_>, _>>()?;
|
||||
let expected = plan
|
||||
.selection
|
||||
.all
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.collect::<BTreeSet<_>>();
|
||||
if keys != expected || keys.len() != findings.len() {
|
||||
return Err(corrupt());
|
||||
}
|
||||
}
|
||||
let mut union = selected.clone();
|
||||
union.extend(excluded.iter());
|
||||
if union != all || selected.iter().any(|key| excluded.contains(key)) {
|
||||
@@ -256,6 +298,34 @@ pub(super) fn read_and_validate_plan_material(
|
||||
if plan.selection.mode == "full" && (!excluded.is_empty() || selected != all) {
|
||||
return Err(corrupt());
|
||||
}
|
||||
if plan.schema_version == "import-plan-v2" {
|
||||
let reasons = plan
|
||||
.excluded_reasons
|
||||
.iter()
|
||||
.map(|item| &item.key)
|
||||
.collect::<BTreeSet<_>>();
|
||||
if reasons != excluded
|
||||
|| reasons.len() != plan.excluded_reasons.len()
|
||||
|| plan.excluded_reasons.iter().any(|item| {
|
||||
item.reason.is_empty() || item.reason.len() > MAX_IMPORT_PLAN_REASON_BYTES
|
||||
})
|
||||
|| !plan
|
||||
.excluded_reasons
|
||||
.windows(2)
|
||||
.all(|items| items[0].key < items[1].key)
|
||||
{
|
||||
return Err(corrupt());
|
||||
}
|
||||
}
|
||||
if plan.schema_version == "import-plan-v2"
|
||||
&& plan.selection.mode == "partial"
|
||||
&& plan
|
||||
.candidates
|
||||
.iter()
|
||||
.any(|candidate| candidate.state != "actionable")
|
||||
{
|
||||
return Err(corrupt());
|
||||
}
|
||||
let candidate_keys: BTreeSet<&String> = plan
|
||||
.candidates
|
||||
.iter()
|
||||
|
||||
@@ -203,7 +203,13 @@ fn excluded_outcomes(plan: &StoredPlan) -> Vec<ImportPlanCandidateReport> {
|
||||
outcome: ImportPlanCandidateOutcome::Excluded,
|
||||
operation_id: None,
|
||||
version: None,
|
||||
reason: Some("not_selected".to_owned()),
|
||||
reason: Some(
|
||||
plan.excluded_reasons
|
||||
.iter()
|
||||
.find(|item| item.key == *key)
|
||||
.map(|item| item.reason.clone())
|
||||
.unwrap_or_else(|| "not_selected".to_owned()),
|
||||
),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
use super::*;
|
||||
|
||||
impl PostgresRegistry {
|
||||
/// Reopens immutable plan evidence without applying it or writing a report.
|
||||
/// The result is current validation evidence, never a promise about a later
|
||||
/// Apply; Apply independently repeats its checks inside its transaction.
|
||||
pub async fn revalidate_import_plan(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
plan_id: &ImportPlanId,
|
||||
verified_fingerprint: &Value,
|
||||
) -> Result<(), RegistryError> {
|
||||
let plan = self
|
||||
.get_import_plan(workspace_id, plan_id)
|
||||
.await?
|
||||
.ok_or_else(|| RegistryError::ImportPlanNotFound {
|
||||
plan_id: plan_id.as_str().to_owned(),
|
||||
})?;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
if plan.expires_at <= now {
|
||||
return Err(RegistryError::ImportPlanExpired {
|
||||
plan_id: plan_id.as_str().to_owned(),
|
||||
});
|
||||
}
|
||||
let request = ApplyImportPlanRequest {
|
||||
workspace_id,
|
||||
plan_id,
|
||||
plan_digest: &plan.digest,
|
||||
idempotency_key: "read-only-revalidation",
|
||||
verified_fingerprint,
|
||||
applied_at: &now,
|
||||
};
|
||||
let material = read_and_validate_plan_material(
|
||||
&plan.payload,
|
||||
&request,
|
||||
&plan.digest,
|
||||
plan.job_id.as_str(),
|
||||
)?;
|
||||
let job = self
|
||||
.get_import_job(workspace_id, &plan.job_id)
|
||||
.await?
|
||||
.ok_or_else(|| RegistryError::ImportPlanJobUnavailable {
|
||||
job_id: plan.job_id.as_str().to_owned(),
|
||||
})?;
|
||||
if job.status != ImportJobStatus::Pending || job.expires_at <= now {
|
||||
return Err(RegistryError::ImportPlanJobTerminal {
|
||||
job_id: job.id.as_str().to_owned(),
|
||||
});
|
||||
}
|
||||
verify_job_source_consistency(&job.preview_payload, &material, plan_id.as_str())?;
|
||||
let mut tx = self.pool.begin().await?;
|
||||
let mut envelopes = material
|
||||
.dependencies
|
||||
.iter()
|
||||
.chain(std::iter::once(&material.source))
|
||||
.map(|source| ImportJobSourceEnvelope {
|
||||
source_id: ArtifactSourceId::new(source.source_id.clone()),
|
||||
digest: ArtifactRef::parse(&source.digest).expect("material was validated"),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
envelopes.sort_by(|a, b| a.source_id.as_str().cmp(b.source_id.as_str()));
|
||||
for envelope in &envelopes {
|
||||
lock_and_verify_envelope(&mut tx, workspace_id, envelope).await?;
|
||||
}
|
||||
lock_and_verify_auth(&mut tx, workspace_id, &material.candidates).await?;
|
||||
if material.schema_version == "import-plan-v2"
|
||||
&& material.catalog_revision.as_deref()
|
||||
!= Some(
|
||||
super::super::catalog::catalog_revision(&mut *tx, workspace_id, true)
|
||||
.await?
|
||||
.as_str(),
|
||||
)
|
||||
{
|
||||
return Err(RegistryError::ImportPlanFingerprintStale {
|
||||
plan_id: plan_id.as_str().to_owned(),
|
||||
});
|
||||
}
|
||||
for candidate in &material.candidates {
|
||||
if let Some(target) = &candidate.target {
|
||||
let row = sqlx::query("select name, status, current_draft_version, latest_published_version from operations where workspace_id = $1 and id = $2 for share")
|
||||
.bind(workspace_id.as_str()).bind(&target.operation_id).fetch_optional(&mut *tx).await?;
|
||||
let matching = match row {
|
||||
Some(row) => {
|
||||
row.try_get::<String, _>("name")? == target.name
|
||||
&& deserialize_enum_text::<OperationStatus>(
|
||||
row.try_get("status")?,
|
||||
"status",
|
||||
)? == target.expected_state.status
|
||||
&& row.try_get::<i32, _>("current_draft_version")? as u32
|
||||
== target.expected_state.current_draft_version
|
||||
&& row
|
||||
.try_get::<Option<i32>, _>("latest_published_version")?
|
||||
.map(|value| value as u32)
|
||||
== target.expected_state.latest_published_version
|
||||
}
|
||||
None => false,
|
||||
};
|
||||
if !matching {
|
||||
return Err(RegistryError::ImportPlanTargetStale {
|
||||
operation_id: target.operation_id.clone(),
|
||||
});
|
||||
}
|
||||
} else if candidate.state == "actionable"
|
||||
&& operation_name_exists(&mut tx, workspace_id, &candidate.name).await?
|
||||
{
|
||||
return Err(RegistryError::ImportPlanNameConflict {
|
||||
name: candidate.name.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
tx.rollback().await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
use super::*;
|
||||
|
||||
/// Derives the canonical plan digest: the lowercase SHA-256 of the payload
|
||||
/// serialized to its deterministic byte form. `serde_json::Value` object keys
|
||||
/// are ordered (BTreeMap-backed map), so `to_vec` is stable across calls and
|
||||
/// platforms — the digest is therefore reproducible for byte-identical
|
||||
/// material without requiring a client-supplied digest.
|
||||
pub(super) fn plan_digest_from_payload(payload: &Value) -> Result<String, RegistryError> {
|
||||
if !payload.is_object() {
|
||||
return Err(RegistryError::InvalidImportPlan { field: "payload" });
|
||||
}
|
||||
let limit = if payload.get("schema_version").and_then(Value::as_str) == Some("import-plan-v2") {
|
||||
MAX_IMPORT_PLAN_PAYLOAD_BYTES
|
||||
} else {
|
||||
MAX_LEGACY_IMPORT_PLAN_PAYLOAD_BYTES
|
||||
};
|
||||
if serde_json::to_vec(payload)?.len() > limit {
|
||||
return Err(RegistryError::InvalidImportPlan { field: "payload" });
|
||||
}
|
||||
let canonical = serde_json::to_vec(&canonical_material(payload))?;
|
||||
Ok(format!("{:x}", Sha256::digest(canonical)))
|
||||
}
|
||||
|
||||
pub(super) fn validate_v2_sources(payload: &Value, preview: &Value) -> Result<(), RegistryError> {
|
||||
let dependency_set =
|
||||
|value: &Value| -> Result<std::collections::BTreeSet<(String, String)>, RegistryError> {
|
||||
Ok(dependencies_from_payload(value)?
|
||||
.iter()
|
||||
.map(|source| {
|
||||
(
|
||||
source.source_id.as_str().to_owned(),
|
||||
source.digest.as_str().to_owned(),
|
||||
)
|
||||
})
|
||||
.collect())
|
||||
};
|
||||
if source_from_payload(payload)? != source_from_payload(preview)?
|
||||
|| dependency_set(payload)? != dependency_set(preview)?
|
||||
{
|
||||
return Err(RegistryError::InvalidImportPlan { field: "source" });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes only server-generated envelope fields from v2 semantic material.
|
||||
/// Paths are explicit: equally named fields in a user schema remain semantic.
|
||||
pub(super) fn canonical_material(payload: &Value) -> Value {
|
||||
let mut material = payload.clone();
|
||||
if payload.get("schema_version").and_then(Value::as_str) != Some("import-plan-v2") {
|
||||
return material;
|
||||
}
|
||||
let object = material.as_object_mut().expect("validated object");
|
||||
object.remove("plan_reference");
|
||||
object.remove("job_id");
|
||||
if let Some(source) = object.get_mut("source").and_then(Value::as_object_mut) {
|
||||
source.remove("source_id");
|
||||
}
|
||||
if let Some(dependencies) = object.get_mut("dependencies").and_then(Value::as_array_mut) {
|
||||
for dependency in dependencies.iter_mut() {
|
||||
if let Some(source) = dependency.as_object_mut() {
|
||||
source.remove("source_id");
|
||||
}
|
||||
}
|
||||
dependencies.sort_by_key(Value::to_string);
|
||||
}
|
||||
if let Some(candidates) = object.get_mut("candidates").and_then(Value::as_array_mut) {
|
||||
for candidate in candidates {
|
||||
let generated = matches!(
|
||||
candidate
|
||||
.pointer("/decision/action")
|
||||
.and_then(Value::as_str),
|
||||
Some("create" | "rename")
|
||||
);
|
||||
if let Some(operation) = candidate
|
||||
.get_mut("operation")
|
||||
.and_then(Value::as_object_mut)
|
||||
{
|
||||
if generated {
|
||||
operation.remove("id");
|
||||
}
|
||||
operation.remove("created_at");
|
||||
operation.remove("updated_at");
|
||||
operation.remove("published_at");
|
||||
}
|
||||
if let Some(snapshot) = candidate
|
||||
.get_mut("auth_snapshot")
|
||||
.and_then(Value::as_object_mut)
|
||||
{
|
||||
snapshot.remove("updated_at");
|
||||
if let Some(secrets) = snapshot.get_mut("secrets").and_then(Value::as_array_mut) {
|
||||
for secret in secrets {
|
||||
if let Some(secret) = secret.as_object_mut() {
|
||||
secret.remove("updated_at");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
material
|
||||
}
|
||||
|
||||
pub(super) fn validate_v2_metadata(payload: &Value) -> Result<(), RegistryError> {
|
||||
let invalid = || RegistryError::InvalidImportPlan { field: "metadata" };
|
||||
let revision = payload
|
||||
.get("catalog_revision")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(invalid)?;
|
||||
if revision.len() != 64
|
||||
|| !revision
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
|
||||
{
|
||||
return Err(invalid());
|
||||
}
|
||||
let matrix = payload
|
||||
.get("support_matrix_version")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(invalid)?;
|
||||
if matrix.is_empty() || matrix.len() > 64 {
|
||||
return Err(invalid());
|
||||
}
|
||||
let findings = payload
|
||||
.get("findings")
|
||||
.and_then(Value::as_object)
|
||||
.ok_or_else(invalid)?;
|
||||
if !findings.get("document").is_some_and(Value::is_array)
|
||||
|| !findings.get("candidates").is_some_and(Value::is_array)
|
||||
{
|
||||
return Err(invalid());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::plan_digest_from_payload;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn payload() -> Value {
|
||||
json!({
|
||||
"schema_version": "import-plan-v2", "plan_reference": "plan_a", "job_id": "job_a",
|
||||
"catalog_revision": "a".repeat(64), "support_matrix_version": "1.0.2",
|
||||
"source": {"source_id": "src_a", "digest": format!("sha256:{}", "b".repeat(64))},
|
||||
"dependencies": [{"source_id": "dep_a", "digest": format!("sha256:{}", "c".repeat(64))}],
|
||||
"findings": {"document": [], "candidates": []},
|
||||
"selection": {"mode": "full", "selected": ["GET /a"], "excluded": [], "all": ["GET /a"]},
|
||||
"candidates": [{
|
||||
"key": "GET /a", "decision": {"action": "create"},
|
||||
"operation": {"id": "op_a", "created_at": "time_a", "updated_at": "time_a",
|
||||
"input_schema": {"properties": {"id": {"default": "semantic_id"}, "created_at": {"default": "semantic_time"}}}},
|
||||
"auth_snapshot": {"profile_id": "auth_a", "updated_at": "time_a", "secrets": [
|
||||
{"id": "secret_a", "current_version": 1, "status": "active", "updated_at": "time_a"}
|
||||
]}
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equivalent_v2_material_ignores_only_identity_envelope_and_runtime_instants() {
|
||||
let first = payload();
|
||||
let mut second = first.clone();
|
||||
second["plan_reference"] = json!("plan_b");
|
||||
second["job_id"] = json!("job_b");
|
||||
second["source"]["source_id"] = json!("src_b");
|
||||
second["dependencies"][0]["source_id"] = json!("dep_b");
|
||||
second["candidates"][0]["operation"]["id"] = json!("op_b");
|
||||
second["candidates"][0]["operation"]["created_at"] = json!("time_b");
|
||||
second["candidates"][0]["operation"]["updated_at"] = json!("time_b");
|
||||
second["candidates"][0]["auth_snapshot"]["updated_at"] = json!("time_b");
|
||||
second["candidates"][0]["auth_snapshot"]["secrets"][0]["updated_at"] = json!("time_b");
|
||||
assert_eq!(
|
||||
plan_digest_from_payload(&first).unwrap(),
|
||||
plan_digest_from_payload(&second).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn v2_semantic_changes_and_schema_fields_named_like_runtime_fields_change_digest() {
|
||||
let first = payload();
|
||||
for pointer in [
|
||||
"/catalog_revision",
|
||||
"/support_matrix_version",
|
||||
"/source/digest",
|
||||
"/candidates/0/decision/action",
|
||||
"/candidates/0/auth_snapshot/secrets/0/current_version",
|
||||
"/candidates/0/operation/input_schema/properties/id/default",
|
||||
"/candidates/0/operation/input_schema/properties/created_at/default",
|
||||
] {
|
||||
let mut changed = first.clone();
|
||||
*changed.pointer_mut(pointer).unwrap() = json!("changed");
|
||||
assert_ne!(
|
||||
plan_digest_from_payload(&first).unwrap(),
|
||||
plan_digest_from_payload(&changed).unwrap(),
|
||||
"{pointer}"
|
||||
);
|
||||
}
|
||||
let mut target = first.clone();
|
||||
target["candidates"][0]["decision"]["action"] = json!("new_version");
|
||||
let mut changed_target = target.clone();
|
||||
changed_target["candidates"][0]["operation"]["id"] = json!("different_existing_target");
|
||||
assert_ne!(
|
||||
plan_digest_from_payload(&target).unwrap(),
|
||||
plan_digest_from_payload(&changed_target).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_payload_digest_still_covers_runtime_and_identity_fields() {
|
||||
let mut first = payload();
|
||||
first["schema_version"] = json!("import-plan-v1");
|
||||
let mut second = first.clone();
|
||||
second["plan_reference"] = json!("other");
|
||||
assert_ne!(
|
||||
plan_digest_from_payload(&first).unwrap(),
|
||||
plan_digest_from_payload(&second).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn v2_payload_budget_grows_without_changing_the_legacy_budget() {
|
||||
let mut large =
|
||||
json!({"schema_version": "import-plan-v1", "evidence": "x".repeat(5 * 1024 * 1024)});
|
||||
assert!(plan_digest_from_payload(&large).is_err());
|
||||
large["schema_version"] = json!("import-plan-v2");
|
||||
assert!(plan_digest_from_payload(&large).is_ok());
|
||||
large["evidence"] = json!("x".repeat(16 * 1024 * 1024));
|
||||
assert!(plan_digest_from_payload(&large).is_err());
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ use time::format_description::well_known::Rfc3339;
|
||||
|
||||
mod apply;
|
||||
mod create;
|
||||
mod preview_v2;
|
||||
pub(super) fn parse_ts(value: &str) -> OffsetDateTime {
|
||||
OffsetDateTime::parse(value, &Rfc3339).unwrap()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,787 @@
|
||||
//! Story 2.12 evidence for v2 semantic digests, catalog drift and Apply.
|
||||
|
||||
use super::super::common::{TestDatabase, test_operation};
|
||||
use super::{create_pending_openapi_job, create_workspace, parse_ts};
|
||||
use crank_artifacts::ArtifactRef;
|
||||
use crank_core::{OperationStatus, WorkspaceId};
|
||||
use crank_registry::{
|
||||
ApplyImportPlanRequest, ArtifactSourceId, CreateImportJobRequest, CreateImportPlanRequest,
|
||||
ImportJobId, ImportJobKind, ImportJobSourceEnvelope, ImportJobStatus, ImportPlanApplyStatus,
|
||||
ImportPlanCandidateOutcome, ImportPlanId, RegistryError,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use sha2::{Digest, Sha256};
|
||||
use time::{Duration, OffsetDateTime};
|
||||
|
||||
const SOURCE_ID: &str = "src_openapi_test";
|
||||
const SOURCE_DIGEST: &str =
|
||||
"sha256:abababababababababababababababababababababababababababababababab";
|
||||
|
||||
fn fingerprint() -> Value {
|
||||
json!({"importer": "registry-preview-v2-test", "preview_digest": "fp-v2-1"})
|
||||
}
|
||||
|
||||
fn operation(
|
||||
id: &str,
|
||||
name: &str,
|
||||
created_at: &str,
|
||||
updated_at: &str,
|
||||
) -> crank_registry::RegistryOperation {
|
||||
let mut operation = test_operation(id, 1, OperationStatus::Draft);
|
||||
operation.name = name.to_owned();
|
||||
operation.display_name = "Candidate display name".to_owned();
|
||||
operation.execution_config.auth_profile_ref = None;
|
||||
operation.created_at = parse_ts(created_at);
|
||||
operation.updated_at = parse_ts(updated_at);
|
||||
operation
|
||||
}
|
||||
|
||||
fn v2_payload(
|
||||
plan_id: &str,
|
||||
job_id: &str,
|
||||
source_id: &str,
|
||||
operation: crank_registry::RegistryOperation,
|
||||
catalog_revision: &str,
|
||||
) -> Value {
|
||||
let key = "candidate";
|
||||
json!({
|
||||
"schema_version": "import-plan-v2",
|
||||
"plan_reference": plan_id,
|
||||
"job_id": job_id,
|
||||
"fingerprint": fingerprint(),
|
||||
"catalog_revision": catalog_revision,
|
||||
"support_matrix_version": "1.0.2",
|
||||
"source": { "source_id": source_id, "digest": SOURCE_DIGEST },
|
||||
"dependencies": [],
|
||||
"excluded_reasons": [],
|
||||
"findings": { "document": [], "candidates": [{ "key": key, "findings": [] }] },
|
||||
"selection": {
|
||||
"mode": "full", "all": [key], "selected": [key], "excluded": []
|
||||
},
|
||||
"counts": { "selected": 1, "excluded": 0, "actionable": 1, "blocked": 0 },
|
||||
"candidates": [{
|
||||
"key": key,
|
||||
"name": operation.name,
|
||||
"state": "actionable",
|
||||
"decision": { "action": "create" },
|
||||
"findings": [],
|
||||
"operation": operation
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
async fn store_plan(
|
||||
registry: &crank_registry::PostgresRegistry,
|
||||
workspace_id: &WorkspaceId,
|
||||
job_id: &ImportJobId,
|
||||
plan_id: &str,
|
||||
payload: &Value,
|
||||
created_at: OffsetDateTime,
|
||||
) -> (ImportPlanId, String) {
|
||||
let plan_id = ImportPlanId::new(plan_id);
|
||||
let created = registry
|
||||
.create_import_plan(CreateImportPlanRequest {
|
||||
id: &plan_id,
|
||||
workspace_id,
|
||||
job_id,
|
||||
payload,
|
||||
created_at: &created_at,
|
||||
expires_at: &(created_at + Duration::minutes(30)),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
(plan_id, created.digest)
|
||||
}
|
||||
|
||||
async fn activate_source(raw: &sqlx::PgPool, workspace_id: &WorkspaceId, now: OffsetDateTime) {
|
||||
let hex = "ab".repeat(32);
|
||||
sqlx::query(
|
||||
"insert into artifact_blobs (digest, artifact_ref, size_bytes, created_at, updated_at)
|
||||
values ($1, 'sha256:' || $1, 16, $2, $2)",
|
||||
)
|
||||
.bind(&hex)
|
||||
.bind(now)
|
||||
.execute(raw)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"insert into artifact_sources (
|
||||
workspace_id, source_id, blob_digest, mime_type, sensitivity, lifecycle,
|
||||
created_at, updated_at
|
||||
) values ($1, $2, $3, 'application/yaml', 'public', 'active', $4, $4)",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(SOURCE_ID)
|
||||
.bind(&hex)
|
||||
.bind(now)
|
||||
.execute(raw)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
async fn create_job_with_source(
|
||||
registry: &crank_registry::PostgresRegistry,
|
||||
workspace_id: &WorkspaceId,
|
||||
job_id: &str,
|
||||
source_id: &str,
|
||||
now: OffsetDateTime,
|
||||
) -> ImportJobId {
|
||||
let job_id = ImportJobId::new(job_id);
|
||||
let source_id = ArtifactSourceId::new(source_id);
|
||||
let digest = ArtifactRef::from_digest_hex(&"ab".repeat(32)).unwrap();
|
||||
let preview_payload = json!({
|
||||
"source": {"source_id": source_id.as_str(), "digest": digest.as_str()},
|
||||
"preview": {"source": "integration-test"}
|
||||
});
|
||||
registry
|
||||
.create_import_job(CreateImportJobRequest {
|
||||
id: &job_id,
|
||||
workspace_id,
|
||||
kind: ImportJobKind::OpenApi,
|
||||
source_format: "openapi",
|
||||
source_version: Some("3.1.0"),
|
||||
status: ImportJobStatus::Pending,
|
||||
source: &ImportJobSourceEnvelope { source_id, digest },
|
||||
preview_payload: &preview_payload,
|
||||
created_at: &now,
|
||||
expires_at: &(now + Duration::hours(1)),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
job_id
|
||||
}
|
||||
|
||||
fn raw_digest(payload: &Value) -> String {
|
||||
format!("{:x}", Sha256::digest(serde_json::to_vec(payload).unwrap()))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn v2_digest_ignores_job_plan_generated_operation_ids_and_runtime_timestamps() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let ws = create_workspace(®istry, "ws_v2_digest").await;
|
||||
let first_time =
|
||||
OffsetDateTime::from_unix_timestamp(OffsetDateTime::now_utc().unix_timestamp()).unwrap();
|
||||
let second_time = first_time + Duration::minutes(2);
|
||||
let first_job =
|
||||
create_job_with_source(®istry, &ws, "job_v2_digest_a", "src_v2_a", first_time).await;
|
||||
let second_job =
|
||||
create_job_with_source(®istry, &ws, "job_v2_digest_b", "src_v2_b", second_time).await;
|
||||
let revision = registry.import_catalog_revision(&ws).await.unwrap();
|
||||
let first_payload = v2_payload(
|
||||
"plan_v2_digest_a",
|
||||
first_job.as_str(),
|
||||
"src_v2_a",
|
||||
operation(
|
||||
"op_generated_a",
|
||||
"candidate_tool",
|
||||
"2026-03-25T10:00:00Z",
|
||||
"2026-03-25T10:00:00Z",
|
||||
),
|
||||
&revision,
|
||||
);
|
||||
let second_payload = v2_payload(
|
||||
"plan_v2_digest_b",
|
||||
second_job.as_str(),
|
||||
"src_v2_b",
|
||||
operation(
|
||||
"op_generated_b",
|
||||
"candidate_tool",
|
||||
"2026-03-25T10:02:00Z",
|
||||
"2026-03-25T10:02:00Z",
|
||||
),
|
||||
&revision,
|
||||
);
|
||||
|
||||
let (_, first_digest) = store_plan(
|
||||
®istry,
|
||||
&ws,
|
||||
&first_job,
|
||||
"plan_v2_digest_a",
|
||||
&first_payload,
|
||||
first_time,
|
||||
)
|
||||
.await;
|
||||
let (_, second_digest) = store_plan(
|
||||
®istry,
|
||||
&ws,
|
||||
&second_job,
|
||||
"plan_v2_digest_b",
|
||||
&second_payload,
|
||||
second_time,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
first_digest, second_digest,
|
||||
"server identities and runtime instants must not change semantic identity"
|
||||
);
|
||||
assert_eq!(
|
||||
registry
|
||||
.get_import_plan(&ws, &ImportPlanId::new("plan_v2_digest_a"))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.payload,
|
||||
first_payload,
|
||||
"canonical hashing must leave immutable v2 evidence untouched"
|
||||
);
|
||||
let mut replay_with_new_generated_id = first_payload.clone();
|
||||
replay_with_new_generated_id["candidates"][0]["operation"]["id"] = json!("op_generated_retry");
|
||||
let plan_id = ImportPlanId::new("plan_v2_digest_a");
|
||||
let conflict = registry
|
||||
.create_import_plan(CreateImportPlanRequest {
|
||||
id: &plan_id,
|
||||
workspace_id: &ws,
|
||||
job_id: &first_job,
|
||||
payload: &replay_with_new_generated_id,
|
||||
created_at: &first_time,
|
||||
expires_at: &(first_time + Duration::minutes(30)),
|
||||
})
|
||||
.await
|
||||
.expect_err("replay identity still compares immutable raw payload after semantic hashing");
|
||||
assert!(matches!(conflict, RegistryError::ImportPlanConflict { .. }));
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn v2_digest_changes_for_selection_name_and_conflict_decision() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let ws = create_workspace(®istry, "ws_v2_semantics").await;
|
||||
let job = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
"job_v2_semantics",
|
||||
now,
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
let revision = registry.import_catalog_revision(&ws).await.unwrap();
|
||||
let base = v2_payload(
|
||||
"plan_semantic_base",
|
||||
job.as_str(),
|
||||
SOURCE_ID,
|
||||
operation(
|
||||
"op_base",
|
||||
"candidate_tool",
|
||||
"2026-10-03T10:00:00Z",
|
||||
"2026-10-03T10:00:00Z",
|
||||
),
|
||||
&revision,
|
||||
);
|
||||
let mut changed_selection = base.clone();
|
||||
changed_selection["plan_reference"] = json!("plan_semantic_selection");
|
||||
changed_selection["selection"]["mode"] = json!("partial");
|
||||
changed_selection["selection"]["all"] = json!(["candidate", "other"]);
|
||||
changed_selection["selection"]["excluded"] = json!(["other"]);
|
||||
changed_selection["counts"]["excluded"] = json!(1);
|
||||
changed_selection["excluded_reasons"] = json!([{"key": "other", "reason": "not_selected"}]);
|
||||
changed_selection["findings"]["candidates"] = json!([
|
||||
{"key": "candidate", "findings": []}, {"key": "other", "findings": []}
|
||||
]);
|
||||
let mut changed_name = base.clone();
|
||||
changed_name["plan_reference"] = json!("plan_semantic_name");
|
||||
changed_name["candidates"][0]["name"] = json!("renamed_tool");
|
||||
changed_name["candidates"][0]["operation"]["name"] = json!("renamed_tool");
|
||||
let mut changed_decision = base.clone();
|
||||
changed_decision["plan_reference"] = json!("plan_semantic_decision");
|
||||
changed_decision["candidates"][0]["decision"] =
|
||||
json!({"action": "rename", "confirmed_name": "candidate_tool"});
|
||||
let mut changed_support_matrix = base.clone();
|
||||
changed_support_matrix["plan_reference"] = json!("plan_semantic_support");
|
||||
changed_support_matrix["support_matrix_version"] = json!("1.0.3");
|
||||
|
||||
let (_, digest) = store_plan(®istry, &ws, &job, "plan_semantic_base", &base, now).await;
|
||||
let (_, selection_digest) = store_plan(
|
||||
®istry,
|
||||
&ws,
|
||||
&job,
|
||||
"plan_semantic_selection",
|
||||
&changed_selection,
|
||||
now,
|
||||
)
|
||||
.await;
|
||||
let (_, name_digest) = store_plan(
|
||||
®istry,
|
||||
&ws,
|
||||
&job,
|
||||
"plan_semantic_name",
|
||||
&changed_name,
|
||||
now,
|
||||
)
|
||||
.await;
|
||||
let (_, decision_digest) = store_plan(
|
||||
®istry,
|
||||
&ws,
|
||||
&job,
|
||||
"plan_semantic_decision",
|
||||
&changed_decision,
|
||||
now,
|
||||
)
|
||||
.await;
|
||||
let (_, support_matrix_digest) = store_plan(
|
||||
®istry,
|
||||
&ws,
|
||||
&job,
|
||||
"plan_semantic_support",
|
||||
&changed_support_matrix,
|
||||
now,
|
||||
)
|
||||
.await;
|
||||
assert_ne!(digest, selection_digest, "selection changes are semantic");
|
||||
assert_ne!(
|
||||
digest, name_digest,
|
||||
"the confirmed operation name is semantic"
|
||||
);
|
||||
assert_ne!(
|
||||
digest, decision_digest,
|
||||
"conflict resolution choices are semantic"
|
||||
);
|
||||
assert_ne!(
|
||||
digest, support_matrix_digest,
|
||||
"the support matrix version is semantic evidence"
|
||||
);
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn legacy_v1_digest_and_stored_payload_remain_unchanged_and_readable() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let ws = create_workspace(®istry, "ws_v1_compat").await;
|
||||
let job = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
"job_v1_compat",
|
||||
now,
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
let plan_id = ImportPlanId::new("plan_v1_compat");
|
||||
let payload = json!({
|
||||
"schema_version": "import-plan-v1", "plan_reference": plan_id.as_str(), "job_id": job.as_str(),
|
||||
"fingerprint": {"legacy": true}, "source": {"source_id": SOURCE_ID, "digest": SOURCE_DIGEST},
|
||||
"dependencies": [], "selection": {"mode": "full", "all": ["legacy"], "selected": ["legacy"], "excluded": []},
|
||||
"counts": {"selected": 1, "excluded": 0, "actionable": 1, "blocked": 0},
|
||||
"candidates": [{"key": "legacy", "name": "legacy_tool", "state": "actionable", "decision": {"action": "create"}}]
|
||||
});
|
||||
let created = registry
|
||||
.create_import_plan(CreateImportPlanRequest {
|
||||
id: &plan_id,
|
||||
workspace_id: &ws,
|
||||
job_id: &job,
|
||||
payload: &payload,
|
||||
created_at: &now,
|
||||
expires_at: &(now + Duration::minutes(30)),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
created.digest,
|
||||
raw_digest(&payload),
|
||||
"legacy v1 keeps byte-for-byte digest rules"
|
||||
);
|
||||
let read = registry
|
||||
.get_import_plan(&ws, &plan_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("stored v1 plan remains readable");
|
||||
assert_eq!(read.payload, payload);
|
||||
assert_eq!(read.digest, created.digest);
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn catalog_revision_ignores_timestamps_and_foreign_workspace_but_tracks_semantics() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let raw = database.raw_pool().await;
|
||||
let ws = create_workspace(®istry, "ws_catalog_revision").await;
|
||||
let foreign = create_workspace(®istry, "ws_catalog_foreign").await;
|
||||
let mut local_op = operation(
|
||||
"op_catalog_local",
|
||||
"local_tool",
|
||||
"2026-10-03T10:00:00Z",
|
||||
"2026-10-03T10:00:00Z",
|
||||
);
|
||||
registry
|
||||
.create_operation(&ws, &local_op, None)
|
||||
.await
|
||||
.unwrap();
|
||||
let baseline = registry.import_catalog_revision(&ws).await.unwrap();
|
||||
|
||||
sqlx::query("update operations set updated_at = $1 where workspace_id = $2 and id = $3")
|
||||
.bind(parse_ts("2026-10-03T11:00:00Z"))
|
||||
.bind(ws.as_str())
|
||||
.bind(local_op.id.as_str())
|
||||
.execute(&raw)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
registry.import_catalog_revision(&ws).await.unwrap(),
|
||||
baseline,
|
||||
"runtime timestamps are excluded"
|
||||
);
|
||||
|
||||
let foreign_op = operation(
|
||||
"op_catalog_foreign",
|
||||
"foreign_tool",
|
||||
"2026-10-03T10:00:00Z",
|
||||
"2026-10-03T10:00:00Z",
|
||||
);
|
||||
registry
|
||||
.create_operation(&foreign, &foreign_op, None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
registry.import_catalog_revision(&ws).await.unwrap(),
|
||||
baseline,
|
||||
"foreign scope is excluded"
|
||||
);
|
||||
|
||||
sqlx::query(
|
||||
"update operations set name = 'renamed_local_tool' where workspace_id = $1 and id = $2",
|
||||
)
|
||||
.bind(ws.as_str())
|
||||
.bind(local_op.id.as_str())
|
||||
.execute(&raw)
|
||||
.await
|
||||
.unwrap();
|
||||
let renamed = registry.import_catalog_revision(&ws).await.unwrap();
|
||||
assert_ne!(renamed, baseline, "catalog names affect the revision");
|
||||
sqlx::query(
|
||||
"update operations set current_draft_version = 2 where workspace_id = $1 and id = $2",
|
||||
)
|
||||
.bind(ws.as_str())
|
||||
.bind(local_op.id.as_str())
|
||||
.execute(&raw)
|
||||
.await
|
||||
.unwrap();
|
||||
let versioned = registry.import_catalog_revision(&ws).await.unwrap();
|
||||
assert_ne!(
|
||||
versioned, renamed,
|
||||
"catalog version pointers affect the revision"
|
||||
);
|
||||
sqlx::query("update operations set status = 'published' where workspace_id = $1 and id = $2")
|
||||
.bind(ws.as_str())
|
||||
.bind(local_op.id.as_str())
|
||||
.execute(&raw)
|
||||
.await
|
||||
.unwrap();
|
||||
let status_changed = registry.import_catalog_revision(&ws).await.unwrap();
|
||||
assert_ne!(
|
||||
status_changed, versioned,
|
||||
"catalog lifecycle affects the revision"
|
||||
);
|
||||
// Avoid accidental use of stale local fixture state if this case grows.
|
||||
local_op.name = "renamed_local_tool".to_owned();
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn revalidation_and_apply_reject_catalog_drift_without_plan_mutation() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let raw = database.raw_pool().await;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let ws = create_workspace(®istry, "ws_v2_drift").await;
|
||||
let job = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
"job_v2_drift",
|
||||
now,
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
activate_source(&raw, &ws, now).await;
|
||||
let fp = fingerprint();
|
||||
let revision = registry.import_catalog_revision(&ws).await.unwrap();
|
||||
let plan_id_text = "plan_v2_drift";
|
||||
let payload = v2_payload(
|
||||
plan_id_text,
|
||||
job.as_str(),
|
||||
SOURCE_ID,
|
||||
operation(
|
||||
"op_v2_planned",
|
||||
"planned_tool",
|
||||
"2026-10-03T10:00:00Z",
|
||||
"2026-10-03T10:00:00Z",
|
||||
),
|
||||
&revision,
|
||||
);
|
||||
let (plan, digest) = store_plan(®istry, &ws, &job, plan_id_text, &payload, now).await;
|
||||
registry
|
||||
.revalidate_import_plan(&ws, &plan, &fp)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let catalog_change = operation(
|
||||
"op_v2_catalog_change",
|
||||
"catalog_change_tool",
|
||||
"2026-10-03T10:00:00Z",
|
||||
"2026-10-03T10:00:00Z",
|
||||
);
|
||||
registry
|
||||
.create_operation(&ws, &catalog_change, None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
matches!(
|
||||
registry.revalidate_import_plan(&ws, &plan, &fp).await,
|
||||
Err(RegistryError::ImportPlanFingerprintStale { .. })
|
||||
),
|
||||
"read-only revalidation must flag catalog drift"
|
||||
);
|
||||
|
||||
let request = ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &plan,
|
||||
plan_digest: &digest,
|
||||
idempotency_key: "idem_v2_drift",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &now,
|
||||
};
|
||||
assert!(
|
||||
matches!(
|
||||
registry.apply_import_plan(&request).await,
|
||||
Err(RegistryError::ImportPlanFingerprintStale { .. })
|
||||
),
|
||||
"fresh Apply must independently reject the stale catalog revision"
|
||||
);
|
||||
assert!(
|
||||
registry
|
||||
.get_operation_summary(&ws, &crank_core::OperationId::new("op_v2_planned"))
|
||||
.await
|
||||
.unwrap()
|
||||
.is_none(),
|
||||
"catalog drift must fail before creating the planned operation"
|
||||
);
|
||||
assert_eq!(
|
||||
registry
|
||||
.get_import_plan_application(&ws, "idem_v2_drift")
|
||||
.await
|
||||
.unwrap(),
|
||||
None,
|
||||
"a stale apply must not persist application evidence"
|
||||
);
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn v2_apply_creates_operation_and_reports_the_confirmed_candidate() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let raw = database.raw_pool().await;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let ws = create_workspace(®istry, "ws_v2_apply").await;
|
||||
let job = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
"job_v2_apply",
|
||||
now,
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
activate_source(&raw, &ws, now).await;
|
||||
let fp = fingerprint();
|
||||
let revision = registry.import_catalog_revision(&ws).await.unwrap();
|
||||
let payload = v2_payload(
|
||||
"plan_v2_apply",
|
||||
job.as_str(),
|
||||
SOURCE_ID,
|
||||
operation(
|
||||
"op_v2_apply",
|
||||
"v2_apply_tool",
|
||||
"2026-10-03T10:00:00Z",
|
||||
"2026-10-03T10:00:00Z",
|
||||
),
|
||||
&revision,
|
||||
);
|
||||
let (plan, digest) = store_plan(®istry, &ws, &job, "plan_v2_apply", &payload, now).await;
|
||||
let request = ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &plan,
|
||||
plan_digest: &digest,
|
||||
idempotency_key: "idem_v2_apply",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &now,
|
||||
};
|
||||
let result = registry.apply_import_plan(&request).await.unwrap();
|
||||
assert!(!result.replayed);
|
||||
assert_eq!(result.report.status, ImportPlanApplyStatus::Applied);
|
||||
assert_eq!(result.report.counts.created, 1);
|
||||
assert_eq!(result.report.outcomes[0].key, "candidate");
|
||||
assert_eq!(
|
||||
result.report.outcomes[0].outcome,
|
||||
ImportPlanCandidateOutcome::Created
|
||||
);
|
||||
assert_eq!(
|
||||
result.report.outcomes[0].operation_id.as_deref(),
|
||||
Some("op_v2_apply")
|
||||
);
|
||||
assert_eq!(
|
||||
registry
|
||||
.get_operation_summary(&ws, &crank_core::OperationId::new("op_v2_apply"))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.current_draft_version,
|
||||
1
|
||||
);
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn partial_v2_apply_preserves_the_reason_for_an_excluded_candidate() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let raw = database.raw_pool().await;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let ws = create_workspace(®istry, "ws_v2_excluded_reason").await;
|
||||
let job = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
"job_v2_excluded_reason",
|
||||
now,
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
activate_source(&raw, &ws, now).await;
|
||||
let fp = fingerprint();
|
||||
let revision = registry.import_catalog_revision(&ws).await.unwrap();
|
||||
let mut payload = v2_payload(
|
||||
"plan_v2_excluded_reason",
|
||||
job.as_str(),
|
||||
SOURCE_ID,
|
||||
operation(
|
||||
"op_v2_excluded_reason",
|
||||
"selected_tool",
|
||||
"2026-10-03T10:00:00Z",
|
||||
"2026-10-03T10:00:00Z",
|
||||
),
|
||||
&revision,
|
||||
);
|
||||
payload["selection"] = json!({
|
||||
"mode": "partial", "all": ["candidate", "unsupported"],
|
||||
"selected": ["candidate"], "excluded": ["unsupported"]
|
||||
});
|
||||
payload["counts"] = json!({"selected": 1, "excluded": 1, "actionable": 1, "blocked": 0});
|
||||
payload["excluded_reasons"] = json!([{"key": "unsupported", "reason": "unsupported_schema"}]);
|
||||
payload["findings"]["candidates"] = json!([
|
||||
{"key": "candidate", "findings": []},
|
||||
{"key": "unsupported", "findings": [{"code": "unsupported_schema"}]}
|
||||
]);
|
||||
let (plan, digest) = store_plan(
|
||||
®istry,
|
||||
&ws,
|
||||
&job,
|
||||
"plan_v2_excluded_reason",
|
||||
&payload,
|
||||
now,
|
||||
)
|
||||
.await;
|
||||
let request = ApplyImportPlanRequest {
|
||||
workspace_id: &ws,
|
||||
plan_id: &plan,
|
||||
plan_digest: &digest,
|
||||
idempotency_key: "idem_v2_excluded_reason",
|
||||
verified_fingerprint: &fp,
|
||||
applied_at: &now,
|
||||
};
|
||||
let result = registry.apply_import_plan(&request).await.unwrap();
|
||||
assert_eq!(result.report.status, ImportPlanApplyStatus::Applied);
|
||||
assert_eq!(result.report.counts.excluded, 1);
|
||||
let excluded = result
|
||||
.report
|
||||
.outcomes
|
||||
.iter()
|
||||
.find(|item| item.key == "unsupported")
|
||||
.unwrap();
|
||||
assert_eq!(excluded.outcome, ImportPlanCandidateOutcome::Excluded);
|
||||
assert_eq!(excluded.reason.as_deref(), Some("unsupported_schema"));
|
||||
assert!(
|
||||
registry
|
||||
.get_operation_summary(&ws, &crank_core::OperationId::new("op_v2_excluded_reason"))
|
||||
.await
|
||||
.unwrap()
|
||||
.is_some()
|
||||
);
|
||||
database.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn plan_store_accepts_the_full_two_thousand_candidate_limit() {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let raw = database.raw_pool().await;
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let ws = create_workspace(®istry, "ws_v2_limit").await;
|
||||
let job = create_pending_openapi_job(
|
||||
®istry,
|
||||
&ws,
|
||||
"job_v2_limit",
|
||||
now,
|
||||
now + Duration::hours(1),
|
||||
)
|
||||
.await;
|
||||
activate_source(&raw, &ws, now).await;
|
||||
let revision = registry.import_catalog_revision(&ws).await.unwrap();
|
||||
let mut keys = Vec::with_capacity(2_000);
|
||||
let mut candidates = Vec::with_capacity(2_000);
|
||||
let mut candidate_findings = Vec::with_capacity(2_000);
|
||||
for index in 0..2_000 {
|
||||
let key = format!("candidate-{index:04}");
|
||||
let name = format!("candidate_{index:04}_tool");
|
||||
let operation = operation(
|
||||
&format!("op_limit_{index:04}"),
|
||||
&name,
|
||||
"2026-10-03T10:00:00Z",
|
||||
"2026-10-03T10:00:00Z",
|
||||
);
|
||||
keys.push(key.clone());
|
||||
candidates.push(json!({
|
||||
"key": key, "name": name, "state": "actionable", "decision": {"action": "create"},
|
||||
"findings": [], "operation": operation
|
||||
}));
|
||||
candidate_findings.push(json!({"key": key, "findings": []}));
|
||||
}
|
||||
let payload = json!({
|
||||
"schema_version": "import-plan-v2", "plan_reference": "plan_v2_limit", "job_id": job.as_str(),
|
||||
"fingerprint": fingerprint(), "catalog_revision": revision, "support_matrix_version": "1.0.2",
|
||||
"source": {"source_id": SOURCE_ID, "digest": SOURCE_DIGEST}, "dependencies": [],
|
||||
"excluded_reasons": [],
|
||||
"findings": {"document": [], "candidates": candidate_findings},
|
||||
"selection": {"mode": "full", "all": keys, "selected": keys, "excluded": []},
|
||||
"counts": {"selected": 2_000, "excluded": 0, "actionable": 2_000, "blocked": 0},
|
||||
"candidates": candidates
|
||||
});
|
||||
let encoded = serde_json::to_vec(&payload).unwrap();
|
||||
assert!(
|
||||
encoded.len() < 16 * 1024 * 1024,
|
||||
"fixture itself must remain under the payload cap"
|
||||
);
|
||||
let (plan_id, _) = store_plan(®istry, &ws, &job, "plan_v2_limit", &payload, now).await;
|
||||
let stored = registry
|
||||
.get_import_plan(&ws, &plan_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
stored.payload["candidates"].as_array().unwrap().len(),
|
||||
2_000
|
||||
);
|
||||
assert_eq!(
|
||||
stored.payload["selection"]["selected"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.len(),
|
||||
2_000
|
||||
);
|
||||
registry
|
||||
.revalidate_import_plan(&ws, &plan_id, &fingerprint())
|
||||
.await
|
||||
.expect("the maximum valid candidate set must pass registry material validation");
|
||||
database.cleanup().await;
|
||||
}
|
||||
Reference in new issue
Block a user