[skip ci] wip: preserve Hermes crank development checkpoint
Owner-authorized recovery of accumulated source changes.
Includes accepted work and in-progress changes; NOT a release or acceptance.
Parent baseline 1b6db09bd1. Runtime data, build caches and local credentials excluded.
This commit is contained in:
1 parent
1b6db09bd1
commit
301dce301a
357 files changed
+118831
-5113
No files matched your search
@@ -91,6 +91,12 @@ pub enum RegistryError {
|
||||
},
|
||||
#[error("operation {operation_id} is archived")]
|
||||
OperationArchived { operation_id: String },
|
||||
#[error("resource {resource_id} is archived and cannot receive new Agent bindings")]
|
||||
ResourceArchived { resource_id: String },
|
||||
#[error(
|
||||
"resource {resource_id} is revoked and cannot receive new Agent bindings or publications"
|
||||
)]
|
||||
ResourceRevoked { resource_id: String },
|
||||
#[error("operation {operation_id} has a stale base version: expected {expected}, got {actual}")]
|
||||
OperationStaleVersion {
|
||||
operation_id: String,
|
||||
@@ -202,4 +208,43 @@ pub enum RegistryError {
|
||||
ArtifactClaimInProgress,
|
||||
#[error("artifact source metadata is invalid for field {field}")]
|
||||
InvalidArtifactSource { field: &'static str },
|
||||
#[error("prompt {prompt_id} was not found in this workspace")]
|
||||
PromptNotFound { prompt_id: String },
|
||||
#[error("prompt {prompt_id} is not in Draft state")]
|
||||
PromptNotDraft { prompt_id: String },
|
||||
#[error("prompt {prompt_id} changed since it was read")]
|
||||
PromptStaleRevision { prompt_id: String },
|
||||
#[error("prompt {prompt_id} version counter overflowed")]
|
||||
PromptVersionOverflow { prompt_id: String },
|
||||
#[error("prompt {prompt_id} has invalid stored data")]
|
||||
PromptCorrupt { prompt_id: String },
|
||||
#[error("prompt {prompt_id} is archived and cannot receive new bindings")]
|
||||
PromptArchived { prompt_id: String },
|
||||
#[error("published prompt version for {prompt_id} was not found in this workspace")]
|
||||
PromptPublicationNotFound { prompt_id: String },
|
||||
#[error("prompt {prompt_id} version is already published")]
|
||||
PromptPublicationConflict { prompt_id: String },
|
||||
#[error("prompt {prompt_id} dependency at position {position} cannot be resolved")]
|
||||
PromptDependencyUnresolved {
|
||||
prompt_id: String,
|
||||
position: usize,
|
||||
resource_id: String,
|
||||
version: u32,
|
||||
},
|
||||
#[error("prompt {prompt_id} dependency at position {position} has no text representation")]
|
||||
PromptDependencyRepresentationUnsupported {
|
||||
prompt_id: String,
|
||||
position: usize,
|
||||
resource_id: String,
|
||||
version: u32,
|
||||
},
|
||||
#[error("prompt {prompt_id} dependency at position {position} is not referenced by a message")]
|
||||
PromptDependencyUnused {
|
||||
prompt_id: String,
|
||||
position: usize,
|
||||
resource_id: String,
|
||||
version: u32,
|
||||
},
|
||||
#[error("prompt {prompt_id} dependency at position {position} is unavailable")]
|
||||
PromptDependencyUnavailable { prompt_id: String, position: usize },
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
mod error;
|
||||
mod ext;
|
||||
mod migrations;
|
||||
mod model;
|
||||
pub mod model;
|
||||
mod postgres;
|
||||
|
||||
pub use error::RegistryError;
|
||||
@@ -13,15 +13,15 @@ pub use migrations::{
|
||||
|
||||
pub mod records {
|
||||
pub use crate::model::{
|
||||
AdminBootstrapContractRecord, AgentSummary, AgentVersionRecord, AppendProductEventOutcome,
|
||||
AppliedImportOperation, ApprovalRequestRecord, ArtifactBlobLifecycle, ArtifactBlobRecord,
|
||||
ArtifactClaimFinalization, ArtifactClaimFinalizeOutcome, ArtifactClaimOutcome,
|
||||
ArtifactClaimRecheckOutcome, ArtifactClaimToken, ArtifactDigest, ArtifactExpiredClaimProbe,
|
||||
ArtifactReconciliationClaim, ArtifactSourceCursor, ArtifactSourceId,
|
||||
ArtifactSourceLifecycle, ArtifactSourcePage, ArtifactSourceRecord,
|
||||
ArtifactSourceSensitivity, AuthUserRecord, DescriptorKind, DescriptorMetadata, ImportJob,
|
||||
ImportJobApplyResult, ImportJobCleanupReport, ImportJobId, ImportJobKind,
|
||||
ImportJobSourceEnvelope, ImportJobStatus, ImportPlan, ImportPlanApplication,
|
||||
AdminBootstrapContractRecord, AgentResourceBinding, AgentSummary, AgentVersionRecord,
|
||||
AppendProductEventOutcome, AppliedImportOperation, ApprovalRequestRecord,
|
||||
ArtifactBlobLifecycle, ArtifactBlobRecord, ArtifactClaimFinalization,
|
||||
ArtifactClaimFinalizeOutcome, ArtifactClaimOutcome, ArtifactClaimRecheckOutcome,
|
||||
ArtifactClaimToken, ArtifactDigest, ArtifactExpiredClaimProbe, ArtifactReconciliationClaim,
|
||||
ArtifactSourceCursor, ArtifactSourceId, ArtifactSourceLifecycle, ArtifactSourcePage,
|
||||
ArtifactSourceRecord, ArtifactSourceSensitivity, AuthUserRecord, DescriptorKind,
|
||||
DescriptorMetadata, ImportJob, ImportJobApplyResult, ImportJobCleanupReport, ImportJobId,
|
||||
ImportJobKind, ImportJobSourceEnvelope, ImportJobStatus, ImportPlan, ImportPlanApplication,
|
||||
ImportPlanApplyCounts, ImportPlanApplyReport, ImportPlanApplyStatus,
|
||||
ImportPlanCandidateOutcome, ImportPlanCandidateReport, ImportPlanDependencyRef,
|
||||
ImportPlanId, InvitationRecord, InvocationHistoryLoss, InvocationHistoryLossCategory,
|
||||
@@ -72,15 +72,15 @@ pub mod infrastructure {
|
||||
}
|
||||
|
||||
pub use model::{
|
||||
AdminBootstrapContractRecord, AdminSecurityAuditRequest, AgentStateExpectation, AgentSummary,
|
||||
AgentVersionRecord, AppendProductEventOutcome, AppendProductEventRequest,
|
||||
AppliedImportOperation, ApplyImportJobRequest, ApplyImportPlanRequest, ApplyImportPlanResult,
|
||||
ApprovalRequestRecord, ArtifactBlobLifecycle, ArtifactBlobRecord, ArtifactClaimFinalization,
|
||||
ArtifactClaimFinalizeOutcome, ArtifactClaimOutcome, ArtifactClaimRecheckOutcome,
|
||||
ArtifactClaimToken, ArtifactDigest, ArtifactExpiredClaimProbe, ArtifactReconciliationClaim,
|
||||
ArtifactSourceCursor, ArtifactSourceId, ArtifactSourceLifecycle, ArtifactSourcePage,
|
||||
ArtifactSourceRecord, ArtifactSourceSensitivity, AuthUserRecord,
|
||||
ClaimArtifactReconciliationRequest, ClaimExpiredArtifactReconciliationRequest,
|
||||
AdminBootstrapContractRecord, AdminSecurityAuditRequest, AgentResourceBinding,
|
||||
AgentStateExpectation, AgentSummary, AgentVersionRecord, AppendProductEventOutcome,
|
||||
AppendProductEventRequest, AppliedImportOperation, ApplyImportJobRequest,
|
||||
ApplyImportPlanRequest, ApplyImportPlanResult, ApprovalRequestRecord, ArtifactBlobLifecycle,
|
||||
ArtifactBlobRecord, ArtifactClaimFinalization, ArtifactClaimFinalizeOutcome,
|
||||
ArtifactClaimOutcome, ArtifactClaimRecheckOutcome, ArtifactClaimToken, ArtifactDigest,
|
||||
ArtifactExpiredClaimProbe, ArtifactReconciliationClaim, ArtifactSourceCursor, ArtifactSourceId,
|
||||
ArtifactSourceLifecycle, ArtifactSourcePage, ArtifactSourceRecord, ArtifactSourceSensitivity,
|
||||
AuthUserRecord, ClaimArtifactReconciliationRequest, ClaimExpiredArtifactReconciliationRequest,
|
||||
ConsumeAdminBootstrapContractRequest, CreateAdminBootstrapContractRequest,
|
||||
CreateAgentDraftVersionRequest, CreateAgentRequest, CreateApprovalRequest,
|
||||
CreateArtifactSourceRequest, CreateImportJobRequest, CreateImportPlanRequest,
|
||||
@@ -115,4 +115,7 @@ pub use model::{
|
||||
WorkspaceMembershipRecord, WorkspaceRecord, WorkspaceUpstream, WorkspaceUpstreamId,
|
||||
YamlImportJob, YamlImportJobCompletion, YamlImportJobId, YamlImportJobStatus,
|
||||
};
|
||||
pub use postgres::{PostgresPoolConfig, PostgresPoolConfigError, PostgresRegistry};
|
||||
pub use postgres::{
|
||||
AuthorizedResourceRead, BoundResourceAdmission, PostgresPoolConfig, PostgresPoolConfigError,
|
||||
PostgresRegistry,
|
||||
};
|
||||
@@ -1,5 +1,6 @@
|
||||
mod admin_auth_lifecycle_v8;
|
||||
mod agent_catalog_lifecycle_v9;
|
||||
mod agent_resource_bindings_v18;
|
||||
mod approval_side_effects_v10;
|
||||
mod artifact_cleanup_indexes_v13;
|
||||
mod artifact_metadata_v12;
|
||||
@@ -12,6 +13,13 @@ mod onboarding_import_selection_v15;
|
||||
mod onboarding_product_events_v11;
|
||||
mod owned_relations;
|
||||
mod platform_key_name_reuse_v6;
|
||||
mod prompt_dependencies_v23;
|
||||
mod prompt_publications_v22;
|
||||
mod prompts_v21;
|
||||
mod resource_drafts_v16;
|
||||
mod resource_publications_v17;
|
||||
mod resource_security_revocations_v19;
|
||||
mod resource_template_sources_v20;
|
||||
mod schema_guard;
|
||||
mod schema_guard_legacy_v1;
|
||||
mod schema_guard_v10;
|
||||
@@ -20,6 +28,13 @@ mod schema_guard_v12;
|
||||
mod schema_guard_v13;
|
||||
mod schema_guard_v14;
|
||||
mod schema_guard_v15;
|
||||
mod schema_guard_v16;
|
||||
mod schema_guard_v17;
|
||||
mod schema_guard_v18;
|
||||
mod schema_guard_v19;
|
||||
mod schema_guard_v20;
|
||||
mod schema_guard_v22;
|
||||
mod schema_guard_v23;
|
||||
mod schema_guard_v7;
|
||||
mod schema_guard_v8;
|
||||
mod schema_guard_v9;
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
use sqlx::{Postgres, Transaction, query};
|
||||
|
||||
use super::authority::{MigrationDescriptor, MigrationError};
|
||||
|
||||
pub(super) const NAME: &str = "agent-resource-bindings-v18";
|
||||
pub(super) const SOURCE: &str = include_str!("agent_resource_bindings_v18.sql");
|
||||
pub(super) const SOURCE_SHA256: &str =
|
||||
"cb9b82183e04eb72c1f1a9ec853fcfc618f2b1c2a73edd051245890292beeb8f";
|
||||
|
||||
pub(super) async fn apply(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
descriptor: &MigrationDescriptor,
|
||||
) -> Result<(), MigrationError> {
|
||||
sqlx::raw_sql(SOURCE)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.agent_resource_bindings",
|
||||
Some(18),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
query(
|
||||
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
|
||||
values ($1, $2, $3, $4, $5)",
|
||||
)
|
||||
.bind(descriptor.version)
|
||||
.bind(descriptor.name)
|
||||
.bind(&descriptor.checksum)
|
||||
.bind(descriptor.phase)
|
||||
.bind(descriptor.compatibility)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.canonical_ledger",
|
||||
Some(18),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
-- V18: typed exact Resource bindings Agent (Story 3.7 AC04, FR-15/FR-16).
|
||||
--
|
||||
-- Отдельная typed-таблица вместо JSON-поля: строка адресует точную
|
||||
-- Published Resource Version (`resource_publications`) для точной версии Agent
|
||||
-- (`agent_versions`). `latest`/floating версия невозможна, потому что FK указывает
|
||||
-- на конкретную строку публикации.
|
||||
--
|
||||
-- Workspace-равенство обеспечивается на ОБОИХ концах composite FK:
|
||||
-- * (workspace_id, agent_id) -> agents(workspace_id, id);
|
||||
-- * (workspace_id, resource_id, resource_version) -> resource_publications(...).
|
||||
-- Поэтому ни Agent другого workspace, ни чужая/неопубликованная Resource Version
|
||||
-- не могут стать частью binding.
|
||||
--
|
||||
-- Published Agent Version immutable: V18-local trigger function проверяет и OLD,
|
||||
-- и NEW ключ строки. Canonical V9 function при UPDATE смотрит только на NEW,
|
||||
-- поэтому перенос binding из опубликованного snapshot в Draft-версию другого
|
||||
-- Agent проходил бы через неё без отказа. V9/V17 SQL не изменяются.
|
||||
|
||||
-- Immutable guard V18: отказ, если затронута опубликованная версия Agent —
|
||||
-- либо покидаемая (OLD), либо новая (NEW).
|
||||
create function crank_reject_published_agent_resource_binding_mutation()
|
||||
returns trigger
|
||||
language plpgsql
|
||||
as $$
|
||||
declare
|
||||
bound_status text;
|
||||
begin
|
||||
if tg_op in ('UPDATE', 'DELETE') then
|
||||
select status
|
||||
into bound_status
|
||||
from agent_versions
|
||||
where agent_id = old.agent_id and version = old.agent_version;
|
||||
if bound_status = 'published' then
|
||||
raise exception 'published Agent catalog bindings are immutable'
|
||||
using errcode = '23514';
|
||||
end if;
|
||||
end if;
|
||||
if tg_op in ('INSERT', 'UPDATE') then
|
||||
select status
|
||||
into bound_status
|
||||
from agent_versions
|
||||
where agent_id = new.agent_id and version = new.agent_version;
|
||||
if bound_status = 'published' then
|
||||
raise exception 'published Agent catalog bindings are immutable'
|
||||
using errcode = '23514';
|
||||
end if;
|
||||
end if;
|
||||
if tg_op = 'DELETE' then
|
||||
return old;
|
||||
end if;
|
||||
return new;
|
||||
end;
|
||||
$$;
|
||||
|
||||
create unique index agents_workspace_id_idx on agents(workspace_id, id);
|
||||
|
||||
create table agent_resource_bindings (
|
||||
workspace_id text not null,
|
||||
agent_id text not null,
|
||||
agent_version integer not null,
|
||||
resource_id text not null,
|
||||
resource_version integer not null,
|
||||
constraint agent_resource_bindings_agent_version_check check (agent_version >= 1),
|
||||
constraint agent_resource_bindings_resource_version_check check (resource_version >= 1),
|
||||
primary key (agent_id, agent_version, resource_id, resource_version),
|
||||
constraint agent_resource_bindings_agent_workspace_fkey
|
||||
foreign key (workspace_id, agent_id)
|
||||
references agents(workspace_id, id) on delete cascade,
|
||||
constraint agent_resource_bindings_agent_version_fkey
|
||||
foreign key (agent_id, agent_version)
|
||||
references agent_versions(agent_id, version) on delete cascade,
|
||||
constraint agent_resource_bindings_publication_fkey
|
||||
foreign key (workspace_id, resource_id, resource_version)
|
||||
references resource_publications(workspace_id, resource_id, version)
|
||||
on delete cascade
|
||||
);
|
||||
|
||||
create trigger agent_resource_bindings_immutable_guard
|
||||
before insert or update or delete on agent_resource_bindings
|
||||
for each row
|
||||
execute function crank_reject_published_agent_resource_binding_mutation();
|
||||
|
||||
create index agent_resource_bindings_resource_idx
|
||||
on agent_resource_bindings (workspace_id, resource_id, resource_version);
|
||||
@@ -1,5 +1,6 @@
|
||||
use super::admin_auth_lifecycle_v8;
|
||||
use super::agent_catalog_lifecycle_v9;
|
||||
use super::agent_resource_bindings_v18;
|
||||
use super::approval_side_effects_v10;
|
||||
use super::artifact_cleanup_indexes_v13;
|
||||
use super::artifact_metadata_v12;
|
||||
@@ -10,6 +11,13 @@ use super::onboarding_import_selection_v15;
|
||||
use super::onboarding_product_events_v11;
|
||||
use super::owned_relations;
|
||||
use super::platform_key_name_reuse_v6;
|
||||
use super::prompt_dependencies_v23;
|
||||
use super::prompt_publications_v22;
|
||||
use super::prompts_v21;
|
||||
use super::resource_drafts_v16;
|
||||
use super::resource_publications_v17;
|
||||
use super::resource_security_revocations_v19;
|
||||
use super::resource_template_sources_v20;
|
||||
use super::schema_guard::{
|
||||
OWNED_RELATIONS, relation_exists, validate_required_relations, validate_schema_fingerprint,
|
||||
};
|
||||
@@ -23,12 +31,18 @@ use std::fmt;
|
||||
|
||||
mod contract;
|
||||
|
||||
mod preflight;
|
||||
|
||||
use preflight::*;
|
||||
|
||||
#[cfg(test)]
|
||||
use contract::baseline_source_digest;
|
||||
use contract::validate_descriptors;
|
||||
const MIGRATION_LOCK_ID: i64 = 0x4352_414E_4B4D_4947;
|
||||
const CURRENT_VERSION: i64 = 15;
|
||||
const IMPLEMENTED_VERSIONS: &[i64] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
|
||||
const CURRENT_VERSION: i64 = 23;
|
||||
const IMPLEMENTED_VERSIONS: &[i64] = &[
|
||||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
|
||||
];
|
||||
const BASELINE_SOURCE_SHA256: &str =
|
||||
"eb1656fc5b4b5be9ee390d237d1d58e4b2274ae5ba9b7ba06a2f3f860dfda675";
|
||||
const CONSOLIDATION_SOURCE: &str = include_str!("consolidation_v2.sql");
|
||||
@@ -273,6 +287,49 @@ impl MigrationAuthority {
|
||||
onboarding_import_selection_v15::SOURCE_SHA256,
|
||||
14,
|
||||
),
|
||||
expand_descriptor(
|
||||
16,
|
||||
resource_drafts_v16::NAME,
|
||||
resource_drafts_v16::SOURCE_SHA256,
|
||||
15,
|
||||
),
|
||||
expand_descriptor(
|
||||
17,
|
||||
resource_publications_v17::NAME,
|
||||
resource_publications_v17::SOURCE_SHA256,
|
||||
16,
|
||||
),
|
||||
expand_descriptor(
|
||||
18,
|
||||
agent_resource_bindings_v18::NAME,
|
||||
agent_resource_bindings_v18::SOURCE_SHA256,
|
||||
17,
|
||||
),
|
||||
expand_descriptor(
|
||||
19,
|
||||
resource_security_revocations_v19::NAME,
|
||||
resource_security_revocations_v19::SOURCE_SHA256,
|
||||
18,
|
||||
),
|
||||
expand_descriptor(
|
||||
20,
|
||||
resource_template_sources_v20::NAME,
|
||||
resource_template_sources_v20::SOURCE_SHA256,
|
||||
19,
|
||||
),
|
||||
expand_descriptor(21, prompts_v21::NAME, prompts_v21::SOURCE_SHA256, 20),
|
||||
expand_descriptor(
|
||||
22,
|
||||
prompt_publications_v22::NAME,
|
||||
prompt_publications_v22::SOURCE_SHA256,
|
||||
21,
|
||||
),
|
||||
expand_descriptor(
|
||||
23,
|
||||
prompt_dependencies_v23::NAME,
|
||||
prompt_dependencies_v23::SOURCE_SHA256,
|
||||
22,
|
||||
),
|
||||
]
|
||||
}
|
||||
pub fn validate_sequence() -> Result<(), MigrationError> {
|
||||
@@ -407,6 +464,31 @@ impl MigrationAuthority {
|
||||
if from < 15 {
|
||||
onboarding_import_selection_v15::apply(&mut transaction, &Self::sequence()[14]).await?;
|
||||
}
|
||||
if from < 16 {
|
||||
resource_drafts_v16::apply(&mut transaction, &Self::sequence()[15]).await?;
|
||||
}
|
||||
if from < 17 {
|
||||
resource_publications_v17::apply(&mut transaction, &Self::sequence()[16]).await?;
|
||||
}
|
||||
if from < 18 {
|
||||
agent_resource_bindings_v18::apply(&mut transaction, &Self::sequence()[17]).await?;
|
||||
}
|
||||
if from < 19 {
|
||||
resource_security_revocations_v19::apply(&mut transaction, &Self::sequence()[18])
|
||||
.await?;
|
||||
}
|
||||
if from < 20 {
|
||||
resource_template_sources_v20::apply(&mut transaction, &Self::sequence()[19]).await?;
|
||||
}
|
||||
if from < 21 {
|
||||
prompts_v21::apply(&mut transaction, &Self::sequence()[20]).await?;
|
||||
}
|
||||
if from < 22 {
|
||||
prompt_publications_v22::apply(&mut transaction, &Self::sequence()[21]).await?;
|
||||
}
|
||||
if from < 23 {
|
||||
prompt_dependencies_v23::apply(&mut transaction, &Self::sequence()[22]).await?;
|
||||
}
|
||||
match inspect(&mut transaction).await? {
|
||||
MigrationPreflight::Current {
|
||||
version: CURRENT_VERSION,
|
||||
@@ -430,407 +512,6 @@ impl MigrationAuthority {
|
||||
})
|
||||
}
|
||||
}
|
||||
async fn inspect(connection: &mut PgConnection) -> Result<MigrationPreflight, MigrationError> {
|
||||
let core_exists = relation_exists(connection, "__crank_core_migrations").await?;
|
||||
let canonical_exists = relation_exists(connection, "__crank_migrations").await?;
|
||||
if !core_exists {
|
||||
let mut owned_exists = canonical_exists;
|
||||
for relation in OWNED_RELATIONS {
|
||||
owned_exists |= relation_exists(connection, relation).await?;
|
||||
}
|
||||
if owned_exists {
|
||||
if is_ledgerless_legacy_baseline(connection, canonical_exists).await? {
|
||||
return Ok(MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: CURRENT_VERSION,
|
||||
});
|
||||
}
|
||||
return Err(MigrationError::new(
|
||||
"partial_sequence",
|
||||
"preflight.core_missing",
|
||||
None,
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
inspect_optional_legacy(connection).await?;
|
||||
return Ok(MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: CURRENT_VERSION,
|
||||
});
|
||||
}
|
||||
validate_core_ledger(connection).await?;
|
||||
validate_required_relations(connection, owned_relations::BASELINE, 1).await?;
|
||||
inspect_optional_legacy(connection).await?;
|
||||
if !canonical_exists {
|
||||
return Ok(MigrationPreflight::MigrationRequired {
|
||||
current: 1,
|
||||
target: CURRENT_VERSION,
|
||||
});
|
||||
}
|
||||
let descriptors = MigrationAuthority::sequence();
|
||||
let rows = query("select version, name, checksum, phase, compatibility from __crank_migrations order by version limit 1025")
|
||||
.fetch_all(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
|
||||
if rows.is_empty() {
|
||||
return Err(MigrationError::new(
|
||||
"partial_sequence",
|
||||
"preflight.canonical",
|
||||
None,
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
for (index, row) in rows.iter().enumerate() {
|
||||
let version = row
|
||||
.try_get::<i64, _>("version")
|
||||
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
|
||||
if version > CURRENT_VERSION {
|
||||
return Err(MigrationError::new(
|
||||
"future_version",
|
||||
"preflight.canonical",
|
||||
Some(version),
|
||||
"install_matching_application",
|
||||
));
|
||||
}
|
||||
let Some(expected) = descriptors.get(index) else {
|
||||
return Err(MigrationError::new(
|
||||
"future_version",
|
||||
"preflight.canonical",
|
||||
Some(version),
|
||||
"install_matching_application",
|
||||
));
|
||||
};
|
||||
if version != expected.version {
|
||||
return Err(MigrationError::new(
|
||||
"partial_sequence",
|
||||
"preflight.canonical",
|
||||
Some(version),
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
let checksum = row
|
||||
.try_get::<String, _>("checksum")
|
||||
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
|
||||
if checksum != expected.checksum {
|
||||
return Err(MigrationError::new(
|
||||
"checksum_mismatch",
|
||||
"preflight.canonical",
|
||||
Some(version),
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
let name = row
|
||||
.try_get::<String, _>("name")
|
||||
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
|
||||
let phase = row
|
||||
.try_get::<String, _>("phase")
|
||||
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
|
||||
let compatibility = row
|
||||
.try_get::<String, _>("compatibility")
|
||||
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
|
||||
if name != expected.name
|
||||
|| phase != expected.phase
|
||||
|| compatibility != expected.compatibility
|
||||
{
|
||||
return Err(MigrationError::new(
|
||||
"checksum_mismatch",
|
||||
"preflight.metadata",
|
||||
Some(version),
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
}
|
||||
let current = rows
|
||||
.last()
|
||||
.and_then(|row| row.try_get::<i64, _>("version").ok())
|
||||
.ok_or_else(|| MigrationError::storage("preflight.canonical"))?;
|
||||
if rows.len() != usize::try_from(current).unwrap_or_default() {
|
||||
return Err(MigrationError::new(
|
||||
"partial_sequence",
|
||||
"preflight.canonical",
|
||||
Some(current),
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
validate_schema_fingerprint(connection, current).await?;
|
||||
if current < CURRENT_VERSION {
|
||||
Ok(MigrationPreflight::MigrationRequired {
|
||||
current,
|
||||
target: CURRENT_VERSION,
|
||||
})
|
||||
} else {
|
||||
validate_required_relations(connection, owned_relations::CONSOLIDATION, CURRENT_VERSION)
|
||||
.await?;
|
||||
validate_required_relations(
|
||||
connection,
|
||||
owned_relations::ONBOARDING_PRODUCT_EVENTS,
|
||||
CURRENT_VERSION,
|
||||
)
|
||||
.await?;
|
||||
validate_required_relations(
|
||||
connection,
|
||||
owned_relations::ARTIFACT_METADATA,
|
||||
CURRENT_VERSION,
|
||||
)
|
||||
.await?;
|
||||
validate_required_relations(connection, owned_relations::IMPORT_PLAN, CURRENT_VERSION)
|
||||
.await?;
|
||||
validate_required_relations(
|
||||
connection,
|
||||
owned_relations::ONBOARDING_IMPORT_SELECTION,
|
||||
CURRENT_VERSION,
|
||||
)
|
||||
.await?;
|
||||
validate_schema_fingerprint(connection, CURRENT_VERSION).await?;
|
||||
validate_legacy_audit(connection).await?;
|
||||
Ok(MigrationPreflight::Current { version: current })
|
||||
}
|
||||
}
|
||||
async fn is_ledgerless_legacy_baseline(
|
||||
connection: &mut PgConnection,
|
||||
canonical_exists: bool,
|
||||
) -> Result<bool, MigrationError> {
|
||||
if canonical_exists {
|
||||
return Ok(false);
|
||||
}
|
||||
for relation in [
|
||||
"__crank_migration_legacy_audit",
|
||||
"master_key_identities",
|
||||
"master_key_rotations",
|
||||
"admin_bootstrap_contracts",
|
||||
"admin_login_backoff",
|
||||
"admin_security_audit_events",
|
||||
"product_events",
|
||||
"product_event_daily_rollups",
|
||||
"onboarding_selections",
|
||||
"onboarding_import_selections",
|
||||
"artifact_blobs",
|
||||
"artifact_sources",
|
||||
] {
|
||||
if relation_exists(connection, relation).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
for relation in owned_relations::BASELINE {
|
||||
if !relation_exists(connection, relation).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
validate_required_relations(connection, owned_relations::BASELINE, 1).await?;
|
||||
validate_ledgerless_baseline_fingerprint(connection).await?;
|
||||
let mcp_ledger = relation_exists(connection, "__crank_mcp_migrations").await?;
|
||||
if mcp_ledger {
|
||||
return Ok(false);
|
||||
}
|
||||
let mcp_sessions = relation_exists(connection, "mcp_transport_sessions").await?;
|
||||
let extension_ledger = relation_exists(connection, "__crank_ext_migrations").await?;
|
||||
validate_ledgerless_optional_fingerprints(connection, mcp_sessions, extension_ledger).await?;
|
||||
inspect_optional_legacy_for_ledgerless_baseline(connection).await?;
|
||||
Ok(true)
|
||||
}
|
||||
async fn validate_core_ledger(connection: &mut PgConnection) -> Result<(), MigrationError> {
|
||||
let rows = query("select version, description, checksum from __crank_core_migrations order by version limit 2")
|
||||
.fetch_all(connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.core"))?;
|
||||
if rows.len() != 1 {
|
||||
return Err(MigrationError::new(
|
||||
"partial_sequence",
|
||||
"preflight.core_cardinality",
|
||||
None,
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
let version = rows[0]
|
||||
.try_get::<i32, _>("version")
|
||||
.map_err(|_| MigrationError::storage("preflight.core"))?;
|
||||
let checksum = rows[0]
|
||||
.try_get::<String, _>("checksum")
|
||||
.map_err(|_| MigrationError::storage("preflight.core"))?;
|
||||
let description = rows[0]
|
||||
.try_get::<String, _>("description")
|
||||
.map_err(|_| MigrationError::storage("preflight.core"))?;
|
||||
if version != BASELINE_VERSION
|
||||
|| description != "community baseline"
|
||||
|| checksum != BASELINE_CHECKSUM
|
||||
{
|
||||
return Err(MigrationError::new(
|
||||
"checksum_mismatch",
|
||||
"preflight.core",
|
||||
Some(i64::from(version)),
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
async fn inspect_optional_legacy(connection: &mut PgConnection) -> Result<(), MigrationError> {
|
||||
inspect_optional_legacy_with_policy(connection, false).await
|
||||
}
|
||||
async fn inspect_optional_legacy_for_ledgerless_baseline(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<(), MigrationError> {
|
||||
inspect_optional_legacy_with_policy(connection, true).await
|
||||
}
|
||||
async fn inspect_optional_legacy_with_policy(
|
||||
connection: &mut PgConnection,
|
||||
allow_sessions_without_ledger: bool,
|
||||
) -> Result<(), MigrationError> {
|
||||
let mcp_ledger = relation_exists(connection, "__crank_mcp_migrations").await?;
|
||||
let mcp_sessions = relation_exists(connection, "mcp_transport_sessions").await?;
|
||||
if mcp_ledger != mcp_sessions && !(allow_sessions_without_ledger && !mcp_ledger && mcp_sessions)
|
||||
{
|
||||
return Err(MigrationError::new(
|
||||
"legacy_conflict",
|
||||
"preflight.legacy_mcp",
|
||||
None,
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
if mcp_ledger {
|
||||
let rows =
|
||||
query("select version, checksum from __crank_mcp_migrations order by version limit 2")
|
||||
.fetch_all(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_mcp"))?;
|
||||
if rows.len() != 1
|
||||
|| rows[0].try_get::<i32, _>("version").ok() != Some(1)
|
||||
|| rows[0].try_get::<String, _>("checksum").ok().as_deref()
|
||||
!= Some("mcp-transport-sessions-v1")
|
||||
{
|
||||
return Err(MigrationError::new(
|
||||
"legacy_conflict",
|
||||
"preflight.legacy_mcp",
|
||||
None,
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
}
|
||||
if relation_exists(connection, "__crank_ext_migrations").await? {
|
||||
let count = query("select count(*)::bigint as count from __crank_ext_migrations")
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?
|
||||
.try_get::<i64, _>("count")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
|
||||
if count > 1_000 {
|
||||
return Err(MigrationError::new(
|
||||
"legacy_conflict",
|
||||
"preflight.legacy_extension",
|
||||
None,
|
||||
"contact_operator",
|
||||
));
|
||||
}
|
||||
if count > 0 {
|
||||
let checksum_column = query(
|
||||
"select exists (
|
||||
select 1 from information_schema.columns
|
||||
where table_schema = current_schema()
|
||||
and table_name = '__crank_ext_migrations'
|
||||
and column_name = 'checksum'
|
||||
) as present",
|
||||
)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?
|
||||
.try_get::<bool, _>("present")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
|
||||
if !checksum_column {
|
||||
return Err(MigrationError::new(
|
||||
"legacy_conflict",
|
||||
"preflight.legacy_extension",
|
||||
None,
|
||||
"contact_operator",
|
||||
));
|
||||
}
|
||||
let rows = query(
|
||||
"select extension_name, version, checksum
|
||||
from __crank_ext_migrations
|
||||
order by extension_name, version
|
||||
limit 1001",
|
||||
)
|
||||
.fetch_all(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
|
||||
for row in rows {
|
||||
let name = row
|
||||
.try_get::<String, _>("extension_name")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
|
||||
let version = row
|
||||
.try_get::<i32, _>("version")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
|
||||
let checksum = row
|
||||
.try_get::<Option<String>, _>("checksum")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
|
||||
let registered = MigrationAuthority::registered_extension_migrations()
|
||||
.iter()
|
||||
.any(|(registered_name, descriptor)| {
|
||||
*registered_name == name
|
||||
&& descriptor.version == u32::try_from(version).unwrap_or_default()
|
||||
&& checksum.as_deref() == Some(descriptor.checksum)
|
||||
});
|
||||
if !registered {
|
||||
return Err(MigrationError::new(
|
||||
"legacy_conflict",
|
||||
"preflight.legacy_extension",
|
||||
Some(i64::from(version)),
|
||||
"contact_operator",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
async fn validate_legacy_audit(connection: &mut PgConnection) -> Result<(), MigrationError> {
|
||||
let rows = query(
|
||||
"select source, source_version, source_checksum
|
||||
from __crank_migration_legacy_audit
|
||||
order by source, source_version
|
||||
limit 1002",
|
||||
)
|
||||
.fetch_all(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
|
||||
if rows.len() > 1001 {
|
||||
return Err(MigrationError::new(
|
||||
"legacy_conflict",
|
||||
"preflight.legacy_audit",
|
||||
None,
|
||||
"contact_operator",
|
||||
));
|
||||
}
|
||||
for row in rows {
|
||||
let source = row
|
||||
.try_get::<String, _>("source")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
|
||||
let version = row
|
||||
.try_get::<i64, _>("source_version")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
|
||||
let checksum = row
|
||||
.try_get::<String, _>("source_checksum")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
|
||||
let valid = (source == "core" && version == 1 && checksum == BASELINE_CHECKSUM)
|
||||
|| (source == "mcp-session" && version == 1 && checksum == "mcp-transport-sessions-v1")
|
||||
|| source.strip_prefix("extension:").is_some_and(|name| {
|
||||
MigrationAuthority::registered_extension_migrations()
|
||||
.iter()
|
||||
.any(|(registered_name, descriptor)| {
|
||||
*registered_name == name
|
||||
&& i64::from(descriptor.version) == version
|
||||
&& descriptor.checksum == checksum
|
||||
})
|
||||
});
|
||||
if !valid {
|
||||
return Err(MigrationError::new(
|
||||
"legacy_conflict",
|
||||
"preflight.legacy_audit",
|
||||
Some(version),
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
async fn create_core_ledger(
|
||||
transaction: &mut Transaction<'_, sqlx::Postgres>,
|
||||
) -> Result<(), MigrationError> {
|
||||
|
||||
@@ -133,6 +133,13 @@ pub(super) fn validate_descriptors(
|
||||
|| sha256_hex(import_plan_v14::SOURCE.as_bytes()) != import_plan_v14::SOURCE_SHA256
|
||||
|| sha256_hex(onboarding_import_selection_v15::SOURCE.as_bytes())
|
||||
!= onboarding_import_selection_v15::SOURCE_SHA256
|
||||
|| sha256_hex(resource_drafts_v16::SOURCE.as_bytes()) != resource_drafts_v16::SOURCE_SHA256
|
||||
|| sha256_hex(resource_publications_v17::SOURCE.as_bytes())
|
||||
!= resource_publications_v17::SOURCE_SHA256
|
||||
|| sha256_hex(agent_resource_bindings_v18::SOURCE.as_bytes())
|
||||
!= agent_resource_bindings_v18::SOURCE_SHA256
|
||||
|| sha256_hex(resource_security_revocations_v19::SOURCE.as_bytes())
|
||||
!= resource_security_revocations_v19::SOURCE_SHA256
|
||||
{
|
||||
return Err(MigrationError::new(
|
||||
"invalid_contract",
|
||||
|
||||
@@ -0,0 +1,409 @@
|
||||
//! Preflight/legacy-state inspection (вынесено из `authority.rs`, чтобы файл
|
||||
//! оставался в пределах rust-code-health); поведение не меняется.
|
||||
|
||||
use super::*;
|
||||
|
||||
pub(super) async fn inspect(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<MigrationPreflight, MigrationError> {
|
||||
let core_exists = relation_exists(connection, "__crank_core_migrations").await?;
|
||||
let canonical_exists = relation_exists(connection, "__crank_migrations").await?;
|
||||
if !core_exists {
|
||||
let mut owned_exists = canonical_exists;
|
||||
for relation in OWNED_RELATIONS {
|
||||
owned_exists |= relation_exists(connection, relation).await?;
|
||||
}
|
||||
if owned_exists {
|
||||
if is_ledgerless_legacy_baseline(connection, canonical_exists).await? {
|
||||
return Ok(MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: CURRENT_VERSION,
|
||||
});
|
||||
}
|
||||
return Err(MigrationError::new(
|
||||
"partial_sequence",
|
||||
"preflight.core_missing",
|
||||
None,
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
inspect_optional_legacy(connection).await?;
|
||||
return Ok(MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: CURRENT_VERSION,
|
||||
});
|
||||
}
|
||||
validate_core_ledger(connection).await?;
|
||||
validate_required_relations(connection, owned_relations::BASELINE, 1).await?;
|
||||
inspect_optional_legacy(connection).await?;
|
||||
if !canonical_exists {
|
||||
return Ok(MigrationPreflight::MigrationRequired {
|
||||
current: 1,
|
||||
target: CURRENT_VERSION,
|
||||
});
|
||||
}
|
||||
let descriptors = MigrationAuthority::sequence();
|
||||
let rows = query("select version, name, checksum, phase, compatibility from __crank_migrations order by version limit 1025")
|
||||
.fetch_all(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
|
||||
if rows.is_empty() {
|
||||
return Err(MigrationError::new(
|
||||
"partial_sequence",
|
||||
"preflight.canonical",
|
||||
None,
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
for (index, row) in rows.iter().enumerate() {
|
||||
let version = row
|
||||
.try_get::<i64, _>("version")
|
||||
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
|
||||
if version > CURRENT_VERSION {
|
||||
return Err(MigrationError::new(
|
||||
"future_version",
|
||||
"preflight.canonical",
|
||||
Some(version),
|
||||
"install_matching_application",
|
||||
));
|
||||
}
|
||||
let Some(expected) = descriptors.get(index) else {
|
||||
return Err(MigrationError::new(
|
||||
"future_version",
|
||||
"preflight.canonical",
|
||||
Some(version),
|
||||
"install_matching_application",
|
||||
));
|
||||
};
|
||||
if version != expected.version {
|
||||
return Err(MigrationError::new(
|
||||
"partial_sequence",
|
||||
"preflight.canonical",
|
||||
Some(version),
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
let checksum = row
|
||||
.try_get::<String, _>("checksum")
|
||||
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
|
||||
if checksum != expected.checksum {
|
||||
return Err(MigrationError::new(
|
||||
"checksum_mismatch",
|
||||
"preflight.canonical",
|
||||
Some(version),
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
let name = row
|
||||
.try_get::<String, _>("name")
|
||||
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
|
||||
let phase = row
|
||||
.try_get::<String, _>("phase")
|
||||
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
|
||||
let compatibility = row
|
||||
.try_get::<String, _>("compatibility")
|
||||
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
|
||||
if name != expected.name
|
||||
|| phase != expected.phase
|
||||
|| compatibility != expected.compatibility
|
||||
{
|
||||
return Err(MigrationError::new(
|
||||
"checksum_mismatch",
|
||||
"preflight.metadata",
|
||||
Some(version),
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
}
|
||||
let current = rows
|
||||
.last()
|
||||
.and_then(|row| row.try_get::<i64, _>("version").ok())
|
||||
.ok_or_else(|| MigrationError::storage("preflight.canonical"))?;
|
||||
if rows.len() != usize::try_from(current).unwrap_or_default() {
|
||||
return Err(MigrationError::new(
|
||||
"partial_sequence",
|
||||
"preflight.canonical",
|
||||
Some(current),
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
validate_schema_fingerprint(connection, current).await?;
|
||||
if current < CURRENT_VERSION {
|
||||
Ok(MigrationPreflight::MigrationRequired {
|
||||
current,
|
||||
target: CURRENT_VERSION,
|
||||
})
|
||||
} else {
|
||||
for relations in [
|
||||
owned_relations::CONSOLIDATION,
|
||||
owned_relations::ONBOARDING_PRODUCT_EVENTS,
|
||||
owned_relations::ARTIFACT_METADATA,
|
||||
owned_relations::IMPORT_PLAN,
|
||||
owned_relations::ONBOARDING_IMPORT_SELECTION,
|
||||
owned_relations::RESOURCE_DRAFTS,
|
||||
owned_relations::RESOURCE_PUBLICATIONS,
|
||||
owned_relations::AGENT_RESOURCE_BINDINGS,
|
||||
owned_relations::RESOURCE_SECURITY_REVOCATIONS,
|
||||
owned_relations::RESOURCE_TEMPLATE_SOURCES,
|
||||
owned_relations::PROMPTS,
|
||||
owned_relations::PROMPT_PUBLICATIONS,
|
||||
owned_relations::PROMPT_DEPENDENCIES,
|
||||
] {
|
||||
validate_required_relations(connection, relations, CURRENT_VERSION).await?;
|
||||
}
|
||||
validate_schema_fingerprint(connection, CURRENT_VERSION).await?;
|
||||
validate_legacy_audit(connection).await?;
|
||||
Ok(MigrationPreflight::Current { version: current })
|
||||
}
|
||||
}
|
||||
pub(super) async fn is_ledgerless_legacy_baseline(
|
||||
connection: &mut PgConnection,
|
||||
canonical_exists: bool,
|
||||
) -> Result<bool, MigrationError> {
|
||||
if canonical_exists {
|
||||
return Ok(false);
|
||||
}
|
||||
for relation in [
|
||||
"__crank_migration_legacy_audit",
|
||||
"master_key_identities",
|
||||
"master_key_rotations",
|
||||
"admin_bootstrap_contracts",
|
||||
"admin_login_backoff",
|
||||
"admin_security_audit_events",
|
||||
"product_events",
|
||||
"product_event_daily_rollups",
|
||||
"onboarding_selections",
|
||||
"onboarding_import_selections",
|
||||
"artifact_blobs",
|
||||
"artifact_sources",
|
||||
] {
|
||||
if relation_exists(connection, relation).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
for relation in owned_relations::BASELINE {
|
||||
if !relation_exists(connection, relation).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
validate_required_relations(connection, owned_relations::BASELINE, 1).await?;
|
||||
validate_ledgerless_baseline_fingerprint(connection).await?;
|
||||
let mcp_ledger = relation_exists(connection, "__crank_mcp_migrations").await?;
|
||||
if mcp_ledger {
|
||||
return Ok(false);
|
||||
}
|
||||
let mcp_sessions = relation_exists(connection, "mcp_transport_sessions").await?;
|
||||
let extension_ledger = relation_exists(connection, "__crank_ext_migrations").await?;
|
||||
validate_ledgerless_optional_fingerprints(connection, mcp_sessions, extension_ledger).await?;
|
||||
inspect_optional_legacy_for_ledgerless_baseline(connection).await?;
|
||||
Ok(true)
|
||||
}
|
||||
pub(super) async fn validate_core_ledger(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<(), MigrationError> {
|
||||
let rows = query("select version, description, checksum from __crank_core_migrations order by version limit 2")
|
||||
.fetch_all(connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.core"))?;
|
||||
if rows.len() != 1 {
|
||||
return Err(MigrationError::new(
|
||||
"partial_sequence",
|
||||
"preflight.core_cardinality",
|
||||
None,
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
let version = rows[0]
|
||||
.try_get::<i32, _>("version")
|
||||
.map_err(|_| MigrationError::storage("preflight.core"))?;
|
||||
let checksum = rows[0]
|
||||
.try_get::<String, _>("checksum")
|
||||
.map_err(|_| MigrationError::storage("preflight.core"))?;
|
||||
let description = rows[0]
|
||||
.try_get::<String, _>("description")
|
||||
.map_err(|_| MigrationError::storage("preflight.core"))?;
|
||||
if version != BASELINE_VERSION
|
||||
|| description != "community baseline"
|
||||
|| checksum != BASELINE_CHECKSUM
|
||||
{
|
||||
return Err(MigrationError::new(
|
||||
"checksum_mismatch",
|
||||
"preflight.core",
|
||||
Some(i64::from(version)),
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(super) async fn inspect_optional_legacy(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<(), MigrationError> {
|
||||
inspect_optional_legacy_with_policy(connection, false).await
|
||||
}
|
||||
pub(super) async fn inspect_optional_legacy_for_ledgerless_baseline(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<(), MigrationError> {
|
||||
inspect_optional_legacy_with_policy(connection, true).await
|
||||
}
|
||||
pub(super) async fn inspect_optional_legacy_with_policy(
|
||||
connection: &mut PgConnection,
|
||||
allow_sessions_without_ledger: bool,
|
||||
) -> Result<(), MigrationError> {
|
||||
let mcp_ledger = relation_exists(connection, "__crank_mcp_migrations").await?;
|
||||
let mcp_sessions = relation_exists(connection, "mcp_transport_sessions").await?;
|
||||
if mcp_ledger != mcp_sessions && !(allow_sessions_without_ledger && !mcp_ledger && mcp_sessions)
|
||||
{
|
||||
return Err(MigrationError::new(
|
||||
"legacy_conflict",
|
||||
"preflight.legacy_mcp",
|
||||
None,
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
if mcp_ledger {
|
||||
let rows =
|
||||
query("select version, checksum from __crank_mcp_migrations order by version limit 2")
|
||||
.fetch_all(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_mcp"))?;
|
||||
if rows.len() != 1
|
||||
|| rows[0].try_get::<i32, _>("version").ok() != Some(1)
|
||||
|| rows[0].try_get::<String, _>("checksum").ok().as_deref()
|
||||
!= Some("mcp-transport-sessions-v1")
|
||||
{
|
||||
return Err(MigrationError::new(
|
||||
"legacy_conflict",
|
||||
"preflight.legacy_mcp",
|
||||
None,
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
}
|
||||
if relation_exists(connection, "__crank_ext_migrations").await? {
|
||||
let count = query("select count(*)::bigint as count from __crank_ext_migrations")
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?
|
||||
.try_get::<i64, _>("count")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
|
||||
if count > 1_000 {
|
||||
return Err(MigrationError::new(
|
||||
"legacy_conflict",
|
||||
"preflight.legacy_extension",
|
||||
None,
|
||||
"contact_operator",
|
||||
));
|
||||
}
|
||||
if count > 0 {
|
||||
let checksum_column = query(
|
||||
"select exists (
|
||||
select 1 from information_schema.columns
|
||||
where table_schema = current_schema()
|
||||
and table_name = '__crank_ext_migrations'
|
||||
and column_name = 'checksum'
|
||||
) as present",
|
||||
)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?
|
||||
.try_get::<bool, _>("present")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
|
||||
if !checksum_column {
|
||||
return Err(MigrationError::new(
|
||||
"legacy_conflict",
|
||||
"preflight.legacy_extension",
|
||||
None,
|
||||
"contact_operator",
|
||||
));
|
||||
}
|
||||
let rows = query(
|
||||
"select extension_name, version, checksum
|
||||
from __crank_ext_migrations
|
||||
order by extension_name, version
|
||||
limit 1001",
|
||||
)
|
||||
.fetch_all(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
|
||||
for row in rows {
|
||||
let name = row
|
||||
.try_get::<String, _>("extension_name")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
|
||||
let version = row
|
||||
.try_get::<i32, _>("version")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
|
||||
let checksum = row
|
||||
.try_get::<Option<String>, _>("checksum")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
|
||||
let registered = MigrationAuthority::registered_extension_migrations()
|
||||
.iter()
|
||||
.any(|(registered_name, descriptor)| {
|
||||
*registered_name == name
|
||||
&& descriptor.version == u32::try_from(version).unwrap_or_default()
|
||||
&& checksum.as_deref() == Some(descriptor.checksum)
|
||||
});
|
||||
if !registered {
|
||||
return Err(MigrationError::new(
|
||||
"legacy_conflict",
|
||||
"preflight.legacy_extension",
|
||||
Some(i64::from(version)),
|
||||
"contact_operator",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(super) async fn validate_legacy_audit(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<(), MigrationError> {
|
||||
let rows = query(
|
||||
"select source, source_version, source_checksum
|
||||
from __crank_migration_legacy_audit
|
||||
order by source, source_version
|
||||
limit 1002",
|
||||
)
|
||||
.fetch_all(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
|
||||
if rows.len() > 1001 {
|
||||
return Err(MigrationError::new(
|
||||
"legacy_conflict",
|
||||
"preflight.legacy_audit",
|
||||
None,
|
||||
"contact_operator",
|
||||
));
|
||||
}
|
||||
for row in rows {
|
||||
let source = row
|
||||
.try_get::<String, _>("source")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
|
||||
let version = row
|
||||
.try_get::<i64, _>("source_version")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
|
||||
let checksum = row
|
||||
.try_get::<String, _>("source_checksum")
|
||||
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
|
||||
let valid = (source == "core" && version == 1 && checksum == BASELINE_CHECKSUM)
|
||||
|| (source == "mcp-session" && version == 1 && checksum == "mcp-transport-sessions-v1")
|
||||
|| source.strip_prefix("extension:").is_some_and(|name| {
|
||||
MigrationAuthority::registered_extension_migrations()
|
||||
.iter()
|
||||
.any(|(registered_name, descriptor)| {
|
||||
*registered_name == name
|
||||
&& i64::from(descriptor.version) == version
|
||||
&& descriptor.checksum == checksum
|
||||
})
|
||||
});
|
||||
if !valid {
|
||||
return Err(MigrationError::new(
|
||||
"legacy_conflict",
|
||||
"preflight.legacy_audit",
|
||||
Some(version),
|
||||
"restore_known_good_backup",
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -8,7 +8,9 @@ fn sequence_is_deterministic_and_append_only() {
|
||||
MigrationAuthority::validate_sequence().unwrap();
|
||||
assert_eq!(
|
||||
first.iter().map(|item| item.version).collect::<Vec<_>>(),
|
||||
vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
|
||||
vec![
|
||||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23
|
||||
]
|
||||
);
|
||||
assert_eq!(first[0].checksum, "crank-community-baseline-v1");
|
||||
assert_eq!(first[0].source_digest, BASELINE_SOURCE_SHA256);
|
||||
|
||||
@@ -33,6 +33,28 @@ pub(super) const ONBOARDING_PRODUCT_EVENTS: &[&str] = &[
|
||||
|
||||
pub(super) const ONBOARDING_IMPORT_SELECTION: &[&str] = &["onboarding_import_selections"];
|
||||
|
||||
pub(super) const RESOURCE_DRAFTS: &[&str] = &["resources", "resource_versions"];
|
||||
|
||||
pub(super) const RESOURCE_PUBLICATIONS: &[&str] = &["resource_publications"];
|
||||
|
||||
pub(super) const AGENT_RESOURCE_BINDINGS: &[&str] = &["agent_resource_bindings"];
|
||||
|
||||
pub(super) const RESOURCE_SECURITY_REVOCATIONS: &[&str] = &["resource_security_revocations"];
|
||||
|
||||
pub(super) const RESOURCE_TEMPLATE_SOURCES: &[&str] = &["resource_template_sources"];
|
||||
|
||||
pub(super) const PROMPTS: &[&str] = &[
|
||||
"prompts",
|
||||
"prompt_versions",
|
||||
"prompt_arguments",
|
||||
"prompt_messages",
|
||||
];
|
||||
|
||||
pub(super) const PROMPT_PUBLICATIONS: &[&str] = &["prompt_publications", "agent_prompt_bindings"];
|
||||
|
||||
pub(super) const PROMPT_DEPENDENCIES: &[&str] =
|
||||
&["prompt_dependencies", "prompt_message_resource_refs"];
|
||||
|
||||
pub(super) const ARTIFACT_METADATA: &[&str] = &["artifact_blobs", "artifact_sources"];
|
||||
|
||||
pub(super) const IMPORT_PLAN: &[&str] = &["import_plans", "import_plan_applications"];
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
use sqlx::{Postgres, Transaction, query};
|
||||
|
||||
use super::authority::{MigrationDescriptor, MigrationError};
|
||||
|
||||
pub(super) const NAME: &str = "prompt-dependencies-v23";
|
||||
pub(super) const SOURCE: &str = include_str!("prompt_dependencies_v23.sql");
|
||||
pub(super) const SOURCE_SHA256: &str =
|
||||
"15799d41e73021386bf1bae5952cbd34df93317cbce1a97fa8f99b3bd15cac64";
|
||||
|
||||
pub(super) async fn apply(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
descriptor: &MigrationDescriptor,
|
||||
) -> Result<(), MigrationError> {
|
||||
sqlx::raw_sql(SOURCE)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.prompt_dependencies_v23",
|
||||
Some(23),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
query(
|
||||
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
|
||||
values ($1, $2, $3, $4, $5)",
|
||||
)
|
||||
.bind(descriptor.version)
|
||||
.bind(descriptor.name)
|
||||
.bind(&descriptor.checksum)
|
||||
.bind(descriptor.phase)
|
||||
.bind(descriptor.compatibility)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.canonical_ledger",
|
||||
Some(23),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
-- V23: version-keyed pinned Prompt dependencies (Story 3.16, FR-18).
|
||||
--
|
||||
-- `prompt_dependencies` фиксирует точную опубликованную версию Resource, которую Draft/Prompt
|
||||
-- объявил в `dependencies`, вместе с разрешёнными на момент сохранения метаданными пина
|
||||
-- (digest/kind/mime/source_class/sensitivity). Строки version-keyed: правка зависимости
|
||||
-- требует нового Draft и новой публикации, поэтому уже опубликованная версия не меняется.
|
||||
--
|
||||
-- `prompt_message_resource_refs` хранит объявленные точки вставки: упорядоченный список
|
||||
-- индексов `dependencies` у конкретного сообщения. Отдельная таблица (а не колонка в
|
||||
-- `prompt_messages`) сохраняет уже принятую схему сообщений без изменения её отпечатка.
|
||||
--
|
||||
-- Guard-функция v22 (`crank_reject_published_prompt_version_mutation`) применяется к обеим
|
||||
-- новым таблицам тем же способом, что к arguments/messages: опубликованная версия immutable.
|
||||
|
||||
create table prompt_dependencies (
|
||||
workspace_id text not null,
|
||||
prompt_id text not null,
|
||||
version integer not null,
|
||||
dependency_position integer not null,
|
||||
resource_id text not null,
|
||||
resource_version integer not null,
|
||||
digest text not null,
|
||||
kind text not null,
|
||||
mime_type text not null,
|
||||
source_class text not null,
|
||||
sensitivity text not null,
|
||||
constraint prompt_dependencies_pkey primary key (workspace_id, prompt_id, version, dependency_position),
|
||||
constraint prompt_dependencies_version_fkey foreign key (workspace_id, prompt_id, version)
|
||||
references prompt_versions(workspace_id, prompt_id, version) on delete cascade,
|
||||
constraint prompt_dependencies_position_check check (dependency_position between 0 and 15),
|
||||
constraint prompt_dependencies_resource_version_check check (resource_version >= 1),
|
||||
constraint prompt_dependencies_kind_check check (kind in ('text', 'json', 'binary')),
|
||||
constraint prompt_dependencies_source_class_check check (source_class in ('static', 'dynamic')),
|
||||
constraint prompt_dependencies_sensitivity_check check (
|
||||
sensitivity in ('public', 'internal', 'secret')
|
||||
),
|
||||
constraint prompt_dependencies_digest_check check (octet_length(digest) between 1 and 256),
|
||||
constraint prompt_dependencies_mime_check check (octet_length(mime_type) between 1 and 255),
|
||||
constraint prompt_dependencies_resource_id_check check (
|
||||
octet_length(resource_id) between 1 and 160
|
||||
)
|
||||
);
|
||||
|
||||
create table prompt_message_resource_refs (
|
||||
workspace_id text not null,
|
||||
prompt_id text not null,
|
||||
version integer not null,
|
||||
message_position integer not null,
|
||||
ref_position integer not null,
|
||||
dependency_position integer not null,
|
||||
constraint prompt_message_resource_refs_pkey primary key (
|
||||
workspace_id, prompt_id, version, message_position, ref_position
|
||||
),
|
||||
constraint prompt_message_resource_refs_version_fkey
|
||||
foreign key (workspace_id, prompt_id, version)
|
||||
references prompt_versions(workspace_id, prompt_id, version) on delete cascade,
|
||||
constraint prompt_message_resource_refs_message_check check (
|
||||
message_position between 0 and 63
|
||||
),
|
||||
constraint prompt_message_resource_refs_ref_check check (ref_position between 0 and 15),
|
||||
constraint prompt_message_resource_refs_dependency_check check (
|
||||
dependency_position between 0 and 15
|
||||
)
|
||||
);
|
||||
|
||||
create trigger prompt_dependencies_immutable_guard
|
||||
before insert or update or delete on prompt_dependencies
|
||||
for each row
|
||||
execute function crank_reject_published_prompt_version_mutation();
|
||||
|
||||
create trigger prompt_message_resource_refs_immutable_guard
|
||||
before insert or update or delete on prompt_message_resource_refs
|
||||
for each row
|
||||
execute function crank_reject_published_prompt_version_mutation();
|
||||
@@ -0,0 +1,45 @@
|
||||
use sqlx::{Postgres, Transaction, query};
|
||||
|
||||
use super::authority::{MigrationDescriptor, MigrationError};
|
||||
|
||||
pub(super) const NAME: &str = "prompt-publications-v22";
|
||||
pub(super) const SOURCE: &str = include_str!("prompt_publications_v22.sql");
|
||||
pub(super) const SOURCE_SHA256: &str =
|
||||
"b330b248f164fc6f3635739668f5ea94dc48f0e84d18f0d3dfceb92ff6c445e7";
|
||||
|
||||
pub(super) async fn apply(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
descriptor: &MigrationDescriptor,
|
||||
) -> Result<(), MigrationError> {
|
||||
sqlx::raw_sql(SOURCE)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.prompt_publications_v22",
|
||||
Some(22),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
query(
|
||||
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
|
||||
values ($1, $2, $3, $4, $5)",
|
||||
)
|
||||
.bind(descriptor.version)
|
||||
.bind(descriptor.name)
|
||||
.bind(&descriptor.checksum)
|
||||
.bind(descriptor.phase)
|
||||
.bind(descriptor.compatibility)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.canonical_ledger",
|
||||
Some(22),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
-- V22: immutable Published Prompt Versions и typed exact Prompt bindings Agent
|
||||
-- (Story 3.13, FR-17).
|
||||
--
|
||||
-- `prompt_publications` фиксирует lifecycle-снимок публикации: точная версия,
|
||||
-- name/description/sensitivity на момент publish и `published_at`. Сама
|
||||
-- definition (arguments/messages) остаётся в version-keyed `prompt_arguments` и
|
||||
-- `prompt_messages`; поэтому снимок не дублирует байты, а отдельная guard-функция
|
||||
-- запрещает менять definition уже опубликованной версии. Archive — не revoke:
|
||||
-- immutable строки остаются.
|
||||
--
|
||||
-- `agent_prompt_bindings` — отдельная typed-таблица: строка адресует точную
|
||||
-- Published Prompt Version для точной версии Agent. Composite FK проверяет
|
||||
-- workspace на обоих концах, поэтому `latest`-версия и чужая публикация в
|
||||
-- binding попасть не могут.
|
||||
|
||||
alter table prompts
|
||||
add column latest_published_version integer,
|
||||
add constraint prompts_latest_published_version_check check (
|
||||
latest_published_version is null or latest_published_version >= 1
|
||||
);
|
||||
|
||||
create table prompt_publications (
|
||||
workspace_id text not null,
|
||||
prompt_id text not null,
|
||||
version integer not null,
|
||||
name text not null,
|
||||
description text not null,
|
||||
sensitivity text not null,
|
||||
published_at timestamptz not null,
|
||||
constraint prompt_publications_pkey primary key (workspace_id, prompt_id, version),
|
||||
constraint prompt_publications_version_check check (version >= 1),
|
||||
constraint prompt_publications_name_length_check check (
|
||||
octet_length(name) between 1 and 16384
|
||||
),
|
||||
constraint prompt_publications_description_length_check check (
|
||||
octet_length(description) between 1 and 16384
|
||||
),
|
||||
constraint prompt_publications_sensitivity_check check (
|
||||
sensitivity in ('public', 'internal', 'secret')
|
||||
),
|
||||
constraint prompt_publications_prompt_fkey
|
||||
foreign key (workspace_id, prompt_id)
|
||||
references prompts(workspace_id, prompt_id) on delete cascade,
|
||||
constraint prompt_publications_version_fkey
|
||||
foreign key (workspace_id, prompt_id, version)
|
||||
references prompt_versions(workspace_id, prompt_id, version)
|
||||
on delete cascade
|
||||
);
|
||||
|
||||
-- Опубликованная definition immutable: guard смотрит и OLD, и NEW ключ строки.
|
||||
-- Удаление допускается только вместе с owning prompt (cascade), потому что archive
|
||||
-- является lifecycle-состоянием, а не удалением снимка.
|
||||
create function crank_reject_published_prompt_version_mutation()
|
||||
returns trigger
|
||||
language plpgsql
|
||||
as $$
|
||||
declare
|
||||
published boolean;
|
||||
owner_present boolean;
|
||||
begin
|
||||
if tg_op in ('UPDATE', 'DELETE') then
|
||||
select exists (
|
||||
select 1 from prompt_publications
|
||||
where workspace_id = old.workspace_id
|
||||
and prompt_id = old.prompt_id
|
||||
and version = old.version
|
||||
), exists (
|
||||
select 1 from prompts
|
||||
where workspace_id = old.workspace_id and prompt_id = old.prompt_id
|
||||
)
|
||||
into published, owner_present;
|
||||
if published and owner_present then
|
||||
raise exception 'published Prompt version is immutable'
|
||||
using errcode = '23514';
|
||||
end if;
|
||||
end if;
|
||||
if tg_op in ('INSERT', 'UPDATE') then
|
||||
select exists (
|
||||
select 1 from prompt_publications
|
||||
where workspace_id = new.workspace_id
|
||||
and prompt_id = new.prompt_id
|
||||
and version = new.version
|
||||
) into published;
|
||||
if published then
|
||||
raise exception 'published Prompt version is immutable'
|
||||
using errcode = '23514';
|
||||
end if;
|
||||
end if;
|
||||
if tg_op = 'DELETE' then
|
||||
return old;
|
||||
end if;
|
||||
return new;
|
||||
end;
|
||||
$$;
|
||||
|
||||
create function crank_reject_prompt_publication_mutation()
|
||||
returns trigger
|
||||
language plpgsql
|
||||
as $$
|
||||
declare
|
||||
owner_present boolean;
|
||||
begin
|
||||
if tg_op = 'DELETE' then
|
||||
select exists (
|
||||
select 1 from prompts
|
||||
where workspace_id = old.workspace_id and prompt_id = old.prompt_id
|
||||
) into owner_present;
|
||||
if owner_present then
|
||||
raise exception 'published Prompt version is immutable'
|
||||
using errcode = '23514';
|
||||
end if;
|
||||
return old;
|
||||
end if;
|
||||
raise exception 'published Prompt version is immutable'
|
||||
using errcode = '23514';
|
||||
end;
|
||||
$$;
|
||||
|
||||
create trigger prompt_arguments_immutable_guard
|
||||
before insert or update or delete on prompt_arguments
|
||||
for each row
|
||||
execute function crank_reject_published_prompt_version_mutation();
|
||||
|
||||
create trigger prompt_messages_immutable_guard
|
||||
before insert or update or delete on prompt_messages
|
||||
for each row
|
||||
execute function crank_reject_published_prompt_version_mutation();
|
||||
|
||||
create trigger prompt_publications_immutable_guard
|
||||
before update or delete on prompt_publications
|
||||
for each row
|
||||
execute function crank_reject_prompt_publication_mutation();
|
||||
|
||||
create table agent_prompt_bindings (
|
||||
workspace_id text not null,
|
||||
agent_id text not null,
|
||||
agent_version integer not null,
|
||||
prompt_id text not null,
|
||||
prompt_version integer not null,
|
||||
constraint agent_prompt_bindings_agent_version_check check (agent_version >= 1),
|
||||
constraint agent_prompt_bindings_prompt_version_check check (prompt_version >= 1),
|
||||
primary key (agent_id, agent_version, prompt_id),
|
||||
constraint agent_prompt_bindings_agent_workspace_fkey
|
||||
foreign key (workspace_id, agent_id)
|
||||
references agents(workspace_id, id) on delete cascade,
|
||||
constraint agent_prompt_bindings_agent_version_fkey
|
||||
foreign key (agent_id, agent_version)
|
||||
references agent_versions(agent_id, version) on delete cascade,
|
||||
constraint agent_prompt_bindings_publication_fkey
|
||||
foreign key (workspace_id, prompt_id, prompt_version)
|
||||
references prompt_publications(workspace_id, prompt_id, version)
|
||||
on delete cascade
|
||||
);
|
||||
|
||||
create function crank_reject_published_agent_prompt_binding_mutation()
|
||||
returns trigger
|
||||
language plpgsql
|
||||
as $$
|
||||
declare
|
||||
bound_status text;
|
||||
begin
|
||||
if tg_op in ('UPDATE', 'DELETE') then
|
||||
select status
|
||||
into bound_status
|
||||
from agent_versions
|
||||
where agent_id = old.agent_id and version = old.agent_version;
|
||||
if bound_status = 'published' then
|
||||
raise exception 'published Agent Prompt bindings are immutable'
|
||||
using errcode = '23514';
|
||||
end if;
|
||||
end if;
|
||||
if tg_op in ('INSERT', 'UPDATE') then
|
||||
select status
|
||||
into bound_status
|
||||
from agent_versions
|
||||
where agent_id = new.agent_id and version = new.agent_version;
|
||||
if bound_status = 'published' then
|
||||
raise exception 'published Agent Prompt bindings are immutable'
|
||||
using errcode = '23514';
|
||||
end if;
|
||||
end if;
|
||||
if tg_op = 'DELETE' then
|
||||
return old;
|
||||
end if;
|
||||
return new;
|
||||
end;
|
||||
$$;
|
||||
|
||||
create trigger agent_prompt_bindings_immutable_guard
|
||||
before insert or update or delete on agent_prompt_bindings
|
||||
for each row
|
||||
execute function crank_reject_published_agent_prompt_binding_mutation();
|
||||
|
||||
create index agent_prompt_bindings_publication_idx
|
||||
on agent_prompt_bindings (workspace_id, prompt_id, prompt_version);
|
||||
@@ -0,0 +1,45 @@
|
||||
use sqlx::{Postgres, Transaction, query};
|
||||
|
||||
use super::authority::{MigrationDescriptor, MigrationError};
|
||||
|
||||
pub(super) const NAME: &str = "prompts-v21";
|
||||
pub(super) const SOURCE: &str = include_str!("prompts_v21.sql");
|
||||
pub(super) const SOURCE_SHA256: &str =
|
||||
"c62717f8eb87b249b7771c74517ce99baeaf2793bfd5fca5d15e8412112bc53e";
|
||||
|
||||
pub(super) async fn apply(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
descriptor: &MigrationDescriptor,
|
||||
) -> Result<(), MigrationError> {
|
||||
sqlx::raw_sql(SOURCE)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.prompts_v21",
|
||||
Some(21),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
query(
|
||||
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
|
||||
values ($1, $2, $3, $4, $5)",
|
||||
)
|
||||
.bind(descriptor.version)
|
||||
.bind(descriptor.name)
|
||||
.bind(&descriptor.checksum)
|
||||
.bind(descriptor.phase)
|
||||
.bind(descriptor.compatibility)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.canonical_ledger",
|
||||
Some(21),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
-- V21: typed Prompt Draft aggregate and ordered arguments/messages (Story 3.12).
|
||||
create table prompts (
|
||||
workspace_id text not null references workspaces(id) on delete cascade,
|
||||
prompt_id text not null,
|
||||
name text not null,
|
||||
description text not null,
|
||||
status text not null default 'draft',
|
||||
sensitivity text not null,
|
||||
current_draft_version integer not null default 1,
|
||||
created_at timestamptz not null,
|
||||
updated_at timestamptz not null,
|
||||
constraint prompts_pkey primary key (workspace_id, prompt_id),
|
||||
constraint prompts_id_check check (prompt_id ~ '^prm_[A-Za-z0-9_-]{1,128}$'),
|
||||
constraint prompts_name_length_check check (octet_length(name) between 1 and 16384),
|
||||
constraint prompts_description_length_check check (octet_length(description) between 1 and 16384),
|
||||
constraint prompts_status_check check (status in ('draft', 'published', 'archived')),
|
||||
constraint prompts_sensitivity_check check (sensitivity in ('public', 'internal', 'secret')),
|
||||
constraint prompts_draft_version_check check (current_draft_version >= 1)
|
||||
);
|
||||
|
||||
create table prompt_versions (
|
||||
workspace_id text not null,
|
||||
prompt_id text not null,
|
||||
version integer not null,
|
||||
created_at timestamptz not null,
|
||||
constraint prompt_versions_pkey primary key (workspace_id, prompt_id, version),
|
||||
constraint prompt_versions_prompt_fkey foreign key (workspace_id, prompt_id)
|
||||
references prompts(workspace_id, prompt_id) on delete cascade,
|
||||
constraint prompt_versions_version_check check (version >= 1)
|
||||
);
|
||||
|
||||
create table prompt_arguments (
|
||||
workspace_id text not null,
|
||||
prompt_id text not null,
|
||||
version integer not null,
|
||||
argument_name text not null,
|
||||
argument_type text not null,
|
||||
required boolean not null,
|
||||
default_value jsonb,
|
||||
enumeration jsonb,
|
||||
position integer not null,
|
||||
constraint prompt_arguments_pkey primary key (workspace_id, prompt_id, version, argument_name),
|
||||
constraint prompt_arguments_version_fkey foreign key (workspace_id, prompt_id, version)
|
||||
references prompt_versions(workspace_id, prompt_id, version) on delete cascade,
|
||||
constraint prompt_arguments_type_check check (argument_type in ('string', 'number', 'integer', 'boolean')),
|
||||
constraint prompt_arguments_name_check check (octet_length(argument_name) between 1 and 16384),
|
||||
constraint prompt_arguments_position_check check (position >= 0),
|
||||
constraint prompt_arguments_default_size_check check (default_value is null or octet_length(default_value::text) <= 16384),
|
||||
constraint prompt_arguments_enum_size_check check (
|
||||
enumeration is null or case
|
||||
when jsonb_typeof(enumeration) = 'array'
|
||||
then jsonb_array_length(enumeration) between 1 and 64
|
||||
else false
|
||||
end
|
||||
)
|
||||
);
|
||||
|
||||
create table prompt_messages (
|
||||
workspace_id text not null,
|
||||
prompt_id text not null,
|
||||
version integer not null,
|
||||
position integer not null,
|
||||
role text not null,
|
||||
content text not null,
|
||||
constraint prompt_messages_pkey primary key (workspace_id, prompt_id, version, position),
|
||||
constraint prompt_messages_version_fkey foreign key (workspace_id, prompt_id, version)
|
||||
references prompt_versions(workspace_id, prompt_id, version) on delete cascade,
|
||||
constraint prompt_messages_position_check check (position between 0 and 63),
|
||||
constraint prompt_messages_role_check check (role in ('system', 'user', 'assistant')),
|
||||
constraint prompt_messages_content_check check (octet_length(content) between 1 and 16384)
|
||||
);
|
||||
@@ -0,0 +1,45 @@
|
||||
use sqlx::{Postgres, Transaction, query};
|
||||
|
||||
use super::authority::{MigrationDescriptor, MigrationError};
|
||||
|
||||
pub(super) const NAME: &str = "resource-drafts-v16";
|
||||
pub(super) const SOURCE: &str = include_str!("resource_drafts_v16.sql");
|
||||
pub(super) const SOURCE_SHA256: &str =
|
||||
"0ed07dabd37f97e212923650b80278898c4e9519cee0cda4170f6b2b2a3d92d7";
|
||||
|
||||
pub(super) async fn apply(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
descriptor: &MigrationDescriptor,
|
||||
) -> Result<(), MigrationError> {
|
||||
sqlx::raw_sql(SOURCE)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.resource_drafts",
|
||||
Some(16),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
query(
|
||||
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
|
||||
values ($1, $2, $3, $4, $5)",
|
||||
)
|
||||
.bind(descriptor.version)
|
||||
.bind(descriptor.name)
|
||||
.bind(&descriptor.checksum)
|
||||
.bind(descriptor.phase)
|
||||
.bind(descriptor.compatibility)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.canonical_ledger",
|
||||
Some(16),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
-- V16: typed static Resource drafts (Story 3.6, D-15).
|
||||
--
|
||||
-- Байты не хранятся здесь: содержимое версии — это content-addressed blob
|
||||
-- (`artifact_blobs`) и owning-ссылка (`artifact_sources`), поэтому Resource
|
||||
-- участвует в существующем учёте владения и sweep-е (AD-10).
|
||||
-- Filesystem path, raw filename и mutable external reference намеренно
|
||||
-- отсутствуют (D-12).
|
||||
|
||||
create table resources (
|
||||
workspace_id text not null references workspaces(id) on delete cascade,
|
||||
resource_id text not null,
|
||||
uri text not null,
|
||||
name text not null,
|
||||
description text not null default '',
|
||||
status text not null default 'draft',
|
||||
kind text not null,
|
||||
current_draft_version integer not null,
|
||||
created_at timestamptz not null,
|
||||
updated_at timestamptz not null,
|
||||
constraint resources_resource_id_check check (resource_id ~ '^res_[A-Za-z0-9_-]{1,96}$'),
|
||||
constraint resources_uri_len_check check (octet_length(uri) between 10 and 200),
|
||||
constraint resources_name_len_check check (octet_length(name) between 1 and 64),
|
||||
constraint resources_description_len check (octet_length(description) <= 1024),
|
||||
constraint resources_status_check check (status in ('draft', 'published', 'archived')),
|
||||
constraint resources_kind_check check (kind in ('text', 'json', 'binary')),
|
||||
constraint resources_current_version_check check (current_draft_version >= 1),
|
||||
constraint resources_timestamps_check check (updated_at >= created_at),
|
||||
constraint resources_workspace_uri_unique unique (workspace_id, uri),
|
||||
constraint resources_workspace_name_unique unique (workspace_id, name),
|
||||
primary key (workspace_id, resource_id)
|
||||
);
|
||||
|
||||
create table resource_versions (
|
||||
workspace_id text not null,
|
||||
resource_id text not null,
|
||||
version integer not null,
|
||||
kind text not null,
|
||||
mime_type text not null,
|
||||
size_bytes bigint not null,
|
||||
digest text not null,
|
||||
sensitivity text not null,
|
||||
artifact_source_id text not null,
|
||||
created_at timestamptz not null,
|
||||
superseded_at timestamptz null,
|
||||
constraint resource_versions_version_check check (version >= 1),
|
||||
constraint resource_versions_kind_check check (kind in ('text', 'json', 'binary')),
|
||||
constraint resource_versions_mime_type_check check (
|
||||
octet_length(mime_type) between 3 and 255
|
||||
and mime_type ~ '^[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+$'
|
||||
),
|
||||
constraint resource_versions_size_check check (size_bytes between 1 and 262144),
|
||||
constraint resource_versions_digest_check check (digest ~ '^[0-9a-f]{64}$'),
|
||||
constraint resource_versions_sensitivity_check check (
|
||||
sensitivity in ('public', 'internal', 'secret')
|
||||
),
|
||||
constraint resource_versions_source_id_check check (
|
||||
artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$'
|
||||
),
|
||||
constraint resource_versions_supersede_check check (
|
||||
superseded_at is null or superseded_at >= created_at
|
||||
),
|
||||
primary key (workspace_id, resource_id, version),
|
||||
constraint resource_versions_resource_fkey foreign key (workspace_id, resource_id)
|
||||
references resources(workspace_id, resource_id) on delete cascade,
|
||||
constraint resource_versions_source_fkey foreign key (workspace_id, artifact_source_id)
|
||||
references artifact_sources(workspace_id, source_id)
|
||||
);
|
||||
|
||||
-- Ровно одна текущая черновая версия на Resource: пометка прежней версии
|
||||
-- обязана произойти до вставки новой (D-15 шаг 4), индекс не ослабляется.
|
||||
create unique index resource_versions_current_draft_unique
|
||||
on resource_versions (workspace_id, resource_id)
|
||||
where superseded_at is null;
|
||||
|
||||
create index resources_workspace_created_idx
|
||||
on resources (workspace_id, created_at, resource_id);
|
||||
@@ -0,0 +1,45 @@
|
||||
use sqlx::{Postgres, Transaction, query};
|
||||
|
||||
use super::authority::{MigrationDescriptor, MigrationError};
|
||||
|
||||
pub(super) const NAME: &str = "resource-publications-v17";
|
||||
pub(super) const SOURCE: &str = include_str!("resource_publications_v17.sql");
|
||||
pub(super) const SOURCE_SHA256: &str =
|
||||
"eaefc08d25ba5ab92775dd9263ced14d927e28b558444f83ea789f1f0023c092";
|
||||
|
||||
pub(super) async fn apply(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
descriptor: &MigrationDescriptor,
|
||||
) -> Result<(), MigrationError> {
|
||||
sqlx::raw_sql(SOURCE)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.resource_publications",
|
||||
Some(17),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
query(
|
||||
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
|
||||
values ($1, $2, $3, $4, $5)",
|
||||
)
|
||||
.bind(descriptor.version)
|
||||
.bind(descriptor.name)
|
||||
.bind(&descriptor.checksum)
|
||||
.bind(descriptor.phase)
|
||||
.bind(descriptor.compatibility)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.canonical_ledger",
|
||||
Some(17),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
-- V17: immutable Published Resource Versions (Story 3.7, FR-15/FR-16).
|
||||
--
|
||||
-- Строка публикации — снимок публичных metadata на момент publish. Байты не
|
||||
-- дублируются: отдельная owning-ссылка (`artifact_source_id`) указывает на тот же
|
||||
-- content-addressed blob, поэтому Draft update не может отсоединить published bytes.
|
||||
-- Filesystem path, raw upload filename и mutable external reference отсутствуют.
|
||||
--
|
||||
-- Закрытая таблица не является универсальным JSON blob: exact published version
|
||||
-- адресуется composite PK (workspace_id, resource_id, version) и FK на
|
||||
-- `resource_versions`.
|
||||
|
||||
create table resource_publications (
|
||||
workspace_id text not null,
|
||||
resource_id text not null,
|
||||
version integer not null,
|
||||
uri text not null,
|
||||
name text not null,
|
||||
description text not null default '',
|
||||
kind text not null,
|
||||
mime_type text not null,
|
||||
size_bytes bigint not null,
|
||||
digest text not null,
|
||||
sensitivity text not null,
|
||||
artifact_source_id text not null,
|
||||
published_at timestamptz not null,
|
||||
constraint resource_publications_version_check check (version >= 1),
|
||||
constraint resource_publications_uri_len_check check (
|
||||
octet_length(uri) between 10 and 200
|
||||
),
|
||||
constraint resource_publications_name_len_check check (
|
||||
octet_length(name) between 1 and 64
|
||||
),
|
||||
constraint resource_publications_description_len check (
|
||||
octet_length(description) <= 1024
|
||||
),
|
||||
constraint resource_publications_kind_check check (
|
||||
kind in ('text', 'json', 'binary')
|
||||
),
|
||||
constraint resource_publications_mime_type_check check (
|
||||
octet_length(mime_type) between 3 and 255
|
||||
and mime_type ~ '^[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+$'
|
||||
),
|
||||
constraint resource_publications_size_check check (
|
||||
size_bytes between 1 and 262144
|
||||
),
|
||||
constraint resource_publications_digest_check check (digest ~ '^[0-9a-f]{64}$'),
|
||||
constraint resource_publications_sensitivity_check check (
|
||||
sensitivity in ('public', 'internal', 'secret')
|
||||
),
|
||||
constraint resource_publications_source_id_check check (
|
||||
artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$'
|
||||
),
|
||||
primary key (workspace_id, resource_id, version),
|
||||
constraint resource_publications_resource_fkey
|
||||
foreign key (workspace_id, resource_id)
|
||||
references resources(workspace_id, resource_id) on delete cascade,
|
||||
constraint resource_publications_version_fkey
|
||||
foreign key (workspace_id, resource_id, version)
|
||||
references resource_versions(workspace_id, resource_id, version)
|
||||
on delete cascade,
|
||||
constraint resource_publications_source_fkey
|
||||
foreign key (workspace_id, artifact_source_id)
|
||||
references artifact_sources(workspace_id, source_id)
|
||||
);
|
||||
|
||||
create index resource_publications_workspace_uri_idx
|
||||
on resource_publications (workspace_id, uri, published_at desc);
|
||||
@@ -0,0 +1,45 @@
|
||||
use sqlx::{Postgres, Transaction, query};
|
||||
|
||||
use super::authority::{MigrationDescriptor, MigrationError};
|
||||
|
||||
pub(super) const NAME: &str = "resource-security-revocations-v19";
|
||||
pub(super) const SOURCE: &str = include_str!("resource_security_revocations_v19.sql");
|
||||
pub(super) const SOURCE_SHA256: &str =
|
||||
"e66493a4014af5cbf1ed7532ab7140ce773dc30b0995dea242b791f51dad5bc0";
|
||||
|
||||
pub(super) async fn apply(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
descriptor: &MigrationDescriptor,
|
||||
) -> Result<(), MigrationError> {
|
||||
sqlx::raw_sql(SOURCE)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.resource_security_revocations",
|
||||
Some(19),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
query(
|
||||
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
|
||||
values ($1, $2, $3, $4, $5)",
|
||||
)
|
||||
.bind(descriptor.version)
|
||||
.bind(descriptor.name)
|
||||
.bind(&descriptor.checksum)
|
||||
.bind(descriptor.phase)
|
||||
.bind(descriptor.compatibility)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.canonical_ledger",
|
||||
Some(19),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
-- V19: Resource-wide security revocation (Story 3.8, FR-15/FR-16).
|
||||
--
|
||||
-- Owner decision A (`t_6f76be08`): revoking a Resource denies every version of it
|
||||
-- in every Agent, including already published snapshots, and forbids new
|
||||
-- publications/bindings. The tombstone is also its own immutable transition
|
||||
-- record: one row per workspace/Resource, the first successful actor/time is
|
||||
-- never rewritten, and no UPDATE/DELETE/restore path exists in this slice.
|
||||
--
|
||||
-- Only the stable identity is stored. No content, URI, name, MIME, digest,
|
||||
-- reason or secret is duplicated here; archive and the immutable published
|
||||
-- snapshot bytes stay untouched.
|
||||
--
|
||||
-- The composite FK pins the tombstone to an existing Resource of the same
|
||||
-- workspace, and the actor FK to a real user without cascading deletion, so the
|
||||
-- audit row cannot outlive its referents or be detached by deleting a user.
|
||||
-- An empty table means the previous (unrevoked) behaviour, so old installations
|
||||
-- need no data migration.
|
||||
|
||||
create function crank_reject_resource_security_revocation_mutation()
|
||||
returns trigger
|
||||
language plpgsql
|
||||
as $$
|
||||
begin
|
||||
raise exception 'resource security revocations are immutable'
|
||||
using errcode = '23514';
|
||||
end;
|
||||
$$;
|
||||
|
||||
create table resource_security_revocations (
|
||||
workspace_id text not null,
|
||||
resource_id text not null,
|
||||
revoked_at timestamptz not null,
|
||||
actor_user_id text not null,
|
||||
request_id text not null,
|
||||
trace_id text not null,
|
||||
primary key (workspace_id, resource_id),
|
||||
constraint resource_security_revocations_resource_fkey
|
||||
foreign key (workspace_id, resource_id)
|
||||
references resources(workspace_id, resource_id) on delete restrict,
|
||||
constraint resource_security_revocations_actor_fkey
|
||||
foreign key (actor_user_id) references users(id) on delete restrict
|
||||
);
|
||||
|
||||
create trigger resource_security_revocations_immutable_guard
|
||||
before update or delete on resource_security_revocations
|
||||
for each row
|
||||
execute function crank_reject_resource_security_revocation_mutation();
|
||||
@@ -0,0 +1,45 @@
|
||||
use sqlx::{Postgres, Transaction, query};
|
||||
|
||||
use super::authority::{MigrationDescriptor, MigrationError};
|
||||
|
||||
pub(super) const NAME: &str = "resource-template-sources-v20";
|
||||
pub(super) const SOURCE: &str = include_str!("resource_template_sources_v20.sql");
|
||||
pub(super) const SOURCE_SHA256: &str =
|
||||
"1537f7267f4bb5317242f3c20d613dd9a5b4e5b01cec5c578949f431e91f7502";
|
||||
|
||||
pub(super) async fn apply(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
descriptor: &MigrationDescriptor,
|
||||
) -> Result<(), MigrationError> {
|
||||
sqlx::raw_sql(SOURCE)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.resource_template_sources",
|
||||
Some(20),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
query(
|
||||
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
|
||||
values ($1, $2, $3, $4, $5)",
|
||||
)
|
||||
.bind(descriptor.version)
|
||||
.bind(descriptor.name)
|
||||
.bind(&descriptor.checksum)
|
||||
.bind(descriptor.phase)
|
||||
.bind(descriptor.compatibility)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.canonical_ledger",
|
||||
Some(20),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
-- V20: byte-less REST-backed Resource template definitions (Story 3.10, FR-16).
|
||||
--
|
||||
-- Шаблон не имеет файла содержимого: определение живёт отдельной version-keyed
|
||||
-- строкой (`resource_template_sources`) рядом с версией, а не в artifact blob.
|
||||
-- Поэтому `source_kind` отделяет artifact-строки (прежние инварианты байт
|
||||
-- сохранены буквально) от template-строк (artifact_source_id null, size 0,
|
||||
-- digest = digest определения).
|
||||
--
|
||||
-- Publication snapshot остаётся неизменяемым: `resource_template_sources`
|
||||
-- insert-only (UPDATE запрещён trigger-ом), а published-версия адресует ту же
|
||||
-- version-keyed строку, поэтому правка Draft не меняет опубликованное определение.
|
||||
|
||||
alter table resource_versions
|
||||
add column source_kind text not null default 'artifact';
|
||||
|
||||
alter table resource_versions
|
||||
alter column artifact_source_id drop not null;
|
||||
|
||||
alter table resource_versions
|
||||
drop constraint resource_versions_size_check;
|
||||
|
||||
alter table resource_versions
|
||||
add constraint resource_versions_size_check check (
|
||||
(source_kind = 'artifact' and size_bytes between 1 and 262144)
|
||||
or (source_kind = 'template' and size_bytes = 0)
|
||||
);
|
||||
|
||||
alter table resource_versions
|
||||
drop constraint resource_versions_source_id_check;
|
||||
|
||||
alter table resource_versions
|
||||
add constraint resource_versions_source_id_check check (
|
||||
(
|
||||
source_kind = 'artifact'
|
||||
and artifact_source_id is not null
|
||||
and artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$'
|
||||
)
|
||||
or (source_kind = 'template' and artifact_source_id is null)
|
||||
);
|
||||
|
||||
alter table resource_versions
|
||||
add constraint resource_versions_source_kind_check check (
|
||||
source_kind in ('artifact', 'template')
|
||||
);
|
||||
|
||||
alter table resource_publications
|
||||
add column source_kind text not null default 'artifact';
|
||||
|
||||
alter table resource_publications
|
||||
alter column artifact_source_id drop not null;
|
||||
|
||||
alter table resource_publications
|
||||
drop constraint resource_publications_size_check;
|
||||
|
||||
alter table resource_publications
|
||||
add constraint resource_publications_size_check check (
|
||||
(source_kind = 'artifact' and size_bytes between 1 and 262144)
|
||||
or (source_kind = 'template' and size_bytes = 0)
|
||||
);
|
||||
|
||||
alter table resource_publications
|
||||
drop constraint resource_publications_source_id_check;
|
||||
|
||||
alter table resource_publications
|
||||
add constraint resource_publications_source_id_check check (
|
||||
(
|
||||
source_kind = 'artifact'
|
||||
and artifact_source_id is not null
|
||||
and artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$'
|
||||
)
|
||||
or (source_kind = 'template' and artifact_source_id is null)
|
||||
);
|
||||
|
||||
alter table resource_publications
|
||||
add constraint resource_publications_source_kind_check check (
|
||||
source_kind in ('artifact', 'template')
|
||||
);
|
||||
|
||||
create table resource_template_sources (
|
||||
workspace_id text not null,
|
||||
resource_id text not null,
|
||||
version integer not null,
|
||||
definition_json text not null,
|
||||
definition_digest text not null,
|
||||
created_at timestamptz not null,
|
||||
constraint resource_template_sources_version_check check (version >= 1),
|
||||
constraint resource_template_sources_definition_len_check check (
|
||||
octet_length(definition_json) between 2 and 65536
|
||||
),
|
||||
constraint resource_template_sources_digest_check check (
|
||||
definition_digest ~ '^[0-9a-f]{64}$'
|
||||
),
|
||||
primary key (workspace_id, resource_id, version),
|
||||
constraint resource_template_sources_version_fkey
|
||||
foreign key (workspace_id, resource_id, version)
|
||||
references resource_versions(workspace_id, resource_id, version)
|
||||
on delete cascade
|
||||
);
|
||||
|
||||
create function crank_guard_resource_template_source_immutable()
|
||||
returns trigger
|
||||
language plpgsql
|
||||
as $$
|
||||
begin
|
||||
raise exception 'resource template source definitions are immutable';
|
||||
end;
|
||||
$$;
|
||||
|
||||
create trigger crank_guard_resource_template_source_immutable
|
||||
before update on resource_template_sources
|
||||
for each row execute function crank_guard_resource_template_source_immutable();
|
||||
@@ -2,269 +2,10 @@ use sqlx::{PgConnection, Row, query};
|
||||
|
||||
use super::authority::MigrationError;
|
||||
|
||||
pub(super) const OWNED_RELATIONS: &[&str] = &[
|
||||
"__crank_core_migrations",
|
||||
"__crank_migrations",
|
||||
"__crank_migration_legacy_audit",
|
||||
"__crank_mcp_migrations",
|
||||
"__crank_ext_migrations",
|
||||
"mcp_transport_sessions",
|
||||
"workspaces",
|
||||
"users",
|
||||
"memberships",
|
||||
"user_sessions",
|
||||
"invitation_tokens",
|
||||
"platform_api_keys",
|
||||
"operations",
|
||||
"operation_versions",
|
||||
"published_operations",
|
||||
"operation_samples",
|
||||
"descriptors",
|
||||
"agents",
|
||||
"agent_versions",
|
||||
"published_agents",
|
||||
"agent_operation_bindings",
|
||||
"secrets",
|
||||
"secret_versions",
|
||||
"master_key_identities",
|
||||
"master_key_rotations",
|
||||
"auth_profiles",
|
||||
"workspace_upstreams",
|
||||
"yaml_import_jobs",
|
||||
"import_jobs",
|
||||
"approval_requests",
|
||||
"invocation_logs",
|
||||
"usage_rollups",
|
||||
"artifact_blobs",
|
||||
"artifact_sources",
|
||||
"import_plans",
|
||||
"import_plan_applications",
|
||||
"onboarding_import_selections",
|
||||
];
|
||||
mod required_tables;
|
||||
|
||||
const REQUIRED_COLUMNS: &[(&str, &[&str])] = &[
|
||||
(
|
||||
"__crank_core_migrations",
|
||||
&["version", "description", "checksum", "applied_at"],
|
||||
),
|
||||
(
|
||||
"__crank_migrations",
|
||||
&[
|
||||
"version",
|
||||
"name",
|
||||
"checksum",
|
||||
"phase",
|
||||
"compatibility",
|
||||
"applied_at",
|
||||
],
|
||||
),
|
||||
(
|
||||
"__crank_migration_legacy_audit",
|
||||
&["source", "source_version", "source_checksum", "imported_at"],
|
||||
),
|
||||
(
|
||||
"__crank_mcp_migrations",
|
||||
&["version", "checksum", "applied_at"],
|
||||
),
|
||||
(
|
||||
"__crank_ext_migrations",
|
||||
&["extension_name", "version", "checksum", "applied_at"],
|
||||
),
|
||||
(
|
||||
"mcp_transport_sessions",
|
||||
&[
|
||||
"id",
|
||||
"protocol_version",
|
||||
"initialized",
|
||||
"supports_elicitation",
|
||||
"workspace_slug",
|
||||
"agent_slug",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
"expires_at",
|
||||
],
|
||||
),
|
||||
(
|
||||
"master_key_identities",
|
||||
&[
|
||||
"epoch",
|
||||
"fingerprint",
|
||||
"cipher_contract",
|
||||
"status",
|
||||
"backup_ref",
|
||||
"created_at",
|
||||
"activated_at",
|
||||
"retired_at",
|
||||
],
|
||||
),
|
||||
(
|
||||
"master_key_rotations",
|
||||
&[
|
||||
"id",
|
||||
"source_epoch",
|
||||
"target_epoch",
|
||||
"target_fingerprint",
|
||||
"state",
|
||||
"backup_ref",
|
||||
"checkpoint_secret_id",
|
||||
"total_secret_versions",
|
||||
"processed_secret_versions",
|
||||
"verified_secret_versions",
|
||||
"failure_code",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
],
|
||||
),
|
||||
];
|
||||
|
||||
const REQUIRED_COLUMN_TYPES: &[(&str, &str, &str, bool)] = &[
|
||||
("__crank_core_migrations", "version", "integer", false),
|
||||
("__crank_core_migrations", "description", "text", false),
|
||||
("__crank_core_migrations", "checksum", "text", false),
|
||||
(
|
||||
"__crank_core_migrations",
|
||||
"applied_at",
|
||||
"timestamp with time zone",
|
||||
false,
|
||||
),
|
||||
("__crank_migrations", "version", "bigint", false),
|
||||
("__crank_migrations", "name", "text", false),
|
||||
("__crank_migrations", "checksum", "text", false),
|
||||
("__crank_migrations", "phase", "text", false),
|
||||
("__crank_migrations", "compatibility", "text", false),
|
||||
(
|
||||
"__crank_migrations",
|
||||
"applied_at",
|
||||
"timestamp with time zone",
|
||||
false,
|
||||
),
|
||||
("__crank_migration_legacy_audit", "source", "text", false),
|
||||
(
|
||||
"__crank_migration_legacy_audit",
|
||||
"source_version",
|
||||
"bigint",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"__crank_migration_legacy_audit",
|
||||
"source_checksum",
|
||||
"text",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"__crank_migration_legacy_audit",
|
||||
"imported_at",
|
||||
"timestamp with time zone",
|
||||
false,
|
||||
),
|
||||
("__crank_mcp_migrations", "version", "integer", false),
|
||||
("__crank_mcp_migrations", "checksum", "text", false),
|
||||
(
|
||||
"__crank_mcp_migrations",
|
||||
"applied_at",
|
||||
"timestamp with time zone",
|
||||
false,
|
||||
),
|
||||
("__crank_ext_migrations", "extension_name", "text", false),
|
||||
("__crank_ext_migrations", "version", "integer", false),
|
||||
("__crank_ext_migrations", "checksum", "text", true),
|
||||
(
|
||||
"__crank_ext_migrations",
|
||||
"applied_at",
|
||||
"timestamp with time zone",
|
||||
false,
|
||||
),
|
||||
("mcp_transport_sessions", "id", "text", false),
|
||||
("mcp_transport_sessions", "protocol_version", "text", false),
|
||||
("mcp_transport_sessions", "initialized", "boolean", false),
|
||||
(
|
||||
"mcp_transport_sessions",
|
||||
"supports_elicitation",
|
||||
"boolean",
|
||||
false,
|
||||
),
|
||||
("mcp_transport_sessions", "workspace_slug", "text", false),
|
||||
("mcp_transport_sessions", "agent_slug", "text", false),
|
||||
(
|
||||
"mcp_transport_sessions",
|
||||
"created_at",
|
||||
"timestamp with time zone",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"mcp_transport_sessions",
|
||||
"updated_at",
|
||||
"timestamp with time zone",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"mcp_transport_sessions",
|
||||
"expires_at",
|
||||
"timestamp with time zone",
|
||||
true,
|
||||
),
|
||||
("master_key_identities", "epoch", "bigint", false),
|
||||
("master_key_identities", "fingerprint", "text", false),
|
||||
("master_key_identities", "cipher_contract", "text", false),
|
||||
("master_key_identities", "status", "text", false),
|
||||
("master_key_identities", "backup_ref", "text", true),
|
||||
(
|
||||
"master_key_identities",
|
||||
"created_at",
|
||||
"timestamp with time zone",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"master_key_identities",
|
||||
"activated_at",
|
||||
"timestamp with time zone",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"master_key_identities",
|
||||
"retired_at",
|
||||
"timestamp with time zone",
|
||||
true,
|
||||
),
|
||||
("master_key_rotations", "id", "text", false),
|
||||
("master_key_rotations", "source_epoch", "bigint", false),
|
||||
("master_key_rotations", "target_epoch", "bigint", false),
|
||||
("master_key_rotations", "target_fingerprint", "text", false),
|
||||
("master_key_rotations", "state", "text", false),
|
||||
("master_key_rotations", "backup_ref", "text", true),
|
||||
("master_key_rotations", "checkpoint_secret_id", "text", true),
|
||||
(
|
||||
"master_key_rotations",
|
||||
"total_secret_versions",
|
||||
"bigint",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"master_key_rotations",
|
||||
"processed_secret_versions",
|
||||
"bigint",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"master_key_rotations",
|
||||
"verified_secret_versions",
|
||||
"bigint",
|
||||
false,
|
||||
),
|
||||
("master_key_rotations", "failure_code", "text", true),
|
||||
(
|
||||
"master_key_rotations",
|
||||
"created_at",
|
||||
"timestamp with time zone",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"master_key_rotations",
|
||||
"updated_at",
|
||||
"timestamp with time zone",
|
||||
false,
|
||||
),
|
||||
];
|
||||
pub(super) use required_tables::OWNED_RELATIONS;
|
||||
use required_tables::{REQUIRED_COLUMN_TYPES, REQUIRED_COLUMNS};
|
||||
|
||||
pub(super) async fn relation_exists(
|
||||
connection: &mut PgConnection,
|
||||
@@ -662,6 +403,71 @@ pub(super) async fn validate_schema_fingerprint(
|
||||
} else {
|
||||
super::schema_guard_v15::validate_v15_onboarding_import_selection(connection).await?;
|
||||
}
|
||||
if current_version < 16 {
|
||||
if !super::schema_guard_v16::validate_v16_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
} else {
|
||||
super::schema_guard_v16::validate_v16_resource_drafts(connection, current_version).await?;
|
||||
}
|
||||
if current_version < 17 {
|
||||
if !super::schema_guard_v17::validate_v17_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
} else {
|
||||
super::schema_guard_v17::validate_v17_resource_publications(connection, current_version)
|
||||
.await?;
|
||||
}
|
||||
if current_version < 18 {
|
||||
if !super::schema_guard_v18::validate_v18_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
} else {
|
||||
super::schema_guard_v18::validate_v18_agent_resource_bindings(connection).await?;
|
||||
}
|
||||
if current_version < 19 {
|
||||
if !super::schema_guard_v19::validate_v19_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
} else {
|
||||
super::schema_guard_v19::validate_v19_resource_security_revocations(connection).await?;
|
||||
}
|
||||
if current_version < 20 {
|
||||
if !super::schema_guard_v20::validate_v20_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
} else {
|
||||
super::schema_guard_v20::validate_v20_resource_template_sources(connection).await?;
|
||||
}
|
||||
if current_version < 21 {
|
||||
for relation in [
|
||||
"prompts",
|
||||
"prompt_versions",
|
||||
"prompt_arguments",
|
||||
"prompt_messages",
|
||||
] {
|
||||
if relation_exists(connection, relation).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
validate_required_relations(connection, super::owned_relations::PROMPTS, current_version)
|
||||
.await?;
|
||||
}
|
||||
if current_version < 22 {
|
||||
if !super::schema_guard_v22::validate_v22_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
} else {
|
||||
super::schema_guard_v22::validate_v22_prompt_publications(connection).await?;
|
||||
}
|
||||
if current_version < 23 {
|
||||
if !super::schema_guard_v23::validate_v23_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
} else {
|
||||
super::schema_guard_v23::validate_v23_prompt_dependencies(connection).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,414 @@
|
||||
//! Статические таблицы ожидаемой схемы (вынесены из `schema_guard.rs`, чтобы
|
||||
//! файл оставался в пределах rust-code-health); поведение guard не меняется.
|
||||
|
||||
pub(crate) const OWNED_RELATIONS: &[&str] = &[
|
||||
"__crank_core_migrations",
|
||||
"__crank_migrations",
|
||||
"__crank_migration_legacy_audit",
|
||||
"__crank_mcp_migrations",
|
||||
"__crank_ext_migrations",
|
||||
"mcp_transport_sessions",
|
||||
"workspaces",
|
||||
"users",
|
||||
"memberships",
|
||||
"user_sessions",
|
||||
"invitation_tokens",
|
||||
"platform_api_keys",
|
||||
"operations",
|
||||
"operation_versions",
|
||||
"published_operations",
|
||||
"operation_samples",
|
||||
"descriptors",
|
||||
"agents",
|
||||
"agent_versions",
|
||||
"published_agents",
|
||||
"agent_operation_bindings",
|
||||
"secrets",
|
||||
"secret_versions",
|
||||
"master_key_identities",
|
||||
"master_key_rotations",
|
||||
"auth_profiles",
|
||||
"workspace_upstreams",
|
||||
"yaml_import_jobs",
|
||||
"import_jobs",
|
||||
"approval_requests",
|
||||
"invocation_logs",
|
||||
"usage_rollups",
|
||||
"artifact_blobs",
|
||||
"artifact_sources",
|
||||
"import_plans",
|
||||
"import_plan_applications",
|
||||
"onboarding_import_selections",
|
||||
"resources",
|
||||
"resource_versions",
|
||||
"resource_publications",
|
||||
"agent_resource_bindings",
|
||||
"resource_security_revocations",
|
||||
"resource_template_sources",
|
||||
"prompts",
|
||||
"prompt_versions",
|
||||
"prompt_arguments",
|
||||
"prompt_messages",
|
||||
"prompt_dependencies",
|
||||
"prompt_message_resource_refs",
|
||||
];
|
||||
|
||||
pub(crate) const REQUIRED_COLUMNS: &[(&str, &[&str])] = &[
|
||||
(
|
||||
"__crank_core_migrations",
|
||||
&["version", "description", "checksum", "applied_at"],
|
||||
),
|
||||
(
|
||||
"__crank_migrations",
|
||||
&[
|
||||
"version",
|
||||
"name",
|
||||
"checksum",
|
||||
"phase",
|
||||
"compatibility",
|
||||
"applied_at",
|
||||
],
|
||||
),
|
||||
(
|
||||
"__crank_migration_legacy_audit",
|
||||
&["source", "source_version", "source_checksum", "imported_at"],
|
||||
),
|
||||
(
|
||||
"__crank_mcp_migrations",
|
||||
&["version", "checksum", "applied_at"],
|
||||
),
|
||||
(
|
||||
"__crank_ext_migrations",
|
||||
&["extension_name", "version", "checksum", "applied_at"],
|
||||
),
|
||||
(
|
||||
"mcp_transport_sessions",
|
||||
&[
|
||||
"id",
|
||||
"protocol_version",
|
||||
"initialized",
|
||||
"supports_elicitation",
|
||||
"workspace_slug",
|
||||
"agent_slug",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
"expires_at",
|
||||
],
|
||||
),
|
||||
(
|
||||
"master_key_identities",
|
||||
&[
|
||||
"epoch",
|
||||
"fingerprint",
|
||||
"cipher_contract",
|
||||
"status",
|
||||
"backup_ref",
|
||||
"created_at",
|
||||
"activated_at",
|
||||
"retired_at",
|
||||
],
|
||||
),
|
||||
(
|
||||
"master_key_rotations",
|
||||
&[
|
||||
"id",
|
||||
"source_epoch",
|
||||
"target_epoch",
|
||||
"target_fingerprint",
|
||||
"state",
|
||||
"backup_ref",
|
||||
"checkpoint_secret_id",
|
||||
"total_secret_versions",
|
||||
"processed_secret_versions",
|
||||
"verified_secret_versions",
|
||||
"failure_code",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
],
|
||||
),
|
||||
(
|
||||
"prompts",
|
||||
&[
|
||||
"workspace_id",
|
||||
"prompt_id",
|
||||
"name",
|
||||
"description",
|
||||
"status",
|
||||
"sensitivity",
|
||||
"current_draft_version",
|
||||
"latest_published_version",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
],
|
||||
),
|
||||
(
|
||||
"prompt_versions",
|
||||
&["workspace_id", "prompt_id", "version", "created_at"],
|
||||
),
|
||||
(
|
||||
"prompt_arguments",
|
||||
&[
|
||||
"workspace_id",
|
||||
"prompt_id",
|
||||
"version",
|
||||
"argument_name",
|
||||
"argument_type",
|
||||
"required",
|
||||
"default_value",
|
||||
"enumeration",
|
||||
"position",
|
||||
],
|
||||
),
|
||||
(
|
||||
"prompt_messages",
|
||||
&[
|
||||
"workspace_id",
|
||||
"prompt_id",
|
||||
"version",
|
||||
"position",
|
||||
"role",
|
||||
"content",
|
||||
],
|
||||
),
|
||||
(
|
||||
"prompt_dependencies",
|
||||
&[
|
||||
"workspace_id",
|
||||
"prompt_id",
|
||||
"version",
|
||||
"dependency_position",
|
||||
"resource_id",
|
||||
"resource_version",
|
||||
"digest",
|
||||
"kind",
|
||||
"mime_type",
|
||||
"source_class",
|
||||
"sensitivity",
|
||||
],
|
||||
),
|
||||
(
|
||||
"prompt_message_resource_refs",
|
||||
&[
|
||||
"workspace_id",
|
||||
"prompt_id",
|
||||
"version",
|
||||
"message_position",
|
||||
"ref_position",
|
||||
"dependency_position",
|
||||
],
|
||||
),
|
||||
];
|
||||
|
||||
pub(crate) const REQUIRED_COLUMN_TYPES: &[(&str, &str, &str, bool)] = &[
|
||||
("__crank_core_migrations", "version", "integer", false),
|
||||
("__crank_core_migrations", "description", "text", false),
|
||||
("__crank_core_migrations", "checksum", "text", false),
|
||||
(
|
||||
"__crank_core_migrations",
|
||||
"applied_at",
|
||||
"timestamp with time zone",
|
||||
false,
|
||||
),
|
||||
("__crank_migrations", "version", "bigint", false),
|
||||
("__crank_migrations", "name", "text", false),
|
||||
("__crank_migrations", "checksum", "text", false),
|
||||
("__crank_migrations", "phase", "text", false),
|
||||
("__crank_migrations", "compatibility", "text", false),
|
||||
(
|
||||
"__crank_migrations",
|
||||
"applied_at",
|
||||
"timestamp with time zone",
|
||||
false,
|
||||
),
|
||||
("__crank_migration_legacy_audit", "source", "text", false),
|
||||
(
|
||||
"__crank_migration_legacy_audit",
|
||||
"source_version",
|
||||
"bigint",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"__crank_migration_legacy_audit",
|
||||
"source_checksum",
|
||||
"text",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"__crank_migration_legacy_audit",
|
||||
"imported_at",
|
||||
"timestamp with time zone",
|
||||
false,
|
||||
),
|
||||
("__crank_mcp_migrations", "version", "integer", false),
|
||||
("__crank_mcp_migrations", "checksum", "text", false),
|
||||
(
|
||||
"__crank_mcp_migrations",
|
||||
"applied_at",
|
||||
"timestamp with time zone",
|
||||
false,
|
||||
),
|
||||
("__crank_ext_migrations", "extension_name", "text", false),
|
||||
("__crank_ext_migrations", "version", "integer", false),
|
||||
("__crank_ext_migrations", "checksum", "text", true),
|
||||
(
|
||||
"__crank_ext_migrations",
|
||||
"applied_at",
|
||||
"timestamp with time zone",
|
||||
false,
|
||||
),
|
||||
("mcp_transport_sessions", "id", "text", false),
|
||||
("mcp_transport_sessions", "protocol_version", "text", false),
|
||||
("mcp_transport_sessions", "initialized", "boolean", false),
|
||||
(
|
||||
"mcp_transport_sessions",
|
||||
"supports_elicitation",
|
||||
"boolean",
|
||||
false,
|
||||
),
|
||||
("mcp_transport_sessions", "workspace_slug", "text", false),
|
||||
("mcp_transport_sessions", "agent_slug", "text", false),
|
||||
(
|
||||
"mcp_transport_sessions",
|
||||
"created_at",
|
||||
"timestamp with time zone",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"mcp_transport_sessions",
|
||||
"updated_at",
|
||||
"timestamp with time zone",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"mcp_transport_sessions",
|
||||
"expires_at",
|
||||
"timestamp with time zone",
|
||||
true,
|
||||
),
|
||||
("master_key_identities", "epoch", "bigint", false),
|
||||
("master_key_identities", "fingerprint", "text", false),
|
||||
("master_key_identities", "cipher_contract", "text", false),
|
||||
("master_key_identities", "status", "text", false),
|
||||
("master_key_identities", "backup_ref", "text", true),
|
||||
(
|
||||
"master_key_identities",
|
||||
"created_at",
|
||||
"timestamp with time zone",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"master_key_identities",
|
||||
"activated_at",
|
||||
"timestamp with time zone",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"master_key_identities",
|
||||
"retired_at",
|
||||
"timestamp with time zone",
|
||||
true,
|
||||
),
|
||||
("master_key_rotations", "id", "text", false),
|
||||
("master_key_rotations", "source_epoch", "bigint", false),
|
||||
("master_key_rotations", "target_epoch", "bigint", false),
|
||||
("master_key_rotations", "target_fingerprint", "text", false),
|
||||
("master_key_rotations", "state", "text", false),
|
||||
("master_key_rotations", "backup_ref", "text", true),
|
||||
("master_key_rotations", "checkpoint_secret_id", "text", true),
|
||||
(
|
||||
"master_key_rotations",
|
||||
"total_secret_versions",
|
||||
"bigint",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"master_key_rotations",
|
||||
"processed_secret_versions",
|
||||
"bigint",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"master_key_rotations",
|
||||
"verified_secret_versions",
|
||||
"bigint",
|
||||
false,
|
||||
),
|
||||
("master_key_rotations", "failure_code", "text", true),
|
||||
(
|
||||
"master_key_rotations",
|
||||
"created_at",
|
||||
"timestamp with time zone",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"master_key_rotations",
|
||||
"updated_at",
|
||||
"timestamp with time zone",
|
||||
false,
|
||||
),
|
||||
("prompts", "workspace_id", "text", false),
|
||||
("prompts", "prompt_id", "text", false),
|
||||
("prompts", "name", "text", false),
|
||||
("prompts", "description", "text", false),
|
||||
("prompts", "status", "text", false),
|
||||
("prompts", "sensitivity", "text", false),
|
||||
("prompts", "current_draft_version", "integer", false),
|
||||
("prompts", "created_at", "timestamp with time zone", false),
|
||||
("prompts", "updated_at", "timestamp with time zone", false),
|
||||
("prompt_versions", "workspace_id", "text", false),
|
||||
("prompt_versions", "prompt_id", "text", false),
|
||||
("prompt_versions", "version", "integer", false),
|
||||
(
|
||||
"prompt_versions",
|
||||
"created_at",
|
||||
"timestamp with time zone",
|
||||
false,
|
||||
),
|
||||
("prompt_arguments", "workspace_id", "text", false),
|
||||
("prompt_arguments", "prompt_id", "text", false),
|
||||
("prompt_arguments", "version", "integer", false),
|
||||
("prompt_arguments", "argument_name", "text", false),
|
||||
("prompt_arguments", "argument_type", "text", false),
|
||||
("prompt_arguments", "required", "boolean", false),
|
||||
("prompt_arguments", "default_value", "jsonb", true),
|
||||
("prompt_arguments", "enumeration", "jsonb", true),
|
||||
("prompt_arguments", "position", "integer", false),
|
||||
("prompt_messages", "workspace_id", "text", false),
|
||||
("prompt_messages", "prompt_id", "text", false),
|
||||
("prompt_messages", "version", "integer", false),
|
||||
("prompt_messages", "position", "integer", false),
|
||||
("prompt_messages", "role", "text", false),
|
||||
("prompt_messages", "content", "text", false),
|
||||
("prompt_dependencies", "workspace_id", "text", false),
|
||||
(
|
||||
"prompt_dependencies",
|
||||
"dependency_position",
|
||||
"integer",
|
||||
false,
|
||||
),
|
||||
("prompt_dependencies", "resource_id", "text", false),
|
||||
("prompt_dependencies", "resource_version", "integer", false),
|
||||
("prompt_dependencies", "digest", "text", false),
|
||||
("prompt_dependencies", "kind", "text", false),
|
||||
("prompt_dependencies", "mime_type", "text", false),
|
||||
("prompt_dependencies", "source_class", "text", false),
|
||||
("prompt_dependencies", "sensitivity", "text", false),
|
||||
(
|
||||
"prompt_message_resource_refs",
|
||||
"message_position",
|
||||
"integer",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"prompt_message_resource_refs",
|
||||
"ref_position",
|
||||
"integer",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"prompt_message_resource_refs",
|
||||
"dependency_position",
|
||||
"integer",
|
||||
false,
|
||||
),
|
||||
];
|
||||
@@ -0,0 +1,571 @@
|
||||
//! V16 schema guard: typed static Resource drafts (Story 3.6).
|
||||
//!
|
||||
//! Проверяет, что схема V16 либо полностью отсутствует (миграция ещё не
|
||||
//! применена), либо присутствует ровно в ожидаемой форме: таблицы, колонки,
|
||||
//! constraints (точные определения и CHECK-выражения с сохранением SQL-литералов)
|
||||
//! и частичный unique-index «одна текущая черновая версия».
|
||||
|
||||
use sqlx::{PgConnection, Row, query};
|
||||
|
||||
use super::authority::MigrationError;
|
||||
use super::schema_guard::{normalize_definition, relation_exists};
|
||||
|
||||
const OWNED_RELATIONS: &[&str] = &[
|
||||
"resources",
|
||||
"resource_versions",
|
||||
"resources_workspace_created_idx",
|
||||
"resource_versions_current_draft_unique",
|
||||
];
|
||||
|
||||
const RESOURCE_COLUMNS: &[(&str, &str, bool)] = &[
|
||||
("workspace_id", "text", false),
|
||||
("resource_id", "text", false),
|
||||
("uri", "text", false),
|
||||
("name", "text", false),
|
||||
("description", "text", false),
|
||||
("status", "text", false),
|
||||
("kind", "text", false),
|
||||
("current_draft_version", "integer", false),
|
||||
("created_at", "timestamp with time zone", false),
|
||||
("updated_at", "timestamp with time zone", false),
|
||||
];
|
||||
|
||||
const VERSION_COLUMNS_V16: &[(&str, &str, bool)] = &[
|
||||
("workspace_id", "text", false),
|
||||
("resource_id", "text", false),
|
||||
("version", "integer", false),
|
||||
("kind", "text", false),
|
||||
("mime_type", "text", false),
|
||||
("size_bytes", "bigint", false),
|
||||
("digest", "text", false),
|
||||
("sensitivity", "text", false),
|
||||
("artifact_source_id", "text", false),
|
||||
("created_at", "timestamp with time zone", false),
|
||||
("superseded_at", "timestamp with time zone", true),
|
||||
];
|
||||
|
||||
/// V20 добавляет `source_kind` и допускает byte-less template-версии: колонки
|
||||
/// проверяются относительно фактической версии схемы.
|
||||
const VERSION_COLUMNS_V20: &[(&str, &str, bool)] = &[
|
||||
("workspace_id", "text", false),
|
||||
("resource_id", "text", false),
|
||||
("version", "integer", false),
|
||||
("kind", "text", false),
|
||||
("mime_type", "text", false),
|
||||
("size_bytes", "bigint", false),
|
||||
("digest", "text", false),
|
||||
("sensitivity", "text", false),
|
||||
("artifact_source_id", "text", true),
|
||||
("source_kind", "text", false),
|
||||
("created_at", "timestamp with time zone", false),
|
||||
("superseded_at", "timestamp with time zone", true),
|
||||
];
|
||||
|
||||
fn version_columns(current_version: i64) -> &'static [(&'static str, &'static str, bool)] {
|
||||
if current_version >= 20 {
|
||||
VERSION_COLUMNS_V20
|
||||
} else {
|
||||
VERSION_COLUMNS_V16
|
||||
}
|
||||
}
|
||||
|
||||
/// V20 переопределяет два CHECK-а `resource_versions`: template-строки не имеют
|
||||
/// artifact-ссылки и байтов, artifact-строки сохраняют прежние границы.
|
||||
const VERSION_CHECK_EXPRESSIONS_V20: &[(&str, &str, &str)] = &[
|
||||
(
|
||||
"resource_versions_size_check",
|
||||
"v16.version_size_check",
|
||||
"CHECK (source_kind = 'artifact'::text AND size_bytes >= 1 AND size_bytes <= 262144 \
|
||||
OR source_kind = 'template'::text AND size_bytes = 0)",
|
||||
),
|
||||
(
|
||||
"resource_versions_source_id_check",
|
||||
"v16.version_source_id_check",
|
||||
"CHECK (source_kind = 'artifact'::text AND artifact_source_id IS NOT NULL \
|
||||
AND artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$'::text \
|
||||
OR source_kind = 'template'::text AND artifact_source_id IS NULL)",
|
||||
),
|
||||
];
|
||||
|
||||
fn version_check_expectations(
|
||||
current_version: i64,
|
||||
) -> Vec<(&'static str, &'static str, &'static str)> {
|
||||
VERSION_CHECK_EXPRESSIONS
|
||||
.iter()
|
||||
.map(|(constraint, stage, legacy)| {
|
||||
let expected = if current_version >= 20 {
|
||||
VERSION_CHECK_EXPRESSIONS_V20
|
||||
.iter()
|
||||
.find(|(name, _, _)| name == constraint)
|
||||
.map(|(_, _, expected)| *expected)
|
||||
.unwrap_or(*legacy)
|
||||
} else {
|
||||
*legacy
|
||||
};
|
||||
(*constraint, *stage, expected)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Определения constraints V16, у которых guard сверяет семантику целиком.
|
||||
///
|
||||
/// Имя и `contype` сохраняются у всех однофакторных мутаций (`check (true)`,
|
||||
/// другая цель/колонки/действие удаления, `NOT VALID`), поэтому ожидание
|
||||
/// сравнивается с нормализованным `pg_get_constraintdef` и требует
|
||||
/// `convalidated = true` (P4, TL run105 F06).
|
||||
const RESOURCE_DEFINITIONS: &[(&str, &str, &str, &str)] = &[
|
||||
(
|
||||
"resources_pkey",
|
||||
"p",
|
||||
"v16.resources_pkey",
|
||||
"primarykeyworkspace_id,resource_id",
|
||||
),
|
||||
(
|
||||
"resources_workspace_id_fkey",
|
||||
"f",
|
||||
"v16.resources_workspace_id_fkey",
|
||||
"foreignkeyworkspace_idreferencesworkspacesidondeletecascade",
|
||||
),
|
||||
(
|
||||
"resources_workspace_uri_unique",
|
||||
"u",
|
||||
"v16.resources_workspace_uri_unique",
|
||||
"uniqueworkspace_id,uri",
|
||||
),
|
||||
(
|
||||
"resources_workspace_name_unique",
|
||||
"u",
|
||||
"v16.resources_workspace_name_unique",
|
||||
"uniqueworkspace_id,name",
|
||||
),
|
||||
];
|
||||
|
||||
const VERSION_DEFINITIONS: &[(&str, &str, &str, &str)] = &[
|
||||
(
|
||||
"resource_versions_pkey",
|
||||
"p",
|
||||
"v16.version_pkey",
|
||||
"primarykeyworkspace_id,resource_id,version",
|
||||
),
|
||||
(
|
||||
"resource_versions_resource_fkey",
|
||||
"f",
|
||||
"v16.version_resource_fkey",
|
||||
"foreignkeyworkspace_id,resource_idreferencesresourcesworkspace_id,resource_idondeletecascade",
|
||||
),
|
||||
(
|
||||
"resource_versions_source_fkey",
|
||||
"f",
|
||||
"v16.version_source_fkey",
|
||||
"foreignkeyworkspace_id,artifact_source_idreferencesartifact_sourcesworkspace_id,source_id",
|
||||
),
|
||||
];
|
||||
|
||||
/// CHECK-выражения V16: сверяется **точное** каноническое определение constraint-а
|
||||
/// (`pg_get_constraintdef(c.oid, true)`) и `convalidated = true`.
|
||||
///
|
||||
/// Ожидания записаны ровно так, как их печатает PostgreSQL 16 (снято из `pg_catalog`
|
||||
/// на канонической схеме V16), и сравниваются через `normalize_v16_definition`,
|
||||
/// который убирает пробелы и приводит регистр только вне строковых литералов.
|
||||
///
|
||||
/// Подстрочная сверка пропускала `check (octet_length(description) <= 1024 or
|
||||
/// resource_id is not null)` (TL run109 F5), а сверка «по набору литералов» —
|
||||
/// перечисляющий CHECK с добавленным предикатом (TL run113 EH1). Общая
|
||||
/// нормализация, снимающая регистр и пробелы по всей строке, пропускала дрейф
|
||||
/// **внутри** SQL-литералов: `'^[0-9a-f ]{64}$'` (класс с пробелом) и
|
||||
/// lowercase-вариант MIME-маски совпадали с каноническими (TL run113 EH2).
|
||||
const RESOURCE_CHECK_EXPRESSIONS: &[(&str, &str, &str)] = &[
|
||||
(
|
||||
"resources_resource_id_check",
|
||||
"v16.resources_resource_id_check",
|
||||
"CHECK (resource_id ~ '^res_[A-Za-z0-9_-]{1,96}$'::text)",
|
||||
),
|
||||
(
|
||||
"resources_uri_len_check",
|
||||
"v16.resources_uri_len_check",
|
||||
"CHECK (octet_length(uri) >= 10 AND octet_length(uri) <= 200)",
|
||||
),
|
||||
(
|
||||
"resources_name_len_check",
|
||||
"v16.resources_name_len_check",
|
||||
"CHECK (octet_length(name) >= 1 AND octet_length(name) <= 64)",
|
||||
),
|
||||
(
|
||||
"resources_description_len",
|
||||
"v16.resources_description_len",
|
||||
"CHECK (octet_length(description) <= 1024)",
|
||||
),
|
||||
(
|
||||
"resources_status_check",
|
||||
"v16.resources_status_check",
|
||||
"CHECK (status = ANY (ARRAY['draft'::text, 'published'::text, 'archived'::text]))",
|
||||
),
|
||||
(
|
||||
"resources_kind_check",
|
||||
"v16.resources_kind_check",
|
||||
"CHECK (kind = ANY (ARRAY['text'::text, 'json'::text, 'binary'::text]))",
|
||||
),
|
||||
(
|
||||
"resources_current_version_check",
|
||||
"v16.resources_current_version_check",
|
||||
"CHECK (current_draft_version >= 1)",
|
||||
),
|
||||
(
|
||||
"resources_timestamps_check",
|
||||
"v16.resources_timestamps_check",
|
||||
"CHECK (updated_at >= created_at)",
|
||||
),
|
||||
];
|
||||
|
||||
const VERSION_CHECK_EXPRESSIONS: &[(&str, &str, &str)] = &[
|
||||
(
|
||||
"resource_versions_version_check",
|
||||
"v16.version_version_check",
|
||||
"CHECK (version >= 1)",
|
||||
),
|
||||
(
|
||||
"resource_versions_kind_check",
|
||||
"v16.version_kind_check",
|
||||
"CHECK (kind = ANY (ARRAY['text'::text, 'json'::text, 'binary'::text]))",
|
||||
),
|
||||
(
|
||||
"resource_versions_mime_type_check",
|
||||
"v16.version_mime_type_check",
|
||||
"CHECK (octet_length(mime_type) >= 3 AND octet_length(mime_type) <= 255 AND \
|
||||
mime_type ~ '^[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+$'::text)",
|
||||
),
|
||||
(
|
||||
"resource_versions_size_check",
|
||||
"v16.version_size_check",
|
||||
"CHECK (size_bytes >= 1 AND size_bytes <= 262144)",
|
||||
),
|
||||
(
|
||||
"resource_versions_digest_check",
|
||||
"v16.version_digest_check",
|
||||
"CHECK (digest ~ '^[0-9a-f]{64}$'::text)",
|
||||
),
|
||||
(
|
||||
"resource_versions_sensitivity_check",
|
||||
"v16.version_sensitivity_check",
|
||||
"CHECK (sensitivity = ANY (ARRAY['public'::text, 'internal'::text, 'secret'::text]))",
|
||||
),
|
||||
(
|
||||
"resource_versions_source_id_check",
|
||||
"v16.version_source_id_check",
|
||||
"CHECK (artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$'::text)",
|
||||
),
|
||||
(
|
||||
"resource_versions_supersede_check",
|
||||
"v16.version_supersede_check",
|
||||
"CHECK (superseded_at IS NULL OR superseded_at >= created_at)",
|
||||
),
|
||||
];
|
||||
|
||||
/// Отказ guard-а V16 с указанием конкретной проверки: наблюдаемый stage помогает
|
||||
/// быстро локализовать расхождение схемы, не ослабляя сам отказ.
|
||||
fn v16_error(stage: &'static str) -> MigrationError {
|
||||
MigrationError::new(
|
||||
"partial_sequence",
|
||||
stage,
|
||||
Some(16),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
}
|
||||
|
||||
/// Схема V16 отсутствует целиком (для current_version < 16).
|
||||
pub(super) async fn validate_v16_absent(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<bool, MigrationError> {
|
||||
for relation in OWNED_RELATIONS {
|
||||
if relation_exists(connection, relation).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Схема V16 присутствует в ожидаемой форме (для current_version >= 16).
|
||||
pub(super) async fn validate_v16_resource_drafts(
|
||||
connection: &mut PgConnection,
|
||||
current_version: i64,
|
||||
) -> Result<(), MigrationError> {
|
||||
for relation in OWNED_RELATIONS {
|
||||
if !relation_exists(connection, relation).await? {
|
||||
return Err(v16_error("v16.relations"));
|
||||
}
|
||||
}
|
||||
validate_columns(
|
||||
connection,
|
||||
"resources",
|
||||
RESOURCE_COLUMNS,
|
||||
"v16.resources_columns",
|
||||
)
|
||||
.await?;
|
||||
validate_columns(
|
||||
connection,
|
||||
"resource_versions",
|
||||
version_columns(current_version),
|
||||
"v16.version_columns",
|
||||
)
|
||||
.await?;
|
||||
validate_definitions(connection, "resources", RESOURCE_DEFINITIONS).await?;
|
||||
validate_definitions(connection, "resource_versions", VERSION_DEFINITIONS).await?;
|
||||
validate_check_expressions(connection, "resources", RESOURCE_CHECK_EXPRESSIONS).await?;
|
||||
validate_check_expressions(
|
||||
connection,
|
||||
"resource_versions",
|
||||
&version_check_expectations(current_version),
|
||||
)
|
||||
.await?;
|
||||
validate_current_draft_index(connection).await?;
|
||||
validate_created_index(connection).await
|
||||
}
|
||||
|
||||
/// Сверка определения constraint: `contype`, `convalidated` и **точное**
|
||||
/// нормализованное `pg_get_constraintdef`.
|
||||
///
|
||||
/// Точное сравнение (а не вхождение ожидаемого префикса) обязательно для FK: иначе
|
||||
/// дополнительные `ON DELETE`-действия и `DEFERRABLE` остаются разрешёнными
|
||||
/// (TL run109 F5).
|
||||
async fn validate_definitions(
|
||||
connection: &mut PgConnection,
|
||||
table: &str,
|
||||
expectations: &[(&'static str, &'static str, &'static str, &'static str)],
|
||||
) -> Result<(), MigrationError> {
|
||||
for (constraint, kind, stage, expected) in expectations {
|
||||
let row = query(
|
||||
"select c.contype::text as kind, c.convalidated,
|
||||
pg_get_constraintdef(c.oid, true) as definition
|
||||
from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema() and t.relname = $1 and c.conname = $2",
|
||||
)
|
||||
.bind(table)
|
||||
.bind(constraint)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let valid = row.is_some_and(|row| {
|
||||
row.try_get::<String, _>("kind").ok().as_deref() == Some(*kind)
|
||||
&& row.try_get::<bool, _>("convalidated").ok() == Some(true)
|
||||
&& row
|
||||
.try_get::<String, _>("definition")
|
||||
.ok()
|
||||
.is_some_and(|definition| {
|
||||
normalize_definition(&definition) == normalize_definition(expected)
|
||||
})
|
||||
});
|
||||
if !valid {
|
||||
return Err(v16_error(stage));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Сверка CHECK-выражений (включая перечисляющие): точное каноническое определение
|
||||
/// + `convalidated = true`.
|
||||
///
|
||||
/// `NOT VALID` сохраняет выражение, поэтому без чтения признака валидации такой дрейф
|
||||
/// не наблюдается (TL run109 F5). Ожидание — полная каноническая форма PostgreSQL,
|
||||
/// поэтому добавленный к перечисляющему CHECK предикат тоже виден (TL run113 EH1).
|
||||
async fn validate_check_expressions(
|
||||
connection: &mut PgConnection,
|
||||
table: &str,
|
||||
expectations: &[(&'static str, &'static str, &'static str)],
|
||||
) -> Result<(), MigrationError> {
|
||||
for (constraint, stage, expected) in expectations {
|
||||
let (definition, convalidated) =
|
||||
constraint_definition_and_validation(connection, table, constraint, stage).await?;
|
||||
if !convalidated
|
||||
|| normalize_v16_definition(&definition) != normalize_v16_definition(expected)
|
||||
{
|
||||
return Err(v16_error(stage));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Нормализация определения V16: пробелы и регистр снимаются только **вне** строковых
|
||||
/// литералов.
|
||||
///
|
||||
/// Общий `normalize_definition` убирает пробелы и приводит регистр по всей строке,
|
||||
/// включая содержимое литералов, поэтому `'^[0-9a-f ]{64}$'` (класс с пробелом) и
|
||||
/// lowercase-вариант MIME-маски становились неотличимы от канонических выражений
|
||||
/// (TL run113 EH1/EH2). Здесь значимые символы внутри литералов сохраняются, а скобки
|
||||
/// и операторы вне литералов не удаляются — разные выражения не сливаются.
|
||||
/// `''` внутри литерала — экранированная кавычка, а не его конец.
|
||||
fn normalize_v16_definition(value: &str) -> String {
|
||||
let mut normalized = String::with_capacity(value.len());
|
||||
let mut literal = false;
|
||||
let mut characters = value.chars().peekable();
|
||||
while let Some(character) = characters.next() {
|
||||
if character == '\'' {
|
||||
normalized.push(character);
|
||||
if !literal {
|
||||
literal = true;
|
||||
} else if characters.peek() == Some(&'\'') {
|
||||
if let Some(escaped) = characters.next() {
|
||||
normalized.push(escaped);
|
||||
}
|
||||
} else {
|
||||
literal = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if literal {
|
||||
normalized.push(character);
|
||||
} else if !character.is_ascii_whitespace() {
|
||||
normalized.push(character.to_ascii_lowercase());
|
||||
}
|
||||
}
|
||||
normalized
|
||||
}
|
||||
|
||||
/// Каноническое определение CHECK-constraint-а V16 и признак его валидации.
|
||||
///
|
||||
/// Отсутствие ожидаемого ограничения — отказ именно V16-шага (а не общий preflight
|
||||
/// другой версии), поэтому stage передаётся в ошибку.
|
||||
async fn constraint_definition_and_validation(
|
||||
connection: &mut PgConnection,
|
||||
table: &str,
|
||||
constraint: &str,
|
||||
stage: &'static str,
|
||||
) -> Result<(String, bool), MigrationError> {
|
||||
query(
|
||||
"select pg_get_constraintdef(c.oid, true) as definition, c.convalidated
|
||||
from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema() and t.relname = $1 and c.conname = $2
|
||||
and c.contype = 'c'",
|
||||
)
|
||||
.bind(table)
|
||||
.bind(constraint)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.and_then(|row| {
|
||||
Some((
|
||||
row.try_get::<String, _>("definition").ok()?,
|
||||
row.try_get::<bool, _>("convalidated").ok()?,
|
||||
))
|
||||
})
|
||||
.ok_or_else(|| v16_error(stage))
|
||||
}
|
||||
|
||||
async fn validate_columns(
|
||||
connection: &mut PgConnection,
|
||||
table: &str,
|
||||
columns: &[(&str, &str, bool)],
|
||||
stage: &'static str,
|
||||
) -> Result<(), MigrationError> {
|
||||
for (column, data_type, nullable) in columns {
|
||||
let row = query(
|
||||
"select data_type, is_nullable from information_schema.columns
|
||||
where table_schema = current_schema() and table_name = $1 and column_name = $2",
|
||||
)
|
||||
.bind(table)
|
||||
.bind(column)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let valid = row.is_some_and(|row| {
|
||||
row.try_get::<String, _>("data_type").ok().as_deref() == Some(*data_type)
|
||||
&& row.try_get::<String, _>("is_nullable").ok().as_deref()
|
||||
== Some(if *nullable { "YES" } else { "NO" })
|
||||
});
|
||||
if !valid {
|
||||
return Err(v16_error(stage));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn validate_current_draft_index(connection: &mut PgConnection) -> Result<(), MigrationError> {
|
||||
let row = query(
|
||||
"select t.relname as table_name, am.amname as access_method, i.indisvalid, i.indisready,
|
||||
i.indisunique,
|
||||
pg_get_indexdef(i.indexrelid, 1, true) as first_column,
|
||||
pg_get_indexdef(i.indexrelid, 2, true) as second_column,
|
||||
pg_get_indexdef(i.indexrelid, 3, true) as third_column,
|
||||
pg_get_expr(i.indpred, i.indrelid) as predicate
|
||||
from pg_catalog.pg_index i
|
||||
join pg_catalog.pg_class idx on idx.oid = i.indexrelid
|
||||
join pg_catalog.pg_class t on t.oid = i.indrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
join pg_catalog.pg_am am on am.oid = idx.relam
|
||||
where n.nspname = current_schema()
|
||||
and idx.relname = 'resource_versions_current_draft_unique'",
|
||||
)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let valid = row.is_some_and(|row| {
|
||||
row.try_get::<String, _>("table_name").ok().as_deref() == Some("resource_versions")
|
||||
&& row.try_get::<String, _>("access_method").ok().as_deref() == Some("btree")
|
||||
&& row.try_get::<bool, _>("indisvalid").ok() == Some(true)
|
||||
&& row.try_get::<bool, _>("indisready").ok() == Some(true)
|
||||
&& row.try_get::<bool, _>("indisunique").ok() == Some(true)
|
||||
&& row.try_get::<String, _>("first_column").ok().as_deref() == Some("workspace_id")
|
||||
&& row.try_get::<String, _>("second_column").ok().as_deref() == Some("resource_id")
|
||||
// У двухколоночного индекса третья позиция пуста (`""`, не NULL).
|
||||
&& row
|
||||
.try_get::<String, _>("third_column")
|
||||
.ok()
|
||||
.is_none_or(|value| value.is_empty())
|
||||
&& row
|
||||
.try_get::<String, _>("predicate")
|
||||
.ok()
|
||||
.is_some_and(|value| normalize_definition(&value) == "superseded_atisnull")
|
||||
});
|
||||
if valid {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(v16_error("v16.current_draft_index"))
|
||||
}
|
||||
}
|
||||
|
||||
async fn validate_created_index(connection: &mut PgConnection) -> Result<(), MigrationError> {
|
||||
let row = query(
|
||||
"select t.relname as table_name, am.amname as access_method, i.indisvalid, i.indisready,
|
||||
i.indisunique, i.indnkeyatts, i.indnatts,
|
||||
pg_get_expr(i.indpred, i.indrelid) as predicate,
|
||||
pg_get_indexdef(i.indexrelid, 1, true) as first_column,
|
||||
pg_get_indexdef(i.indexrelid, 2, true) as second_column,
|
||||
pg_get_indexdef(i.indexrelid, 3, true) as third_column
|
||||
from pg_catalog.pg_index i
|
||||
join pg_catalog.pg_class idx on idx.oid = i.indexrelid
|
||||
join pg_catalog.pg_class t on t.oid = i.indrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
join pg_catalog.pg_am am on am.oid = idx.relam
|
||||
where n.nspname = current_schema()
|
||||
and idx.relname = 'resources_workspace_created_idx'",
|
||||
)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let valid = row.is_some_and(|row| {
|
||||
row.try_get::<String, _>("table_name").ok().as_deref() == Some("resources")
|
||||
&& row.try_get::<String, _>("access_method").ok().as_deref() == Some("btree")
|
||||
&& row.try_get::<bool, _>("indisvalid").ok() == Some(true)
|
||||
&& row.try_get::<bool, _>("indisready").ok() == Some(true)
|
||||
&& row.try_get::<bool, _>("indisunique").ok() == Some(false)
|
||||
// Ровно три ключевых столбца: четвёртый (или INCLUDE-столбец) — дрейф.
|
||||
&& row.try_get::<i16, _>("indnkeyatts").ok() == Some(3)
|
||||
&& row.try_get::<i16, _>("indnatts").ok() == Some(3)
|
||||
// Частичный индекс на этом месте — тоже дрейф: предиката быть не должно.
|
||||
&& row
|
||||
.try_get::<Option<String>, _>("predicate")
|
||||
.ok()
|
||||
.is_none_or(|value| value.is_none())
|
||||
&& row.try_get::<String, _>("first_column").ok().as_deref() == Some("workspace_id")
|
||||
&& row.try_get::<String, _>("second_column").ok().as_deref() == Some("created_at")
|
||||
&& row.try_get::<String, _>("third_column").ok().as_deref() == Some("resource_id")
|
||||
});
|
||||
if valid {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(v16_error("v16.created_index"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
//! V17 schema guard: typed immutable Resource publications (Story 3.7).
|
||||
//!
|
||||
//! Проверяет, что схема V17 либо полностью отсутствует (миграция ещё не
|
||||
//! применена), либо присутствует ровно в ожидаемой форме: таблица, колонки,
|
||||
//! PK/FK и CHECK-выражения снимка публичных metadata плюс индекс разрешения
|
||||
//! explicit `include:` цели по URI.
|
||||
|
||||
use sqlx::{PgConnection, Row, query};
|
||||
|
||||
use super::authority::MigrationError;
|
||||
use super::schema_guard::{normalize_definition, relation_exists};
|
||||
|
||||
const OWNED_RELATIONS: &[&str] = &[
|
||||
"resource_publications",
|
||||
"resource_publications_workspace_uri_idx",
|
||||
];
|
||||
|
||||
const COLUMNS_V17: &[(&str, &str, bool)] = &[
|
||||
("workspace_id", "text", false),
|
||||
("resource_id", "text", false),
|
||||
("version", "integer", false),
|
||||
("uri", "text", false),
|
||||
("name", "text", false),
|
||||
("description", "text", false),
|
||||
("kind", "text", false),
|
||||
("mime_type", "text", false),
|
||||
("size_bytes", "bigint", false),
|
||||
("digest", "text", false),
|
||||
("sensitivity", "text", false),
|
||||
("artifact_source_id", "text", false),
|
||||
("published_at", "timestamp with time zone", false),
|
||||
];
|
||||
|
||||
/// V20 добавляет `source_kind` и допускает byte-less template-публикации.
|
||||
const COLUMNS_V20: &[(&str, &str, bool)] = &[
|
||||
("workspace_id", "text", false),
|
||||
("resource_id", "text", false),
|
||||
("version", "integer", false),
|
||||
("uri", "text", false),
|
||||
("name", "text", false),
|
||||
("description", "text", false),
|
||||
("kind", "text", false),
|
||||
("mime_type", "text", false),
|
||||
("size_bytes", "bigint", false),
|
||||
("digest", "text", false),
|
||||
("sensitivity", "text", false),
|
||||
("artifact_source_id", "text", true),
|
||||
("source_kind", "text", false),
|
||||
("published_at", "timestamp with time zone", false),
|
||||
];
|
||||
|
||||
fn columns(current_version: i64) -> &'static [(&'static str, &'static str, bool)] {
|
||||
if current_version >= 20 {
|
||||
COLUMNS_V20
|
||||
} else {
|
||||
COLUMNS_V17
|
||||
}
|
||||
}
|
||||
|
||||
const DEFINITIONS: &[(&str, &str, &str, &str)] = &[
|
||||
(
|
||||
"resource_publications_pkey",
|
||||
"p",
|
||||
"v17.pkey",
|
||||
"primarykeyworkspace_id,resource_id,version",
|
||||
),
|
||||
(
|
||||
"resource_publications_resource_fkey",
|
||||
"f",
|
||||
"v17.resource_fkey",
|
||||
"foreignkeyworkspace_id,resource_idreferencesresourcesworkspace_id,resource_idondeletecascade",
|
||||
),
|
||||
(
|
||||
"resource_publications_version_fkey",
|
||||
"f",
|
||||
"v17.version_fkey",
|
||||
"foreignkeyworkspace_id,resource_id,versionreferencesresource_versionsworkspace_id,resource_id,versionondeletecascade",
|
||||
),
|
||||
(
|
||||
"resource_publications_source_fkey",
|
||||
"f",
|
||||
"v17.source_fkey",
|
||||
"foreignkeyworkspace_id,artifact_source_idreferencesartifact_sourcesworkspace_id,source_id",
|
||||
),
|
||||
];
|
||||
|
||||
const CHECK_EXPRESSIONS: &[(&str, &str, &str)] = &[
|
||||
(
|
||||
"resource_publications_version_check",
|
||||
"v17.version_check",
|
||||
"CHECK (version >= 1)",
|
||||
),
|
||||
(
|
||||
"resource_publications_uri_len_check",
|
||||
"v17.uri_len_check",
|
||||
"CHECK (octet_length(uri) >= 10 AND octet_length(uri) <= 200)",
|
||||
),
|
||||
(
|
||||
"resource_publications_name_len_check",
|
||||
"v17.name_len_check",
|
||||
"CHECK (octet_length(name) >= 1 AND octet_length(name) <= 64)",
|
||||
),
|
||||
(
|
||||
"resource_publications_description_len",
|
||||
"v17.description_len",
|
||||
"CHECK (octet_length(description) <= 1024)",
|
||||
),
|
||||
(
|
||||
"resource_publications_kind_check",
|
||||
"v17.kind_check",
|
||||
"CHECK (kind = ANY (ARRAY['text'::text, 'json'::text, 'binary'::text]))",
|
||||
),
|
||||
(
|
||||
"resource_publications_mime_type_check",
|
||||
"v17.mime_type_check",
|
||||
"CHECK (octet_length(mime_type) >= 3 AND octet_length(mime_type) <= 255 AND \
|
||||
mime_type ~ '^[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+$'::text)",
|
||||
),
|
||||
(
|
||||
"resource_publications_size_check",
|
||||
"v17.size_check",
|
||||
"CHECK (size_bytes >= 1 AND size_bytes <= 262144)",
|
||||
),
|
||||
(
|
||||
"resource_publications_digest_check",
|
||||
"v17.digest_check",
|
||||
"CHECK (digest ~ '^[0-9a-f]{64}$'::text)",
|
||||
),
|
||||
(
|
||||
"resource_publications_sensitivity_check",
|
||||
"v17.sensitivity_check",
|
||||
"CHECK (sensitivity = ANY (ARRAY['public'::text, 'internal'::text, 'secret'::text]))",
|
||||
),
|
||||
(
|
||||
"resource_publications_source_id_check",
|
||||
"v17.source_id_check",
|
||||
"CHECK (artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$'::text)",
|
||||
),
|
||||
];
|
||||
|
||||
/// V20 переопределяет два CHECK-а публикаций так же, как у версий.
|
||||
const CHECK_EXPRESSIONS_V20: &[(&str, &str, &str)] = &[
|
||||
(
|
||||
"resource_publications_size_check",
|
||||
"v17.size_check",
|
||||
"CHECK (source_kind = 'artifact'::text AND size_bytes >= 1 AND size_bytes <= 262144 \
|
||||
OR source_kind = 'template'::text AND size_bytes = 0)",
|
||||
),
|
||||
(
|
||||
"resource_publications_source_id_check",
|
||||
"v17.source_id_check",
|
||||
"CHECK (source_kind = 'artifact'::text AND artifact_source_id IS NOT NULL \
|
||||
AND artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$'::text \
|
||||
OR source_kind = 'template'::text AND artifact_source_id IS NULL)",
|
||||
),
|
||||
];
|
||||
|
||||
fn check_expectations(current_version: i64) -> Vec<(&'static str, &'static str, &'static str)> {
|
||||
CHECK_EXPRESSIONS
|
||||
.iter()
|
||||
.map(|(constraint, stage, legacy)| {
|
||||
let expected = if current_version >= 20 {
|
||||
CHECK_EXPRESSIONS_V20
|
||||
.iter()
|
||||
.find(|(name, _, _)| name == constraint)
|
||||
.map(|(_, _, expected)| *expected)
|
||||
.unwrap_or(*legacy)
|
||||
} else {
|
||||
*legacy
|
||||
};
|
||||
(*constraint, *stage, expected)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Нормализация определения CHECK: пробелы/регистр снимаются только вне строковых
|
||||
/// литералов, поэтому ослабленная маска внутри литерала (`'^[0-9a-f ]{64}$'`) и
|
||||
/// другой регистр в литерале не сливаются с каноническим выражением.
|
||||
fn normalize_guard_definition(value: &str) -> String {
|
||||
let mut normalized = String::with_capacity(value.len());
|
||||
let mut literal = false;
|
||||
let mut characters = value.chars().peekable();
|
||||
while let Some(character) = characters.next() {
|
||||
if character == '\'' {
|
||||
normalized.push(character);
|
||||
if !literal {
|
||||
literal = true;
|
||||
} else if characters.peek() == Some(&'\'') {
|
||||
if let Some(escaped) = characters.next() {
|
||||
normalized.push(escaped);
|
||||
}
|
||||
} else {
|
||||
literal = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if literal {
|
||||
normalized.push(character);
|
||||
} else if !character.is_ascii_whitespace() {
|
||||
normalized.push(character.to_ascii_lowercase());
|
||||
}
|
||||
}
|
||||
normalized
|
||||
}
|
||||
|
||||
fn v17_error(stage: &'static str) -> MigrationError {
|
||||
MigrationError::new(
|
||||
"partial_sequence",
|
||||
stage,
|
||||
Some(17),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
}
|
||||
|
||||
/// Схема V17 отсутствует целиком (для current_version < 17).
|
||||
pub(super) async fn validate_v17_absent(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<bool, MigrationError> {
|
||||
for relation in OWNED_RELATIONS {
|
||||
if relation_exists(connection, relation).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Схема V17 присутствует в ожидаемой форме (для current_version >= 17).
|
||||
pub(super) async fn validate_v17_resource_publications(
|
||||
connection: &mut PgConnection,
|
||||
current_version: i64,
|
||||
) -> Result<(), MigrationError> {
|
||||
let columns = columns(current_version);
|
||||
for relation in OWNED_RELATIONS {
|
||||
if !relation_exists(connection, relation).await? {
|
||||
return Err(v17_error("v17.relations"));
|
||||
}
|
||||
}
|
||||
let column_count: i64 = query(
|
||||
"select count(*)::bigint as count from information_schema.columns
|
||||
where table_schema = current_schema() and table_name = 'resource_publications'",
|
||||
)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.try_get("count")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
if column_count != i64::try_from(columns.len()).unwrap_or_default() {
|
||||
return Err(v17_error("v17.columns"));
|
||||
}
|
||||
for (column, data_type, nullable) in columns {
|
||||
let row = query(
|
||||
"select data_type, is_nullable from information_schema.columns
|
||||
where table_schema = current_schema() and table_name = 'resource_publications'
|
||||
and column_name = $1",
|
||||
)
|
||||
.bind(column)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let valid = row.is_some_and(|row| {
|
||||
row.try_get::<String, _>("data_type").ok().as_deref() == Some(*data_type)
|
||||
&& row.try_get::<String, _>("is_nullable").ok().as_deref()
|
||||
== Some(if *nullable { "YES" } else { "NO" })
|
||||
});
|
||||
if !valid {
|
||||
return Err(v17_error("v17.columns"));
|
||||
}
|
||||
}
|
||||
for (constraint, kind, stage, expected) in DEFINITIONS {
|
||||
let row = query(
|
||||
"select c.contype::text as kind, c.convalidated,
|
||||
pg_get_constraintdef(c.oid, true) as definition
|
||||
from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema() and t.relname = 'resource_publications'
|
||||
and c.conname = $1",
|
||||
)
|
||||
.bind(constraint)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let valid = row.is_some_and(|row| {
|
||||
row.try_get::<String, _>("kind").ok().as_deref() == Some(*kind)
|
||||
&& row.try_get::<bool, _>("convalidated").ok() == Some(true)
|
||||
&& row
|
||||
.try_get::<String, _>("definition")
|
||||
.ok()
|
||||
.is_some_and(|definition| {
|
||||
normalize_definition(&definition) == normalize_definition(expected)
|
||||
})
|
||||
});
|
||||
if !valid {
|
||||
return Err(v17_error(stage));
|
||||
}
|
||||
}
|
||||
for (constraint, stage, expected) in check_expectations(current_version) {
|
||||
let row = query(
|
||||
"select pg_get_constraintdef(c.oid, true) as definition, c.convalidated
|
||||
from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema() and t.relname = 'resource_publications'
|
||||
and c.conname = $1 and c.contype = 'c'",
|
||||
)
|
||||
.bind(constraint)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let valid = row.is_some_and(|row| {
|
||||
row.try_get::<bool, _>("convalidated").ok() == Some(true)
|
||||
&& row
|
||||
.try_get::<String, _>("definition")
|
||||
.ok()
|
||||
.is_some_and(|definition| {
|
||||
normalize_guard_definition(&definition)
|
||||
== normalize_guard_definition(expected)
|
||||
})
|
||||
});
|
||||
if !valid {
|
||||
return Err(v17_error(stage));
|
||||
}
|
||||
}
|
||||
validate_uri_index(connection).await
|
||||
}
|
||||
|
||||
async fn validate_uri_index(connection: &mut PgConnection) -> Result<(), MigrationError> {
|
||||
let row = query(
|
||||
"select t.relname as table_name, am.amname as access_method, i.indisvalid, i.indisready,
|
||||
i.indisunique, i.indnkeyatts, i.indnatts,
|
||||
pg_get_expr(i.indpred, i.indrelid) as predicate,
|
||||
pg_get_indexdef(i.indexrelid, 1, true) as first_column,
|
||||
pg_get_indexdef(i.indexrelid, 2, true) as second_column,
|
||||
pg_get_indexdef(i.indexrelid, 3, true) as third_column
|
||||
from pg_catalog.pg_index i
|
||||
join pg_catalog.pg_class idx on idx.oid = i.indexrelid
|
||||
join pg_catalog.pg_class t on t.oid = i.indrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
join pg_catalog.pg_am am on am.oid = idx.relam
|
||||
where n.nspname = current_schema()
|
||||
and idx.relname = 'resource_publications_workspace_uri_idx'",
|
||||
)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let valid = row.is_some_and(|row| {
|
||||
row.try_get::<String, _>("table_name").ok().as_deref() == Some("resource_publications")
|
||||
&& row.try_get::<String, _>("access_method").ok().as_deref() == Some("btree")
|
||||
&& row.try_get::<bool, _>("indisvalid").ok() == Some(true)
|
||||
&& row.try_get::<bool, _>("indisready").ok() == Some(true)
|
||||
&& row.try_get::<bool, _>("indisunique").ok() == Some(false)
|
||||
&& row.try_get::<i16, _>("indnkeyatts").ok() == Some(3)
|
||||
&& row.try_get::<i16, _>("indnatts").ok() == Some(3)
|
||||
&& row
|
||||
.try_get::<Option<String>, _>("predicate")
|
||||
.ok()
|
||||
.is_none_or(|value| value.is_none())
|
||||
&& row.try_get::<String, _>("first_column").ok().as_deref() == Some("workspace_id")
|
||||
&& row.try_get::<String, _>("second_column").ok().as_deref() == Some("uri")
|
||||
&& row
|
||||
.try_get::<String, _>("third_column")
|
||||
.ok()
|
||||
.is_some_and(|value| value == "published_at" || value == "published_at DESC")
|
||||
});
|
||||
if valid {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(v17_error("v17.uri_index"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
//! V18 schema guard: typed exact Resource bindings Agent (Story 3.7 AC04).
|
||||
//!
|
||||
//! Проверяет, что схема V18 либо полностью отсутствует (миграция ещё не
|
||||
//! применена), либо присутствует ровно в ожидаемой форме: отдельная таблица
|
||||
//! `agent_resource_bindings`, workspace-равенство на обоих концах composite FK,
|
||||
//! exact positive version, immutability trigger для published Agent Version и
|
||||
//! индексы адресации.
|
||||
|
||||
use sqlx::{PgConnection, Row, query};
|
||||
|
||||
use super::authority::MigrationError;
|
||||
use super::schema_guard::{normalize_definition, relation_exists};
|
||||
|
||||
/// Нормализация определения CHECK: пробелы/регистр снимаются только вне строковых
|
||||
/// литералов, поэтому ослабленная маска (`'^[0-9a-f ]{64}$'`) не сливается с
|
||||
/// каноническим выражением (тот же инвариант, что в V17 guard).
|
||||
fn normalize_guard_definition(value: &str) -> String {
|
||||
let mut normalized = String::with_capacity(value.len());
|
||||
let mut literal = false;
|
||||
let mut characters = value.chars().peekable();
|
||||
while let Some(character) = characters.next() {
|
||||
if character == '\'' {
|
||||
normalized.push(character);
|
||||
if !literal {
|
||||
literal = true;
|
||||
} else if characters.peek() == Some(&'\'') {
|
||||
if let Some(escaped) = characters.next() {
|
||||
normalized.push(escaped);
|
||||
}
|
||||
} else {
|
||||
literal = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if literal {
|
||||
normalized.push(character);
|
||||
} else if !character.is_ascii_whitespace() {
|
||||
normalized.push(character.to_ascii_lowercase());
|
||||
}
|
||||
}
|
||||
normalized
|
||||
}
|
||||
|
||||
const OWNED_RELATIONS: &[&str] = &[
|
||||
"agent_resource_bindings",
|
||||
"agent_resource_bindings_resource_idx",
|
||||
"agents_workspace_id_idx",
|
||||
];
|
||||
|
||||
const COLUMNS: &[(&str, &str, bool)] = &[
|
||||
("workspace_id", "text", false),
|
||||
("agent_id", "text", false),
|
||||
("agent_version", "integer", false),
|
||||
("resource_id", "text", false),
|
||||
("resource_version", "integer", false),
|
||||
];
|
||||
|
||||
const DEFINITIONS: &[(&str, &str, &str, &str)] = &[
|
||||
(
|
||||
"agent_resource_bindings_pkey",
|
||||
"p",
|
||||
"v18.pkey",
|
||||
"primarykeyagent_id,agent_version,resource_id,resource_version",
|
||||
),
|
||||
(
|
||||
"agent_resource_bindings_agent_workspace_fkey",
|
||||
"f",
|
||||
"v18.agent_workspace_fkey",
|
||||
"foreignkeyworkspace_id,agent_idreferencesagentsworkspace_id,idondeletecascade",
|
||||
),
|
||||
(
|
||||
"agent_resource_bindings_agent_version_fkey",
|
||||
"f",
|
||||
"v18.agent_version_fkey",
|
||||
"foreignkeyagent_id,agent_versionreferencesagent_versionsagent_id,versionondeletecascade",
|
||||
),
|
||||
(
|
||||
"agent_resource_bindings_publication_fkey",
|
||||
"f",
|
||||
"v18.publication_fkey",
|
||||
"foreignkeyworkspace_id,resource_id,resource_versionreferencesresource_publicationsworkspace_id,resource_id,versionondeletecascade",
|
||||
),
|
||||
];
|
||||
|
||||
const CHECK_EXPRESSIONS: &[(&str, &str, &str)] = &[
|
||||
(
|
||||
"agent_resource_bindings_agent_version_check",
|
||||
"v18.agent_version_check",
|
||||
"CHECK (agent_version >= 1)",
|
||||
),
|
||||
(
|
||||
"agent_resource_bindings_resource_version_check",
|
||||
"v18.resource_version_check",
|
||||
"CHECK (resource_version >= 1)",
|
||||
),
|
||||
];
|
||||
|
||||
fn v18_error(stage: &'static str) -> MigrationError {
|
||||
MigrationError::new(
|
||||
"partial_sequence",
|
||||
stage,
|
||||
Some(18),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
}
|
||||
|
||||
/// Схема V18 отсутствует целиком (для current_version < 18).
|
||||
pub(super) async fn validate_v18_absent(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<bool, MigrationError> {
|
||||
for relation in OWNED_RELATIONS {
|
||||
if relation_exists(connection, relation).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
if trigger_exists(connection).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
if guard_function_exists(connection).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Схема V18 присутствует в ожидаемой форме (для current_version >= 18).
|
||||
pub(super) async fn validate_v18_agent_resource_bindings(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<(), MigrationError> {
|
||||
for relation in OWNED_RELATIONS {
|
||||
if !relation_exists(connection, relation).await? {
|
||||
return Err(v18_error("v18.relations"));
|
||||
}
|
||||
}
|
||||
let column_count: i64 = query(
|
||||
"select count(*)::bigint as count from information_schema.columns
|
||||
where table_schema = current_schema() and table_name = 'agent_resource_bindings'",
|
||||
)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.try_get("count")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
if column_count != i64::try_from(COLUMNS.len()).unwrap_or_default() {
|
||||
return Err(v18_error("v18.columns"));
|
||||
}
|
||||
for (column, data_type, nullable) in COLUMNS {
|
||||
let row = query(
|
||||
"select data_type, is_nullable from information_schema.columns
|
||||
where table_schema = current_schema() and table_name = 'agent_resource_bindings'
|
||||
and column_name = $1",
|
||||
)
|
||||
.bind(column)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let valid = row.is_some_and(|row| {
|
||||
row.try_get::<String, _>("data_type").ok().as_deref() == Some(*data_type)
|
||||
&& row.try_get::<String, _>("is_nullable").ok().as_deref()
|
||||
== Some(if *nullable { "YES" } else { "NO" })
|
||||
});
|
||||
if !valid {
|
||||
return Err(v18_error("v18.columns"));
|
||||
}
|
||||
}
|
||||
for (constraint, kind, stage, expected) in DEFINITIONS {
|
||||
let row = query(
|
||||
"select c.contype::text as kind, c.convalidated,
|
||||
pg_get_constraintdef(c.oid, true) as definition
|
||||
from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema() and t.relname = 'agent_resource_bindings'
|
||||
and c.conname = $1",
|
||||
)
|
||||
.bind(constraint)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let valid = row.is_some_and(|row| {
|
||||
row.try_get::<String, _>("kind").ok().as_deref() == Some(*kind)
|
||||
&& row.try_get::<bool, _>("convalidated").ok() == Some(true)
|
||||
&& row
|
||||
.try_get::<String, _>("definition")
|
||||
.ok()
|
||||
.is_some_and(|definition| {
|
||||
normalize_definition(&definition) == normalize_definition(expected)
|
||||
})
|
||||
});
|
||||
if !valid {
|
||||
return Err(v18_error(stage));
|
||||
}
|
||||
}
|
||||
for (constraint, stage, expected) in CHECK_EXPRESSIONS {
|
||||
let row = query(
|
||||
"select pg_get_constraintdef(c.oid, true) as definition, c.convalidated
|
||||
from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema() and t.relname = 'agent_resource_bindings'
|
||||
and c.conname = $1 and c.contype = 'c'",
|
||||
)
|
||||
.bind(constraint)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let valid = row.is_some_and(|row| {
|
||||
row.try_get::<bool, _>("convalidated").ok() == Some(true)
|
||||
&& row
|
||||
.try_get::<String, _>("definition")
|
||||
.ok()
|
||||
.is_some_and(|definition| {
|
||||
normalize_guard_definition(&definition)
|
||||
== normalize_guard_definition(expected)
|
||||
})
|
||||
});
|
||||
if !valid {
|
||||
return Err(v18_error(stage));
|
||||
}
|
||||
}
|
||||
if !trigger_exists(connection).await? {
|
||||
return Err(v18_error("v18.immutable_trigger"));
|
||||
}
|
||||
validate_agent_workspace_index(connection).await?;
|
||||
validate_resource_index(connection).await
|
||||
}
|
||||
|
||||
async fn trigger_exists(connection: &mut PgConnection) -> Result<bool, MigrationError> {
|
||||
query(
|
||||
"select exists (
|
||||
select 1 from pg_catalog.pg_trigger tg
|
||||
join pg_catalog.pg_class t on t.oid = tg.tgrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
join pg_catalog.pg_proc p on p.oid = tg.tgfoid
|
||||
where n.nspname = current_schema()
|
||||
and t.relname = 'agent_resource_bindings'
|
||||
and tg.tgname = 'agent_resource_bindings_immutable_guard'
|
||||
and p.proname = 'crank_reject_published_agent_resource_binding_mutation'
|
||||
and not tg.tgisinternal
|
||||
) as present",
|
||||
)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.try_get::<bool, _>("present")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))
|
||||
}
|
||||
|
||||
async fn guard_function_exists(connection: &mut PgConnection) -> Result<bool, MigrationError> {
|
||||
query(
|
||||
"select exists (
|
||||
select 1 from pg_catalog.pg_proc p
|
||||
join pg_catalog.pg_namespace n on n.oid = p.pronamespace
|
||||
where n.nspname = current_schema()
|
||||
and p.proname = 'crank_reject_published_agent_resource_binding_mutation'
|
||||
) as present",
|
||||
)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.try_get::<bool, _>("present")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))
|
||||
}
|
||||
|
||||
async fn validate_agent_workspace_index(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<(), MigrationError> {
|
||||
let row = query(
|
||||
"select t.relname as table_name, am.amname as access_method, i.indisvalid,
|
||||
i.indisready, i.indisunique, i.indnkeyatts,
|
||||
pg_get_indexdef(i.indexrelid, 1, true) as first_column,
|
||||
pg_get_indexdef(i.indexrelid, 2, true) as second_column
|
||||
from pg_catalog.pg_index i
|
||||
join pg_catalog.pg_class idx on idx.oid = i.indexrelid
|
||||
join pg_catalog.pg_class t on t.oid = i.indrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
join pg_catalog.pg_am am on am.oid = idx.relam
|
||||
where n.nspname = current_schema() and idx.relname = 'agents_workspace_id_idx'",
|
||||
)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let valid = row.is_some_and(|row| {
|
||||
row.try_get::<String, _>("table_name").ok().as_deref() == Some("agents")
|
||||
&& row.try_get::<String, _>("access_method").ok().as_deref() == Some("btree")
|
||||
&& row.try_get::<bool, _>("indisvalid").ok() == Some(true)
|
||||
&& row.try_get::<bool, _>("indisready").ok() == Some(true)
|
||||
&& row.try_get::<bool, _>("indisunique").ok() == Some(true)
|
||||
&& row.try_get::<i16, _>("indnkeyatts").ok() == Some(2)
|
||||
&& row.try_get::<String, _>("first_column").ok().as_deref() == Some("workspace_id")
|
||||
&& row.try_get::<String, _>("second_column").ok().as_deref() == Some("id")
|
||||
});
|
||||
if valid {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(v18_error("v18.agents_workspace_index"))
|
||||
}
|
||||
}
|
||||
|
||||
async fn validate_resource_index(connection: &mut PgConnection) -> Result<(), MigrationError> {
|
||||
let row = query(
|
||||
"select t.relname as table_name, am.amname as access_method, i.indisvalid,
|
||||
i.indisready, i.indisunique, i.indnkeyatts,
|
||||
pg_get_indexdef(i.indexrelid, 1, true) as first_column,
|
||||
pg_get_indexdef(i.indexrelid, 2, true) as second_column,
|
||||
pg_get_indexdef(i.indexrelid, 3, true) as third_column
|
||||
from pg_catalog.pg_index i
|
||||
join pg_catalog.pg_class idx on idx.oid = i.indexrelid
|
||||
join pg_catalog.pg_class t on t.oid = i.indrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
join pg_catalog.pg_am am on am.oid = idx.relam
|
||||
where n.nspname = current_schema()
|
||||
and idx.relname = 'agent_resource_bindings_resource_idx'",
|
||||
)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let valid = row.is_some_and(|row| {
|
||||
row.try_get::<String, _>("table_name").ok().as_deref() == Some("agent_resource_bindings")
|
||||
&& row.try_get::<String, _>("access_method").ok().as_deref() == Some("btree")
|
||||
&& row.try_get::<bool, _>("indisvalid").ok() == Some(true)
|
||||
&& row.try_get::<bool, _>("indisready").ok() == Some(true)
|
||||
&& row.try_get::<bool, _>("indisunique").ok() == Some(false)
|
||||
&& row.try_get::<i16, _>("indnkeyatts").ok() == Some(3)
|
||||
&& row.try_get::<String, _>("first_column").ok().as_deref() == Some("workspace_id")
|
||||
&& row.try_get::<String, _>("second_column").ok().as_deref() == Some("resource_id")
|
||||
&& row.try_get::<String, _>("third_column").ok().as_deref() == Some("resource_version")
|
||||
});
|
||||
if valid {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(v18_error("v18.resource_index"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
//! V19 schema guard: immutable Resource security revocation tombstones (Story 3.8).
|
||||
//!
|
||||
//! Проверяет, что схема V19 либо полностью отсутствует (миграция ещё не
|
||||
//! применена), либо присутствует ровно в ожидаемой форме: одна таблица
|
||||
//! `resource_security_revocations` с составным PK, FK на `resources` и `users`
|
||||
//! без каскадного удаления и trigger неизменяемости. Bounded request/trace
|
||||
//! значения задаются серверными типами (`RequestId`/`TraceContext`), а не
|
||||
//! пользовательским вводом.
|
||||
|
||||
use sqlx::{PgConnection, Row, query};
|
||||
|
||||
use super::authority::MigrationError;
|
||||
use super::schema_guard::{normalize_definition, relation_exists};
|
||||
|
||||
const OWNED_RELATIONS: &[&str] = &["resource_security_revocations"];
|
||||
|
||||
const COLUMNS: &[(&str, &str, bool)] = &[
|
||||
("workspace_id", "text", false),
|
||||
("resource_id", "text", false),
|
||||
("revoked_at", "timestamp with time zone", false),
|
||||
("actor_user_id", "text", false),
|
||||
("request_id", "text", false),
|
||||
("trace_id", "text", false),
|
||||
];
|
||||
|
||||
const DEFINITIONS: &[(&str, &str, &str, &str)] = &[
|
||||
(
|
||||
"resource_security_revocations_pkey",
|
||||
"p",
|
||||
"v19.pkey",
|
||||
"primary key (workspace_id, resource_id)",
|
||||
),
|
||||
(
|
||||
"resource_security_revocations_resource_fkey",
|
||||
"f",
|
||||
"v19.resource_fkey",
|
||||
"foreign key (workspace_id, resource_id)
|
||||
references resources(workspace_id, resource_id) on delete restrict",
|
||||
),
|
||||
(
|
||||
"resource_security_revocations_actor_fkey",
|
||||
"f",
|
||||
"v19.actor_fkey",
|
||||
"foreign key (actor_user_id) references users(id) on delete restrict",
|
||||
),
|
||||
];
|
||||
|
||||
fn v19_error(stage: &'static str) -> MigrationError {
|
||||
MigrationError::new(
|
||||
"partial_sequence",
|
||||
stage,
|
||||
Some(19),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
}
|
||||
|
||||
/// Схема V19 отсутствует целиком (для current_version < 19).
|
||||
pub(super) async fn validate_v19_absent(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<bool, MigrationError> {
|
||||
for relation in OWNED_RELATIONS {
|
||||
if relation_exists(connection, relation).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
if guard_function_exists(connection).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
Ok(!trigger_exists(connection).await?)
|
||||
}
|
||||
|
||||
/// Схема V19 присутствует в ожидаемой форме (для current_version >= 19).
|
||||
pub(super) async fn validate_v19_resource_security_revocations(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<(), MigrationError> {
|
||||
for relation in OWNED_RELATIONS {
|
||||
if !relation_exists(connection, relation).await? {
|
||||
return Err(v19_error("v19.relations"));
|
||||
}
|
||||
}
|
||||
let column_count: i64 = query(
|
||||
"select count(*)::bigint as count from information_schema.columns
|
||||
where table_schema = current_schema() and table_name = 'resource_security_revocations'",
|
||||
)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.try_get("count")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
if column_count != i64::try_from(COLUMNS.len()).unwrap_or_default() {
|
||||
return Err(v19_error("v19.columns"));
|
||||
}
|
||||
for (column, data_type, nullable) in COLUMNS {
|
||||
let row = query(
|
||||
"select data_type, is_nullable from information_schema.columns
|
||||
where table_schema = current_schema() and table_name = 'resource_security_revocations'
|
||||
and column_name = $1",
|
||||
)
|
||||
.bind(column)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let valid = row.is_some_and(|row| {
|
||||
row.try_get::<String, _>("data_type").ok().as_deref() == Some(*data_type)
|
||||
&& row.try_get::<String, _>("is_nullable").ok().as_deref()
|
||||
== Some(if *nullable { "YES" } else { "NO" })
|
||||
});
|
||||
if !valid {
|
||||
return Err(v19_error("v19.columns"));
|
||||
}
|
||||
}
|
||||
for (constraint, kind, stage, expected) in DEFINITIONS {
|
||||
let row = query(
|
||||
"select c.contype::text as kind, c.convalidated,
|
||||
pg_get_constraintdef(c.oid, true) as definition
|
||||
from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and t.relname = 'resource_security_revocations'
|
||||
and c.conname = $1",
|
||||
)
|
||||
.bind(constraint)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let valid = row.is_some_and(|row| {
|
||||
row.try_get::<String, _>("kind").ok().as_deref() == Some(*kind)
|
||||
&& row.try_get::<bool, _>("convalidated").ok() == Some(true)
|
||||
&& row
|
||||
.try_get::<String, _>("definition")
|
||||
.ok()
|
||||
.is_some_and(|definition| {
|
||||
normalize_definition(&definition) == normalize_definition(expected)
|
||||
})
|
||||
});
|
||||
if !valid {
|
||||
return Err(v19_error(stage));
|
||||
}
|
||||
}
|
||||
if !trigger_exists(connection).await? {
|
||||
return Err(v19_error("v19.immutable_trigger"));
|
||||
}
|
||||
if !guard_function_exists(connection).await? {
|
||||
return Err(v19_error("v19.immutable_trigger"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn trigger_exists(connection: &mut PgConnection) -> Result<bool, MigrationError> {
|
||||
query(
|
||||
"select exists (
|
||||
select 1 from pg_catalog.pg_trigger tg
|
||||
join pg_catalog.pg_class t on t.oid = tg.tgrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
join pg_catalog.pg_proc p on p.oid = tg.tgfoid
|
||||
where n.nspname = current_schema()
|
||||
and t.relname = 'resource_security_revocations'
|
||||
and tg.tgname = 'resource_security_revocations_immutable_guard'
|
||||
and p.proname = 'crank_reject_resource_security_revocation_mutation'
|
||||
and not tg.tgisinternal
|
||||
) as present",
|
||||
)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.try_get::<bool, _>("present")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))
|
||||
}
|
||||
|
||||
async fn guard_function_exists(connection: &mut PgConnection) -> Result<bool, MigrationError> {
|
||||
query(
|
||||
"select exists (
|
||||
select 1 from pg_catalog.pg_proc p
|
||||
join pg_catalog.pg_namespace n on n.oid = p.pronamespace
|
||||
where n.nspname = current_schema()
|
||||
and p.proname = 'crank_reject_resource_security_revocation_mutation'
|
||||
) as present",
|
||||
)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.try_get::<bool, _>("present")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
//! V20 schema guard: byte-less REST-backed Resource template sources (Story 3.10).
|
||||
//!
|
||||
//! Схема V20 либо полностью отсутствует (миграция ещё не применена), либо
|
||||
//! присутствует ровно в ожидаемой форме: `resource_template_sources` с
|
||||
//! version-keyed PK/FK на версию, insert-only trigger, а в `resource_versions` и
|
||||
//! `resource_publications` — `source_kind` и CHECK-и, которые допускают byte-less
|
||||
//! template-строки, сохраняя прежние ограничения artifact-строк.
|
||||
|
||||
use sqlx::{PgConnection, Row, query};
|
||||
|
||||
use super::authority::MigrationError;
|
||||
use super::schema_guard::{normalize_definition, relation_exists};
|
||||
|
||||
const OWNED_RELATIONS: &[&str] = &["resource_template_sources"];
|
||||
|
||||
const COLUMNS: &[(&str, &str, bool)] = &[
|
||||
("workspace_id", "text", false),
|
||||
("resource_id", "text", false),
|
||||
("version", "integer", false),
|
||||
("definition_json", "text", false),
|
||||
("definition_digest", "text", false),
|
||||
("created_at", "timestamp with time zone", false),
|
||||
];
|
||||
|
||||
const DEFINITIONS: &[(&str, &str, &str, &str)] = &[
|
||||
(
|
||||
"resource_template_sources_pkey",
|
||||
"p",
|
||||
"v20.pkey",
|
||||
"primary key (workspace_id, resource_id, version)",
|
||||
),
|
||||
(
|
||||
"resource_template_sources_version_fkey",
|
||||
"f",
|
||||
"v20.version_fkey",
|
||||
"foreign key (workspace_id, resource_id, version)
|
||||
references resource_versions(workspace_id, resource_id, version)
|
||||
on delete cascade",
|
||||
),
|
||||
];
|
||||
|
||||
const CHECK_EXPRESSIONS: &[(&str, &str, &str)] = &[
|
||||
(
|
||||
"resource_template_sources_version_check",
|
||||
"v20.version_check",
|
||||
"CHECK (version >= 1)",
|
||||
),
|
||||
(
|
||||
"resource_template_sources_definition_len_check",
|
||||
"v20.definition_len_check",
|
||||
"CHECK (octet_length(definition_json) >= 2 AND octet_length(definition_json) <= 65536)",
|
||||
),
|
||||
(
|
||||
"resource_template_sources_digest_check",
|
||||
"v20.digest_check",
|
||||
"CHECK (definition_digest ~ '^[0-9a-f]{64}$'::text)",
|
||||
),
|
||||
(
|
||||
"resource_versions_source_kind_check",
|
||||
"v20.version_source_kind_check",
|
||||
"CHECK (source_kind = ANY (ARRAY['artifact'::text, 'template'::text]))",
|
||||
),
|
||||
(
|
||||
"resource_publications_source_kind_check",
|
||||
"v20.publication_source_kind_check",
|
||||
"CHECK (source_kind = ANY (ARRAY['artifact'::text, 'template'::text]))",
|
||||
),
|
||||
];
|
||||
|
||||
fn v20_error(stage: &'static str) -> MigrationError {
|
||||
MigrationError::new(
|
||||
"partial_sequence",
|
||||
stage,
|
||||
Some(20),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
}
|
||||
|
||||
/// Схема V20 отсутствует целиком (для current_version < 20).
|
||||
pub(super) async fn validate_v20_absent(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<bool, MigrationError> {
|
||||
for relation in OWNED_RELATIONS {
|
||||
if relation_exists(connection, relation).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
if guard_function_exists(connection).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
if trigger_exists(connection).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
for (table, column) in [
|
||||
("resource_versions", "source_kind"),
|
||||
("resource_publications", "source_kind"),
|
||||
] {
|
||||
if column_exists(connection, table, column).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Схема V20 присутствует в ожидаемой форме (для current_version >= 20).
|
||||
pub(super) async fn validate_v20_resource_template_sources(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<(), MigrationError> {
|
||||
if !relation_exists(connection, "resource_template_sources").await? {
|
||||
return Err(v20_error("v20.relations"));
|
||||
}
|
||||
let column_count: i64 = query(
|
||||
"select count(*)::bigint as count from information_schema.columns
|
||||
where table_schema = current_schema() and table_name = 'resource_template_sources'",
|
||||
)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.try_get("count")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
if column_count != i64::try_from(COLUMNS.len()).unwrap_or_default() {
|
||||
return Err(v20_error("v20.columns"));
|
||||
}
|
||||
for (column, data_type, nullable) in COLUMNS {
|
||||
let row = query(
|
||||
"select data_type, is_nullable from information_schema.columns
|
||||
where table_schema = current_schema() and table_name = 'resource_template_sources'
|
||||
and column_name = $1",
|
||||
)
|
||||
.bind(column)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let valid = row.is_some_and(|row| {
|
||||
row.try_get::<String, _>("data_type").ok().as_deref() == Some(*data_type)
|
||||
&& row.try_get::<String, _>("is_nullable").ok().as_deref()
|
||||
== Some(if *nullable { "YES" } else { "NO" })
|
||||
});
|
||||
if !valid {
|
||||
return Err(v20_error("v20.columns"));
|
||||
}
|
||||
}
|
||||
// `source_kind` добавлен в обе существующие resource-таблицы: template-строки
|
||||
// без него неотличимы от artifact-строк, поэтому его форма обязательна.
|
||||
for table in ["resource_versions", "resource_publications"] {
|
||||
let row = query(
|
||||
"select data_type, is_nullable from information_schema.columns
|
||||
where table_schema = current_schema() and table_name = $1
|
||||
and column_name = 'source_kind'",
|
||||
)
|
||||
.bind(table)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let valid = row.is_some_and(|row| {
|
||||
row.try_get::<String, _>("data_type").ok().as_deref() == Some("text")
|
||||
&& row.try_get::<String, _>("is_nullable").ok().as_deref() == Some("NO")
|
||||
});
|
||||
if !valid {
|
||||
return Err(v20_error("v20.source_kind"));
|
||||
}
|
||||
}
|
||||
for (constraint, kind, stage, expected) in DEFINITIONS {
|
||||
if !constraint_matches(
|
||||
connection,
|
||||
"resource_template_sources",
|
||||
constraint,
|
||||
kind,
|
||||
expected,
|
||||
)
|
||||
.await?
|
||||
{
|
||||
return Err(v20_error(stage));
|
||||
}
|
||||
}
|
||||
for (constraint, stage, expected) in CHECK_EXPRESSIONS {
|
||||
let table = if constraint.starts_with("resource_template_sources") {
|
||||
"resource_template_sources"
|
||||
} else if constraint.starts_with("resource_versions") {
|
||||
"resource_versions"
|
||||
} else {
|
||||
"resource_publications"
|
||||
};
|
||||
if !check_matches(connection, table, constraint, expected).await? {
|
||||
return Err(v20_error(stage));
|
||||
}
|
||||
}
|
||||
if !trigger_exists(connection).await? {
|
||||
return Err(v20_error("v20.immutable_trigger"));
|
||||
}
|
||||
if !guard_function_exists(connection).await? {
|
||||
return Err(v20_error("v20.immutable_trigger"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn constraint_matches(
|
||||
connection: &mut PgConnection,
|
||||
table: &str,
|
||||
constraint: &str,
|
||||
kind: &str,
|
||||
expected: &str,
|
||||
) -> Result<bool, MigrationError> {
|
||||
let row = query(
|
||||
"select c.contype::text as kind, c.convalidated,
|
||||
pg_get_constraintdef(c.oid, true) as definition
|
||||
from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema() and t.relname = $1 and c.conname = $2",
|
||||
)
|
||||
.bind(table)
|
||||
.bind(constraint)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
Ok(row.is_some_and(|row| {
|
||||
row.try_get::<String, _>("kind").ok().as_deref() == Some(kind)
|
||||
&& row.try_get::<bool, _>("convalidated").ok() == Some(true)
|
||||
&& row
|
||||
.try_get::<String, _>("definition")
|
||||
.ok()
|
||||
.is_some_and(|definition| {
|
||||
normalize_definition(&definition) == normalize_definition(expected)
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
async fn check_matches(
|
||||
connection: &mut PgConnection,
|
||||
table: &str,
|
||||
constraint: &str,
|
||||
expected: &str,
|
||||
) -> Result<bool, MigrationError> {
|
||||
constraint_matches(connection, table, constraint, "c", expected).await
|
||||
}
|
||||
|
||||
async fn column_exists(
|
||||
connection: &mut PgConnection,
|
||||
table: &str,
|
||||
column: &str,
|
||||
) -> Result<bool, MigrationError> {
|
||||
query(
|
||||
"select exists (
|
||||
select 1 from information_schema.columns
|
||||
where table_schema = current_schema() and table_name = $1 and column_name = $2
|
||||
) as present",
|
||||
)
|
||||
.bind(table)
|
||||
.bind(column)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.try_get::<bool, _>("present")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))
|
||||
}
|
||||
|
||||
async fn trigger_exists(connection: &mut PgConnection) -> Result<bool, MigrationError> {
|
||||
query(
|
||||
"select exists (
|
||||
select 1 from pg_catalog.pg_trigger tg
|
||||
join pg_catalog.pg_class t on t.oid = tg.tgrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
join pg_catalog.pg_proc p on p.oid = tg.tgfoid
|
||||
where n.nspname = current_schema()
|
||||
and t.relname = 'resource_template_sources'
|
||||
and tg.tgname = 'crank_guard_resource_template_source_immutable'
|
||||
and p.proname = 'crank_guard_resource_template_source_immutable'
|
||||
and not tg.tgisinternal
|
||||
) as present",
|
||||
)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.try_get::<bool, _>("present")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))
|
||||
}
|
||||
|
||||
async fn guard_function_exists(connection: &mut PgConnection) -> Result<bool, MigrationError> {
|
||||
query(
|
||||
"select exists (
|
||||
select 1 from pg_catalog.pg_proc p
|
||||
join pg_catalog.pg_namespace n on n.oid = p.pronamespace
|
||||
where n.nspname = current_schema()
|
||||
and p.proname = 'crank_guard_resource_template_source_immutable'
|
||||
) as present",
|
||||
)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.try_get::<bool, _>("present")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
//! V22 schema guard: immutable Published Prompt Versions и typed exact Prompt
|
||||
//! bindings Agent (Story 3.13, FR-17).
|
||||
//!
|
||||
//! Схема V22 либо полностью отсутствует (миграция ещё не применена), либо
|
||||
//! присутствует ровно в ожидаемой форме: `prompt_publications` с composite PK/FK,
|
||||
//! `agent_prompt_bindings` с workspace-safe FK на обоих концах, nullable
|
||||
//! `prompts.latest_published_version` и guard-триггеры неизменяемости
|
||||
//! опубликованной definition/публикации и bindings опубликованного Agent.
|
||||
|
||||
use sqlx::{PgConnection, Row, query};
|
||||
|
||||
use super::authority::MigrationError;
|
||||
use super::schema_guard::{normalize_definition, relation_exists};
|
||||
|
||||
const PUBLICATION: &str = "prompt_publications";
|
||||
const BINDINGS: &str = "agent_prompt_bindings";
|
||||
|
||||
const OWNED_RELATIONS: &[&str] = &[PUBLICATION, BINDINGS];
|
||||
|
||||
const PUBLICATION_COLUMNS: &[(&str, &str, bool)] = &[
|
||||
("workspace_id", "text", false),
|
||||
("prompt_id", "text", false),
|
||||
("version", "integer", false),
|
||||
("name", "text", false),
|
||||
("description", "text", false),
|
||||
("sensitivity", "text", false),
|
||||
("published_at", "timestamp with time zone", false),
|
||||
];
|
||||
|
||||
const BINDING_COLUMNS: &[(&str, &str, bool)] = &[
|
||||
("workspace_id", "text", false),
|
||||
("agent_id", "text", false),
|
||||
("agent_version", "integer", false),
|
||||
("prompt_id", "text", false),
|
||||
("prompt_version", "integer", false),
|
||||
];
|
||||
|
||||
const DEFINITIONS: &[(&str, &str, &str, &str, &str)] = &[
|
||||
(
|
||||
PUBLICATION,
|
||||
"prompt_publications_pkey",
|
||||
"p",
|
||||
"v22.publication_pkey",
|
||||
"primary key (workspace_id, prompt_id, version)",
|
||||
),
|
||||
(
|
||||
PUBLICATION,
|
||||
"prompt_publications_prompt_fkey",
|
||||
"f",
|
||||
"v22.publication_prompt_fkey",
|
||||
"foreign key (workspace_id, prompt_id) references prompts(workspace_id, prompt_id) on delete cascade",
|
||||
),
|
||||
(
|
||||
PUBLICATION,
|
||||
"prompt_publications_version_fkey",
|
||||
"f",
|
||||
"v22.publication_version_fkey",
|
||||
"foreign key (workspace_id, prompt_id, version)
|
||||
references prompt_versions(workspace_id, prompt_id, version) on delete cascade",
|
||||
),
|
||||
(
|
||||
BINDINGS,
|
||||
"agent_prompt_bindings_pkey",
|
||||
"p",
|
||||
"v22.binding_pkey",
|
||||
"primary key (agent_id, agent_version, prompt_id)",
|
||||
),
|
||||
(
|
||||
BINDINGS,
|
||||
"agent_prompt_bindings_agent_workspace_fkey",
|
||||
"f",
|
||||
"v22.binding_agent_workspace_fkey",
|
||||
"foreign key (workspace_id, agent_id) references agents(workspace_id, id) on delete cascade",
|
||||
),
|
||||
(
|
||||
BINDINGS,
|
||||
"agent_prompt_bindings_agent_version_fkey",
|
||||
"f",
|
||||
"v22.binding_agent_version_fkey",
|
||||
"foreign key (agent_id, agent_version)
|
||||
references agent_versions(agent_id, version) on delete cascade",
|
||||
),
|
||||
(
|
||||
BINDINGS,
|
||||
"agent_prompt_bindings_publication_fkey",
|
||||
"f",
|
||||
"v22.binding_publication_fkey",
|
||||
"foreign key (workspace_id, prompt_id, prompt_version)
|
||||
references prompt_publications(workspace_id, prompt_id, version) on delete cascade",
|
||||
),
|
||||
];
|
||||
|
||||
const TRIGGERS: &[(&str, &str, &str)] = &[
|
||||
(
|
||||
"prompt_arguments",
|
||||
"prompt_arguments_immutable_guard",
|
||||
"crank_reject_published_prompt_version_mutation",
|
||||
),
|
||||
(
|
||||
"prompt_messages",
|
||||
"prompt_messages_immutable_guard",
|
||||
"crank_reject_published_prompt_version_mutation",
|
||||
),
|
||||
(
|
||||
PUBLICATION,
|
||||
"prompt_publications_immutable_guard",
|
||||
"crank_reject_prompt_publication_mutation",
|
||||
),
|
||||
(
|
||||
BINDINGS,
|
||||
"agent_prompt_bindings_immutable_guard",
|
||||
"crank_reject_published_agent_prompt_binding_mutation",
|
||||
),
|
||||
];
|
||||
|
||||
fn v22_error(stage: &'static str) -> MigrationError {
|
||||
MigrationError::new(
|
||||
"partial_sequence",
|
||||
stage,
|
||||
Some(22),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
}
|
||||
|
||||
/// Схема V22 отсутствует целиком (для current_version < 22).
|
||||
pub(super) async fn validate_v22_absent(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<bool, MigrationError> {
|
||||
for relation in OWNED_RELATIONS {
|
||||
if relation_exists(connection, relation).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
if super::schema_guard::column_exists(connection, "prompts", "latest_published_version").await?
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
for (_, _, function) in TRIGGERS {
|
||||
if function_exists(connection, function).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Схема V22 присутствует в ожидаемой форме (для current_version >= 22).
|
||||
pub(super) async fn validate_v22_prompt_publications(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<(), MigrationError> {
|
||||
for relation in OWNED_RELATIONS {
|
||||
if !relation_exists(connection, relation).await? {
|
||||
return Err(v22_error("v22.relations"));
|
||||
}
|
||||
}
|
||||
if !super::schema_guard::column_exists(connection, "prompts", "latest_published_version")
|
||||
.await?
|
||||
{
|
||||
return Err(v22_error("v22.prompt_columns"));
|
||||
}
|
||||
for (table, columns) in [
|
||||
(PUBLICATION, PUBLICATION_COLUMNS),
|
||||
(BINDINGS, BINDING_COLUMNS),
|
||||
] {
|
||||
validate_columns(connection, table, columns).await?;
|
||||
}
|
||||
for (table, constraint, kind, stage, expected) in DEFINITIONS {
|
||||
if !constraint_matches(connection, table, constraint, kind, expected).await? {
|
||||
return Err(v22_error(stage));
|
||||
}
|
||||
}
|
||||
for (table, trigger, function) in TRIGGERS {
|
||||
if !trigger_exists(connection, table, trigger, function).await? {
|
||||
return Err(v22_error("v22.immutable_trigger"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn validate_columns(
|
||||
connection: &mut PgConnection,
|
||||
table: &str,
|
||||
columns: &[(&str, &str, bool)],
|
||||
) -> Result<(), MigrationError> {
|
||||
let column_count: i64 = query(
|
||||
"select count(*)::bigint as count from information_schema.columns
|
||||
where table_schema = current_schema() and table_name = $1",
|
||||
)
|
||||
.bind(table)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.try_get("count")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
if column_count != i64::try_from(columns.len()).unwrap_or_default() {
|
||||
return Err(v22_error("v22.columns"));
|
||||
}
|
||||
for (column, data_type, nullable) in columns {
|
||||
let row = query(
|
||||
"select data_type, is_nullable from information_schema.columns
|
||||
where table_schema = current_schema() and table_name = $1 and column_name = $2",
|
||||
)
|
||||
.bind(table)
|
||||
.bind(column)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let valid = row.is_some_and(|row| {
|
||||
row.try_get::<String, _>("data_type").ok().as_deref() == Some(*data_type)
|
||||
&& row.try_get::<String, _>("is_nullable").ok().as_deref()
|
||||
== Some(if *nullable { "YES" } else { "NO" })
|
||||
});
|
||||
if !valid {
|
||||
return Err(v22_error("v22.columns"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn constraint_matches(
|
||||
connection: &mut PgConnection,
|
||||
table: &str,
|
||||
constraint: &str,
|
||||
kind: &str,
|
||||
expected: &str,
|
||||
) -> Result<bool, MigrationError> {
|
||||
let row = query(
|
||||
"select c.contype::text as kind, c.convalidated,
|
||||
pg_get_constraintdef(c.oid, true) as definition
|
||||
from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and t.relname = $1
|
||||
and c.conname = $2",
|
||||
)
|
||||
.bind(table)
|
||||
.bind(constraint)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
Ok(row.is_some_and(|row| {
|
||||
row.try_get::<String, _>("kind").ok().as_deref() == Some(kind)
|
||||
&& row.try_get::<bool, _>("convalidated").ok() == Some(true)
|
||||
&& row
|
||||
.try_get::<String, _>("definition")
|
||||
.ok()
|
||||
.is_some_and(|definition| {
|
||||
normalize_definition(&definition) == normalize_definition(expected)
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
async fn trigger_exists(
|
||||
connection: &mut PgConnection,
|
||||
table: &str,
|
||||
trigger: &str,
|
||||
function: &str,
|
||||
) -> Result<bool, MigrationError> {
|
||||
query(
|
||||
"select exists (
|
||||
select 1 from pg_catalog.pg_trigger tg
|
||||
join pg_catalog.pg_class t on t.oid = tg.tgrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
join pg_catalog.pg_proc p on p.oid = tg.tgfoid
|
||||
where n.nspname = current_schema()
|
||||
and t.relname = $1
|
||||
and tg.tgname = $2
|
||||
and p.proname = $3
|
||||
and not tg.tgisinternal
|
||||
) as present",
|
||||
)
|
||||
.bind(table)
|
||||
.bind(trigger)
|
||||
.bind(function)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.try_get::<bool, _>("present")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))
|
||||
}
|
||||
|
||||
async fn function_exists(
|
||||
connection: &mut PgConnection,
|
||||
function: &str,
|
||||
) -> Result<bool, MigrationError> {
|
||||
query(
|
||||
"select exists (
|
||||
select 1 from pg_catalog.pg_proc p
|
||||
join pg_catalog.pg_namespace n on n.oid = p.pronamespace
|
||||
where n.nspname = current_schema() and p.proname = $1
|
||||
) as present",
|
||||
)
|
||||
.bind(function)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.try_get::<bool, _>("present")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
//! V23 schema guard: version-keyed pinned Prompt dependencies (Story 3.16, FR-18).
|
||||
//!
|
||||
//! Схема V23 либо полностью отсутствует (миграция ещё не применена), либо присутствует ровно в
|
||||
//! ожидаемой форме: `prompt_dependencies` с composite PK/FK на `prompt_versions`,
|
||||
//! `prompt_message_resource_refs` с упорядоченными точками вставки и guard-триггеры
|
||||
//! неизменяемости опубликованной версии на обеих таблицах.
|
||||
|
||||
use sqlx::{PgConnection, Row, query};
|
||||
|
||||
use super::authority::MigrationError;
|
||||
use super::schema_guard::{normalize_definition, relation_exists};
|
||||
|
||||
const DEPENDENCIES: &str = "prompt_dependencies";
|
||||
const RESOURCE_REFS: &str = "prompt_message_resource_refs";
|
||||
const GUARD_FUNCTION: &str = "crank_reject_published_prompt_version_mutation";
|
||||
|
||||
const OWNED_RELATIONS: &[&str] = &[DEPENDENCIES, RESOURCE_REFS];
|
||||
|
||||
const DEPENDENCY_COLUMNS: &[(&str, &str, bool)] = &[
|
||||
("workspace_id", "text", false),
|
||||
("prompt_id", "text", false),
|
||||
("version", "integer", false),
|
||||
("dependency_position", "integer", false),
|
||||
("resource_id", "text", false),
|
||||
("resource_version", "integer", false),
|
||||
("digest", "text", false),
|
||||
("kind", "text", false),
|
||||
("mime_type", "text", false),
|
||||
("source_class", "text", false),
|
||||
("sensitivity", "text", false),
|
||||
];
|
||||
|
||||
const REF_COLUMNS: &[(&str, &str, bool)] = &[
|
||||
("workspace_id", "text", false),
|
||||
("prompt_id", "text", false),
|
||||
("version", "integer", false),
|
||||
("message_position", "integer", false),
|
||||
("ref_position", "integer", false),
|
||||
("dependency_position", "integer", false),
|
||||
];
|
||||
|
||||
const DEFINITIONS: &[(&str, &str, &str, &str, &str)] = &[
|
||||
(
|
||||
DEPENDENCIES,
|
||||
"prompt_dependencies_pkey",
|
||||
"p",
|
||||
"v23.dependencies_pkey",
|
||||
"primary key (workspace_id, prompt_id, version, dependency_position)",
|
||||
),
|
||||
(
|
||||
DEPENDENCIES,
|
||||
"prompt_dependencies_version_fkey",
|
||||
"f",
|
||||
"v23.dependencies_version_fkey",
|
||||
"foreign key (workspace_id, prompt_id, version)
|
||||
references prompt_versions(workspace_id, prompt_id, version) on delete cascade",
|
||||
),
|
||||
(
|
||||
RESOURCE_REFS,
|
||||
"prompt_message_resource_refs_pkey",
|
||||
"p",
|
||||
"v23.refs_pkey",
|
||||
"primary key (workspace_id, prompt_id, version, message_position, ref_position)",
|
||||
),
|
||||
(
|
||||
RESOURCE_REFS,
|
||||
"prompt_message_resource_refs_version_fkey",
|
||||
"f",
|
||||
"v23.refs_version_fkey",
|
||||
"foreign key (workspace_id, prompt_id, version)
|
||||
references prompt_versions(workspace_id, prompt_id, version) on delete cascade",
|
||||
),
|
||||
];
|
||||
|
||||
fn v23_error(stage: &'static str) -> MigrationError {
|
||||
MigrationError::new(
|
||||
"partial_sequence",
|
||||
stage,
|
||||
Some(23),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
}
|
||||
|
||||
/// Схема V23 отсутствует целиком (для current_version < 23).
|
||||
pub(super) async fn validate_v23_absent(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<bool, MigrationError> {
|
||||
for relation in OWNED_RELATIONS {
|
||||
if relation_exists(connection, relation).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
if trigger_exists(
|
||||
connection,
|
||||
DEPENDENCIES,
|
||||
"prompt_dependencies_immutable_guard",
|
||||
)
|
||||
.await?
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Схема V23 присутствует в ожидаемой форме (для current_version >= 23).
|
||||
pub(super) async fn validate_v23_prompt_dependencies(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<(), MigrationError> {
|
||||
for relation in OWNED_RELATIONS {
|
||||
if !relation_exists(connection, relation).await? {
|
||||
return Err(v23_error("v23.relations"));
|
||||
}
|
||||
}
|
||||
for (table, columns) in [
|
||||
(DEPENDENCIES, DEPENDENCY_COLUMNS),
|
||||
(RESOURCE_REFS, REF_COLUMNS),
|
||||
] {
|
||||
validate_columns(connection, table, columns).await?;
|
||||
}
|
||||
for (table, constraint, kind, stage, expected) in DEFINITIONS {
|
||||
if !constraint_matches(connection, table, constraint, kind, expected).await? {
|
||||
return Err(v23_error(stage));
|
||||
}
|
||||
}
|
||||
for (table, trigger) in [
|
||||
(DEPENDENCIES, "prompt_dependencies_immutable_guard"),
|
||||
(
|
||||
RESOURCE_REFS,
|
||||
"prompt_message_resource_refs_immutable_guard",
|
||||
),
|
||||
] {
|
||||
if !trigger_exists(connection, table, trigger).await? {
|
||||
return Err(v23_error("v23.immutable_trigger"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn validate_columns(
|
||||
connection: &mut PgConnection,
|
||||
table: &str,
|
||||
columns: &[(&str, &str, bool)],
|
||||
) -> Result<(), MigrationError> {
|
||||
let column_count: i64 = query(
|
||||
"select count(*)::bigint as count from information_schema.columns
|
||||
where table_schema = current_schema() and table_name = $1",
|
||||
)
|
||||
.bind(table)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.try_get("count")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
if column_count != i64::try_from(columns.len()).unwrap_or_default() {
|
||||
return Err(v23_error("v23.columns"));
|
||||
}
|
||||
for (column, data_type, nullable) in columns {
|
||||
let row = query(
|
||||
"select data_type, is_nullable from information_schema.columns
|
||||
where table_schema = current_schema() and table_name = $1 and column_name = $2",
|
||||
)
|
||||
.bind(table)
|
||||
.bind(column)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let valid = row.is_some_and(|row| {
|
||||
row.try_get::<String, _>("data_type").ok().as_deref() == Some(*data_type)
|
||||
&& row.try_get::<String, _>("is_nullable").ok().as_deref()
|
||||
== Some(if *nullable { "YES" } else { "NO" })
|
||||
});
|
||||
if !valid {
|
||||
return Err(v23_error("v23.columns"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn constraint_matches(
|
||||
connection: &mut PgConnection,
|
||||
table: &str,
|
||||
constraint: &str,
|
||||
kind: &str,
|
||||
expected: &str,
|
||||
) -> Result<bool, MigrationError> {
|
||||
let row = query(
|
||||
"select c.contype::text as kind, c.convalidated,
|
||||
pg_get_constraintdef(c.oid, true) as definition
|
||||
from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and t.relname = $1
|
||||
and c.conname = $2",
|
||||
)
|
||||
.bind(table)
|
||||
.bind(constraint)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
Ok(row.is_some_and(|row| {
|
||||
row.try_get::<String, _>("kind").ok().as_deref() == Some(kind)
|
||||
&& row.try_get::<bool, _>("convalidated").ok() == Some(true)
|
||||
&& row
|
||||
.try_get::<String, _>("definition")
|
||||
.ok()
|
||||
.is_some_and(|definition| {
|
||||
normalize_definition(&definition) == normalize_definition(expected)
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
async fn trigger_exists(
|
||||
connection: &mut PgConnection,
|
||||
table: &str,
|
||||
trigger: &str,
|
||||
) -> Result<bool, MigrationError> {
|
||||
query(
|
||||
"select exists (
|
||||
select 1 from pg_catalog.pg_trigger tg
|
||||
join pg_catalog.pg_class t on t.oid = tg.tgrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
join pg_catalog.pg_proc p on p.oid = tg.tgfoid
|
||||
where n.nspname = current_schema()
|
||||
and t.relname = $1
|
||||
and tg.tgname = $2
|
||||
and p.proname = $3
|
||||
and not tg.tgisinternal
|
||||
) as present",
|
||||
)
|
||||
.bind(table)
|
||||
.bind(trigger)
|
||||
.bind(GUARD_FUNCTION)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.try_get::<bool, _>("present")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
use crank_artifacts::ArtifactRef;
|
||||
use crank_core::ids::{PromptId, ResourceId};
|
||||
use crank_core::{
|
||||
Agent, AgentId, AgentOperationBinding, AgentStatus, AgentVersion, ApprovalRequest,
|
||||
ApprovalRequestId, ApprovalRequestStatus, AuthProfile, DescriptorId, ExecutionErrorCode,
|
||||
@@ -48,6 +49,14 @@ mod artifact_source;
|
||||
|
||||
pub use artifact_source::*;
|
||||
|
||||
pub mod resource;
|
||||
|
||||
mod prompt;
|
||||
|
||||
pub use prompt::*;
|
||||
|
||||
pub use resource::*;
|
||||
|
||||
mod import_plan;
|
||||
|
||||
pub use import_plan::*;
|
||||
@@ -56,6 +65,10 @@ mod onboarding_import;
|
||||
|
||||
pub use onboarding_import::*;
|
||||
|
||||
mod usage;
|
||||
|
||||
pub use usage::*;
|
||||
|
||||
define_registry_id!(YamlImportJobId);
|
||||
define_registry_id!(ImportJobId);
|
||||
define_registry_id!(ImportPlanId);
|
||||
@@ -243,161 +256,6 @@ pub struct WorkspaceUpstream {
|
||||
pub updated_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct InvocationLogRecord {
|
||||
pub log: InvocationLog,
|
||||
pub operation_name: String,
|
||||
pub operation_display_name: String,
|
||||
pub agent_slug: Option<String>,
|
||||
pub agent_display_name: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct UsageRollupRecord {
|
||||
pub rollup: UsageRollup,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct UsageTimelinePoint {
|
||||
#[serde(with = "time::serde::rfc3339")]
|
||||
pub bucket_start: OffsetDateTime,
|
||||
pub calls_ok: u64,
|
||||
pub calls_error: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct UsageOperationBreakdown {
|
||||
pub operation_id: OperationId,
|
||||
pub operation_name: String,
|
||||
pub operation_display_name: String,
|
||||
pub protocol: Protocol,
|
||||
pub calls_total: u64,
|
||||
pub calls_error: u64,
|
||||
pub p50_ms: u64,
|
||||
pub p95_ms: u64,
|
||||
pub p99_ms: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct UsageAgentBreakdown {
|
||||
pub agent_id: AgentId,
|
||||
pub agent_slug: String,
|
||||
pub agent_display_name: String,
|
||||
pub calls_total: u64,
|
||||
pub calls_error: u64,
|
||||
pub p50_ms: u64,
|
||||
pub p95_ms: u64,
|
||||
pub p99_ms: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum UsageOutcomeGroup {
|
||||
Success,
|
||||
Upstream,
|
||||
Client,
|
||||
Schema,
|
||||
Crank,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct UsageOutcomeBreakdown {
|
||||
pub group: UsageOutcomeGroup,
|
||||
pub execution_error_code: Option<ExecutionErrorCode>,
|
||||
pub calls_total: u64,
|
||||
pub p50_ms: u64,
|
||||
pub p95_ms: u64,
|
||||
pub p99_ms: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AppendProductEventOutcome {
|
||||
Recorded,
|
||||
Duplicate,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ProductEventRecord {
|
||||
pub event: ProductEvent,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct AppendProductEventRequest<'a> {
|
||||
pub event: &'a ProductEvent,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ListProductEventsQuery<'a> {
|
||||
pub workspace_id: &'a WorkspaceId,
|
||||
pub kind: Option<ProductEventKind>,
|
||||
pub created_after: OffsetDateTime,
|
||||
pub created_before: OffsetDateTime,
|
||||
pub limit: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum OnboardingPresentationMilestone {
|
||||
Eligible,
|
||||
Started,
|
||||
Resumed,
|
||||
Dismissed,
|
||||
Abandoned,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RecordOnboardingMilestoneRequest<'a> {
|
||||
pub workspace_id: &'a WorkspaceId,
|
||||
pub event_id: &'a ProductEventId,
|
||||
pub milestone: OnboardingPresentationMilestone,
|
||||
pub idempotency_key: &'a str,
|
||||
pub expected_revision: i64,
|
||||
pub occurred_at: OffsetDateTime,
|
||||
pub eligible_since: Option<OffsetDateTime>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RecordOnboardingCompletionRequest<'a> {
|
||||
pub workspace_id: &'a WorkspaceId,
|
||||
pub event_id: &'a ProductEventId,
|
||||
pub idempotency_key: &'a str,
|
||||
pub expected_revision: i64,
|
||||
pub occurred_at: OffsetDateTime,
|
||||
pub eligible_since: OffsetDateTime,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct OnboardingMilestoneResult {
|
||||
pub accepted: bool,
|
||||
pub projection: OnboardingProjection,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum InvocationRetentionStatus {
|
||||
Noop,
|
||||
Completed,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct InvocationRetentionPolicy {
|
||||
#[serde(with = "time::serde::rfc3339")]
|
||||
pub requested_cutoff: OffsetDateTime,
|
||||
#[serde(with = "time::serde::rfc3339")]
|
||||
pub effective_cutoff: OffsetDateTime,
|
||||
#[serde(with = "time::serde::rfc3339")]
|
||||
pub usage_preservation_floor: OffsetDateTime,
|
||||
pub preserved_usage_window_days: u16,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct InvocationRetentionOutcome {
|
||||
pub status: InvocationRetentionStatus,
|
||||
pub deleted_records: u64,
|
||||
pub policy: InvocationRetentionPolicy,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AgentSummary {
|
||||
pub id: AgentId,
|
||||
@@ -414,6 +272,21 @@ pub struct AgentSummary {
|
||||
pub published_at: Option<OffsetDateTime>,
|
||||
}
|
||||
|
||||
/// Точная опубликованная Resource Version, закреплённая за конкретной версией
|
||||
/// Agent (Story 3.7 AC04): typed binding, а не JSON-заместитель и не `latest`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct AgentResourceBinding {
|
||||
pub resource_id: ResourceId,
|
||||
pub resource_version: u32,
|
||||
}
|
||||
|
||||
/// Точная Published Prompt Version в snapshot версии Agent (Story 3.13).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct AgentPromptBinding {
|
||||
pub prompt_id: PromptId,
|
||||
pub prompt_version: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AgentVersionRecord {
|
||||
pub agent_id: AgentId,
|
||||
@@ -423,6 +296,12 @@ pub struct AgentVersionRecord {
|
||||
pub created_at: OffsetDateTime,
|
||||
pub snapshot: AgentVersion,
|
||||
pub bindings: Vec<AgentOperationBinding>,
|
||||
/// Отдельный typed список exact Published Resource Versions рядом с Operation bindings.
|
||||
#[serde(default)]
|
||||
pub resource_bindings: Vec<AgentResourceBinding>,
|
||||
/// Отдельный typed список exact Published Prompt Versions (Story 3.13).
|
||||
#[serde(default)]
|
||||
pub prompt_bindings: Vec<AgentPromptBinding>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -452,6 +331,14 @@ pub struct PublishedAgentCatalog {
|
||||
pub catalog_revision: String,
|
||||
pub tool_selection_policy: ToolSelectionPolicy,
|
||||
pub tools: Vec<PublishedAgentTool>,
|
||||
/// Точные Resource bindings того же `agent_version`/`catalog_revision` из той же
|
||||
/// read-транзакции каталога (Story 3.7 AC04).
|
||||
#[serde(default)]
|
||||
pub resources: Vec<AgentResourceBinding>,
|
||||
/// Точные Prompt bindings того же `agent_version`/`catalog_revision` из той же
|
||||
/// read-транзакции каталога (Story 3.14).
|
||||
#[serde(default)]
|
||||
pub prompts: Vec<AgentPromptBinding>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
@@ -883,6 +770,8 @@ pub struct SaveAgentCatalogConfigRequest<'a> {
|
||||
pub agent_version: u32,
|
||||
pub bindings: &'a [AgentOperationBinding],
|
||||
pub tool_selection_policy: &'a ToolSelectionPolicy,
|
||||
/// Точный список Published Resource Versions для Draft-версии (Story 3.7 AC04).
|
||||
pub resource_bindings: &'a [AgentResourceBinding],
|
||||
pub expected_state: Option<&'a AgentStateExpectation>,
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
use crank_core::{
|
||||
WorkspaceId,
|
||||
ids::PromptId,
|
||||
prompt::{PromptDefinition, PromptDraft, PromptSensitivity},
|
||||
prompt_composition::PromptDependencyPin,
|
||||
};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PromptDraftRecord {
|
||||
pub prompt: PromptDraft,
|
||||
/// Точная опубликованная версия, если Prompt уже публиковался (Story 3.13).
|
||||
pub latest_published_version: Option<u32>,
|
||||
/// Разрешённые пины зависимостей этой версии в порядке объявления (Story 3.16).
|
||||
pub dependencies: Vec<PromptDependencyPin>,
|
||||
pub created_at: OffsetDateTime,
|
||||
pub updated_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
/// Immutable Published Prompt Version, прочитанная по точному номеру версии.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PromptPublicationRecord {
|
||||
pub prompt_id: PromptId,
|
||||
pub version: u32,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub sensitivity: PromptSensitivity,
|
||||
pub definition: PromptDefinition,
|
||||
/// Пины зависимостей, зафиксированные публикацией (Story 3.16).
|
||||
pub dependencies: Vec<PromptDependencyPin>,
|
||||
pub published_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct PublishPromptRequest {
|
||||
pub workspace_id: WorkspaceId,
|
||||
pub prompt_id: PromptId,
|
||||
pub expected_updated_at: OffsetDateTime,
|
||||
pub published_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ArchivePromptRequest {
|
||||
pub workspace_id: WorkspaceId,
|
||||
pub prompt_id: PromptId,
|
||||
pub expected_updated_at: OffsetDateTime,
|
||||
pub archived_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct CreatePromptDraftRequest {
|
||||
pub workspace_id: WorkspaceId,
|
||||
pub prompt_id: PromptId,
|
||||
pub sensitivity: PromptSensitivity,
|
||||
pub definition: PromptDefinition,
|
||||
pub created_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct UpdatePromptDraftRequest {
|
||||
pub workspace_id: WorkspaceId,
|
||||
pub prompt_id: PromptId,
|
||||
pub sensitivity: PromptSensitivity,
|
||||
pub definition: PromptDefinition,
|
||||
pub expected_updated_at: OffsetDateTime,
|
||||
pub updated_at: OffsetDateTime,
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
//! Registry-модели Story 3.6: typed static Resource Drafts (V16).
|
||||
//!
|
||||
//! Мутирующие запросы получают `RegisteredArtifact` — доказательство уже
|
||||
//! зарегистрированных durable bytes (`ArtifactStore::put_registered`), а не сырые
|
||||
//! bytes и не digest строкой: реестр получает durable metadata/owning ref и **не**
|
||||
//! становится владельцем записи файла (D-15 шаг 3 `ensure_blob`).
|
||||
//!
|
||||
//! `resource_versions` не имеет `updated_at`: optimistic-precondition берётся из
|
||||
//! `resources.updated_at`, а CAS прежней owning-ссылки — из
|
||||
//! `artifact_sources.updated_at` через `get_source_in_transaction` (D-15 шаг 2).
|
||||
|
||||
use crank_artifacts::{ArtifactRef, RegisteredArtifact};
|
||||
use crank_core::WorkspaceId;
|
||||
use crank_core::ids::ResourceId;
|
||||
use crank_core::resource::ResourceStatus;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
/// Максимальный размер страницы списка Draft-ов.
|
||||
pub const MAX_RESOURCE_DRAFT_PAGE_SIZE: u32 = 100;
|
||||
|
||||
/// Создание Draft: одна транзакция, строгий insert без `on conflict do nothing`.
|
||||
#[derive(Debug)]
|
||||
pub struct CreateResourceDraftRequest {
|
||||
pub workspace_id: WorkspaceId,
|
||||
pub resource_id: ResourceId,
|
||||
pub uri: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub kind: String,
|
||||
pub mime_type: String,
|
||||
pub sensitivity: String,
|
||||
pub artifact: RegisteredArtifact,
|
||||
pub created_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
/// Обновление Draft. `uri`/`name`/`kind` неизменяемы и в запросе отсутствуют (D-16).
|
||||
#[derive(Debug)]
|
||||
pub struct UpdateResourceDraftRequest {
|
||||
pub workspace_id: WorkspaceId,
|
||||
pub resource_id: ResourceId,
|
||||
pub description: String,
|
||||
pub mime_type: String,
|
||||
pub sensitivity: String,
|
||||
/// Precondition из `resources.updated_at`: missing/stale → `ResourceError::Stale`.
|
||||
pub expected_updated_at: OffsetDateTime,
|
||||
pub artifact: RegisteredArtifact,
|
||||
}
|
||||
|
||||
/// Строка `resources` вместе с её текущей черновой версией.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ResourceDraftRecord {
|
||||
pub resource: ResourceRecord,
|
||||
pub version: ResourceVersionRecord,
|
||||
}
|
||||
|
||||
/// Story 3.10: version-keyed определение REST-шаблона (canonical JSON + digest).
|
||||
/// Отдельная таблица: у шаблона нет файла содержимого и нет фейкового blob.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ResourceTemplateSourceRecord {
|
||||
pub definition_json: String,
|
||||
pub definition_digest: String,
|
||||
}
|
||||
|
||||
/// Template Draft: карточка/версия того же снимка и её определение.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ResourceTemplateDraftRecord {
|
||||
pub snapshot: ResourceDraftRecord,
|
||||
pub source: ResourceTemplateSourceRecord,
|
||||
}
|
||||
|
||||
/// Создание template Draft: bytes отсутствуют, определение version-keyed.
|
||||
#[derive(Debug)]
|
||||
pub struct CreateResourceTemplateDraftRequest {
|
||||
pub workspace_id: WorkspaceId,
|
||||
pub resource_id: ResourceId,
|
||||
pub uri: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub kind: String,
|
||||
pub mime_type: String,
|
||||
pub sensitivity: String,
|
||||
pub definition_json: String,
|
||||
pub definition_digest: String,
|
||||
pub created_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
/// Обновление template Draft: uri/name/kind неизменяемы, определение заменяется
|
||||
/// целиком новой версией (прежняя остаётся для уже опубликованного снимка).
|
||||
#[derive(Debug)]
|
||||
pub struct UpdateResourceTemplateDraftRequest {
|
||||
pub workspace_id: WorkspaceId,
|
||||
pub resource_id: ResourceId,
|
||||
pub description: String,
|
||||
pub mime_type: String,
|
||||
pub sensitivity: String,
|
||||
pub expected_updated_at: OffsetDateTime,
|
||||
pub definition_json: String,
|
||||
pub definition_digest: String,
|
||||
}
|
||||
|
||||
/// Публикация template Draft: CAS по ревизии карточки и по exact определению.
|
||||
#[derive(Debug)]
|
||||
pub struct PublishResourceTemplateVersionRequest {
|
||||
pub workspace_id: WorkspaceId,
|
||||
pub resource_id: ResourceId,
|
||||
pub expected_updated_at: OffsetDateTime,
|
||||
pub expected_version: u32,
|
||||
pub expected_digest: String,
|
||||
pub published_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
/// Публикация текущего Draft (Story 3.7): точная CAS-ревизия карточки плюс
|
||||
/// повторно проверенные version/digest/size, которые транзакция сверяет под
|
||||
/// блокировкой строки Resource (TOCTOU между чтением bytes и коммитом).
|
||||
/// Снимок публичных metadata строится в транзакции из заблокированных строк
|
||||
/// `resources`/`resource_versions`, а не из переданного клиентом тела.
|
||||
#[derive(Debug)]
|
||||
pub struct PublishResourceVersionRequest {
|
||||
pub workspace_id: WorkspaceId,
|
||||
pub resource_id: ResourceId,
|
||||
/// Precondition из `resources.updated_at`: missing/stale → `ResourceError::Stale`.
|
||||
pub expected_updated_at: OffsetDateTime,
|
||||
pub expected_version: u32,
|
||||
pub expected_digest: String,
|
||||
pub expected_size_bytes: i64,
|
||||
/// Уже зарегистрированные immutable bytes (`ArtifactStore::put_registered`).
|
||||
pub artifact: RegisteredArtifact,
|
||||
/// Момент публикации (монотонно сдвигает CAS-ревизию карточки).
|
||||
pub published_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
/// Immutable Published Resource Version (V17): публичные metadata снимка.
|
||||
/// Owning-ссылка на хранилище и raw upload filename сюда не входят.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ResourcePublicationRecord {
|
||||
pub resource_id: ResourceId,
|
||||
pub version: u32,
|
||||
pub uri: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub kind: String,
|
||||
pub mime_type: String,
|
||||
pub size_bytes: i64,
|
||||
pub digest: String,
|
||||
pub sensitivity: String,
|
||||
/// Story 3.10: `artifact` (static) или `template` (byte-less definition).
|
||||
pub source_kind: String,
|
||||
pub published_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
/// Exact admitted Published template definition from the same live Resource-lock transaction.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct BoundResourceTemplate {
|
||||
pub publication: ResourcePublicationRecord,
|
||||
pub source: ResourceTemplateSourceRecord,
|
||||
}
|
||||
|
||||
/// Точная опубликованная версия вместе с owning-ссылкой для физического чтения
|
||||
/// bytes сервисом. `artifact_ref` не сериализуется и никогда не попадает в wire.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ResolvedResourcePublication {
|
||||
pub publication: ResourcePublicationRecord,
|
||||
pub artifact_ref: ArtifactRef,
|
||||
}
|
||||
|
||||
/// Архив текущего Resource (Story 3.7 AC05): тот же CAS, что у PUT/publish.
|
||||
/// Транзакция меняет только lifecycle/ревизию карточки; artifacts, publications и
|
||||
/// Agent snapshots не затрагиваются.
|
||||
#[derive(Debug)]
|
||||
pub struct ArchiveResourceRequest {
|
||||
pub workspace_id: WorkspaceId,
|
||||
pub resource_id: ResourceId,
|
||||
/// Precondition из `resources.updated_at`: missing/stale → `ResourceError::Stale`.
|
||||
pub expected_updated_at: OffsetDateTime,
|
||||
/// Момент архивации (монотонно сдвигает CAS-ревизию карточки).
|
||||
pub archived_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
/// Отзыв Resource (Story 3.8, owner decision A). Actor и корреляция берутся
|
||||
/// только из серверной сессии/RequestContext, не из тела запроса. Повтор
|
||||
/// существующего отзыва сохраняет первую запись и не создаёт новую.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RevokeResourceRequest {
|
||||
pub workspace_id: WorkspaceId,
|
||||
pub resource_id: ResourceId,
|
||||
pub actor_user_id: String,
|
||||
pub request_id: String,
|
||||
pub trace_id: String,
|
||||
pub revoked_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
/// Проекция `resources`: без filesystem path, raw filename и storage ref (D-12).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ResourceRecord {
|
||||
pub resource_id: ResourceId,
|
||||
pub uri: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub status: ResourceStatus,
|
||||
pub kind: String,
|
||||
pub current_draft_version: u32,
|
||||
/// Workspace-scoped максимум Published версий: discovery-указатель точной версии,
|
||||
/// не latest-alias для bytes (`/versions/{integer}` остаётся единственным чтением).
|
||||
pub latest_published_version: Option<u32>,
|
||||
pub created_at: OffsetDateTime,
|
||||
pub updated_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
/// Проекция `resource_versions` без owning-ссылки на хранилище.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ResourceVersionRecord {
|
||||
pub version: u32,
|
||||
pub kind: String,
|
||||
pub mime_type: String,
|
||||
pub size_bytes: i64,
|
||||
pub digest: String,
|
||||
pub sensitivity: String,
|
||||
/// Story 3.10: `artifact` (static) или `template` (byte-less definition).
|
||||
pub source_kind: String,
|
||||
pub created_at: OffsetDateTime,
|
||||
pub superseded_at: Option<OffsetDateTime>,
|
||||
}
|
||||
|
||||
impl ResourceVersionRecord {
|
||||
pub fn is_current(&self) -> bool {
|
||||
self.superseded_at.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// Результат workspace-scoped разрешения версии **одним** запросом: строки
|
||||
/// `resources`/`resource_versions` одного снимка и `artifact_ref` для физического
|
||||
/// чтения байт сервисом (D-19: точка чтения байт — в сервисе).
|
||||
///
|
||||
/// Один снимок обязателен, чтобы ответ не смешивал metadata одной версии с bytes
|
||||
/// другой (P3): разрешение версии происходит ровно один раз на запрос.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ResolvedResourceVersion {
|
||||
/// Строки `resources` и `resource_versions` того же снимка.
|
||||
pub snapshot: ResourceDraftRecord,
|
||||
/// Ссылка на физические bytes этой версии.
|
||||
pub artifact_ref: ArtifactRef,
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
//! Usage / product-event / retention DTO (вынесены из `model.rs`, чтобы файл
|
||||
//! оставался в пределах rust-code-health). Публичные пути сохранены через
|
||||
//! `pub use usage::*;` в родительском модуле.
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct InvocationLogRecord {
|
||||
pub log: InvocationLog,
|
||||
pub operation_name: String,
|
||||
pub operation_display_name: String,
|
||||
pub agent_slug: Option<String>,
|
||||
pub agent_display_name: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct UsageRollupRecord {
|
||||
pub rollup: UsageRollup,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct UsageTimelinePoint {
|
||||
#[serde(with = "time::serde::rfc3339")]
|
||||
pub bucket_start: OffsetDateTime,
|
||||
pub calls_ok: u64,
|
||||
pub calls_error: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct UsageOperationBreakdown {
|
||||
pub operation_id: OperationId,
|
||||
pub operation_name: String,
|
||||
pub operation_display_name: String,
|
||||
pub protocol: Protocol,
|
||||
pub calls_total: u64,
|
||||
pub calls_error: u64,
|
||||
pub p50_ms: u64,
|
||||
pub p95_ms: u64,
|
||||
pub p99_ms: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct UsageAgentBreakdown {
|
||||
pub agent_id: AgentId,
|
||||
pub agent_slug: String,
|
||||
pub agent_display_name: String,
|
||||
pub calls_total: u64,
|
||||
pub calls_error: u64,
|
||||
pub p50_ms: u64,
|
||||
pub p95_ms: u64,
|
||||
pub p99_ms: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum UsageOutcomeGroup {
|
||||
Success,
|
||||
Upstream,
|
||||
Client,
|
||||
Schema,
|
||||
Crank,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct UsageOutcomeBreakdown {
|
||||
pub group: UsageOutcomeGroup,
|
||||
pub execution_error_code: Option<ExecutionErrorCode>,
|
||||
pub calls_total: u64,
|
||||
pub p50_ms: u64,
|
||||
pub p95_ms: u64,
|
||||
pub p99_ms: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AppendProductEventOutcome {
|
||||
Recorded,
|
||||
Duplicate,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ProductEventRecord {
|
||||
pub event: ProductEvent,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct AppendProductEventRequest<'a> {
|
||||
pub event: &'a ProductEvent,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ListProductEventsQuery<'a> {
|
||||
pub workspace_id: &'a WorkspaceId,
|
||||
pub kind: Option<ProductEventKind>,
|
||||
pub created_after: OffsetDateTime,
|
||||
pub created_before: OffsetDateTime,
|
||||
pub limit: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum OnboardingPresentationMilestone {
|
||||
Eligible,
|
||||
Started,
|
||||
Resumed,
|
||||
Dismissed,
|
||||
Abandoned,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RecordOnboardingMilestoneRequest<'a> {
|
||||
pub workspace_id: &'a WorkspaceId,
|
||||
pub event_id: &'a ProductEventId,
|
||||
pub milestone: OnboardingPresentationMilestone,
|
||||
pub idempotency_key: &'a str,
|
||||
pub expected_revision: i64,
|
||||
pub occurred_at: OffsetDateTime,
|
||||
pub eligible_since: Option<OffsetDateTime>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RecordOnboardingCompletionRequest<'a> {
|
||||
pub workspace_id: &'a WorkspaceId,
|
||||
pub event_id: &'a ProductEventId,
|
||||
pub idempotency_key: &'a str,
|
||||
pub expected_revision: i64,
|
||||
pub occurred_at: OffsetDateTime,
|
||||
pub eligible_since: OffsetDateTime,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct OnboardingMilestoneResult {
|
||||
pub accepted: bool,
|
||||
pub projection: OnboardingProjection,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum InvocationRetentionStatus {
|
||||
Noop,
|
||||
Completed,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct InvocationRetentionPolicy {
|
||||
#[serde(with = "time::serde::rfc3339")]
|
||||
pub requested_cutoff: OffsetDateTime,
|
||||
#[serde(with = "time::serde::rfc3339")]
|
||||
pub effective_cutoff: OffsetDateTime,
|
||||
#[serde(with = "time::serde::rfc3339")]
|
||||
pub usage_preservation_floor: OffsetDateTime,
|
||||
pub preserved_usage_window_days: u16,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct InvocationRetentionOutcome {
|
||||
pub status: InvocationRetentionStatus,
|
||||
pub deleted_records: u64,
|
||||
pub policy: InvocationRetentionPolicy,
|
||||
}
|
||||
@@ -1,3 +1,9 @@
|
||||
use super::agent_prompt_bindings::{
|
||||
ensure_agent_prompt_bindings_not_archived, replace_agent_prompt_bindings_rows,
|
||||
};
|
||||
use super::agent_resource_bindings::{
|
||||
ensure_agent_bindings_not_revoked, replace_agent_resource_bindings_rows,
|
||||
};
|
||||
use super::*;
|
||||
use crate::model::{AgentStateExpectation, UpdateAgentSummaryRequest};
|
||||
|
||||
@@ -224,6 +230,8 @@ impl PostgresRegistry {
|
||||
};
|
||||
|
||||
let bindings = self.list_agent_bindings(agent_id, version).await?;
|
||||
let resource_bindings = self.list_agent_resource_bindings(agent_id, version).await?;
|
||||
let prompt_bindings = self.list_agent_prompt_bindings(agent_id, version).await?;
|
||||
Ok(Some(build_agent_version_record(
|
||||
&summary,
|
||||
row.version,
|
||||
@@ -232,6 +240,8 @@ impl PostgresRegistry {
|
||||
row.tool_selection_policy_json,
|
||||
row.created_at,
|
||||
bindings,
|
||||
resource_bindings,
|
||||
prompt_bindings,
|
||||
)?))
|
||||
}
|
||||
|
||||
@@ -265,7 +275,7 @@ impl PostgresRegistry {
|
||||
&self,
|
||||
request: SaveAgentCatalogConfigRequest<'_>,
|
||||
) -> Result<(), RegistryError> {
|
||||
self.save_agent_catalog_config_inner(request, false)
|
||||
self.save_agent_catalog_config_inner(request, false, &[])
|
||||
.await
|
||||
.map(|_| ())
|
||||
}
|
||||
@@ -274,13 +284,27 @@ impl PostgresRegistry {
|
||||
&self,
|
||||
request: SaveAgentCatalogConfigRequest<'_>,
|
||||
) -> Result<u32, RegistryError> {
|
||||
self.save_agent_catalog_config_inner(request, true).await
|
||||
self.save_agent_catalog_config_inner(request, true, &[])
|
||||
.await
|
||||
}
|
||||
|
||||
/// Как [`Self::save_agent_catalog_config_editable`], но с точными Prompt
|
||||
/// bindings Draft-версии (Story 3.13). Существующие вызовы без Prompt
|
||||
/// сохраняют прежнюю сигнатуру и семантику.
|
||||
pub async fn save_agent_catalog_config_editable_with_prompts(
|
||||
&self,
|
||||
request: SaveAgentCatalogConfigRequest<'_>,
|
||||
prompt_bindings: &[AgentPromptBinding],
|
||||
) -> Result<u32, RegistryError> {
|
||||
self.save_agent_catalog_config_inner(request, true, prompt_bindings)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn save_agent_catalog_config_inner(
|
||||
&self,
|
||||
request: SaveAgentCatalogConfigRequest<'_>,
|
||||
allow_fork: bool,
|
||||
prompt_bindings: &[AgentPromptBinding],
|
||||
) -> Result<u32, RegistryError> {
|
||||
let mut tx = self.pool.begin().await?;
|
||||
let agent_row = Self::lock_agent_and_validate_expected_state(
|
||||
@@ -350,6 +374,22 @@ impl PostgresRegistry {
|
||||
request.bindings,
|
||||
)
|
||||
.await?;
|
||||
replace_agent_resource_bindings_rows(
|
||||
&mut tx,
|
||||
request.workspace_id,
|
||||
request.agent_id,
|
||||
draft.version,
|
||||
request.resource_bindings,
|
||||
)
|
||||
.await?;
|
||||
replace_agent_prompt_bindings_rows(
|
||||
&mut tx,
|
||||
request.workspace_id,
|
||||
request.agent_id,
|
||||
draft.version,
|
||||
prompt_bindings,
|
||||
)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"update agents
|
||||
set current_draft_version = $3,
|
||||
@@ -394,6 +434,22 @@ impl PostgresRegistry {
|
||||
request.bindings,
|
||||
)
|
||||
.await?;
|
||||
replace_agent_resource_bindings_rows(
|
||||
&mut tx,
|
||||
request.workspace_id,
|
||||
request.agent_id,
|
||||
request.agent_version,
|
||||
request.resource_bindings,
|
||||
)
|
||||
.await?;
|
||||
replace_agent_prompt_bindings_rows(
|
||||
&mut tx,
|
||||
request.workspace_id,
|
||||
request.agent_id,
|
||||
request.agent_version,
|
||||
prompt_bindings,
|
||||
)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"update agents
|
||||
set updated_at = now()
|
||||
@@ -645,6 +701,14 @@ impl PostgresRegistry {
|
||||
actual: request.version,
|
||||
});
|
||||
}
|
||||
// Повторная публикация уже опубликованной версии идемпотентна и не даёт
|
||||
// второго bump catalog_revision (Story 3.13 AC2). После unpublish Agent
|
||||
// снова Draft, поэтому такое состояние требует обычной публикации.
|
||||
if latest_published_version == Some(request.version)
|
||||
&& agent_status == AgentStatus::Published
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
let catalog_revision: i64 = agent_row.try_get("catalog_revision")?;
|
||||
let next_catalog_revision = catalog_revision
|
||||
.checked_add(1)
|
||||
@@ -670,6 +734,26 @@ impl PostgresRegistry {
|
||||
});
|
||||
}
|
||||
|
||||
// Story 3.8: публикация Agent — тоже точка выдачи Resource-доступа. Текущая
|
||||
// версия bindings перечитывается внутри этой транзакции после Agent lock,
|
||||
// Resources блокируются в порядке resource_id ASC, и отозванный Resource
|
||||
// отменяет публикацию до любой мутации каталога.
|
||||
ensure_agent_bindings_not_revoked(
|
||||
&mut tx,
|
||||
request.workspace_id,
|
||||
request.agent_id,
|
||||
request.version,
|
||||
)
|
||||
.await?;
|
||||
// Story 3.13: archived Prompt не может войти в новую публикацию Agent.
|
||||
ensure_agent_prompt_bindings_not_archived(
|
||||
&mut tx,
|
||||
request.workspace_id,
|
||||
request.agent_id,
|
||||
request.version,
|
||||
)
|
||||
.await?;
|
||||
|
||||
sqlx::query(
|
||||
"update agent_versions
|
||||
set status = $1
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use super::agent_prompt_bindings::read_agent_prompt_bindings;
|
||||
use super::agent_resource_bindings::read_agent_resource_bindings;
|
||||
use super::*;
|
||||
|
||||
impl PostgresRegistry {
|
||||
@@ -12,6 +14,7 @@ impl PostgresRegistry {
|
||||
.await?;
|
||||
let row = sqlx::query(
|
||||
"select
|
||||
a.id as agent_id,
|
||||
pa.version,
|
||||
pa.catalog_revision,
|
||||
av.tool_selection_policy_json
|
||||
@@ -35,6 +38,13 @@ impl PostgresRegistry {
|
||||
let tools = query_published_agent_tools(&mut tx, workspace_slug, agent_slug).await?;
|
||||
|
||||
let agent_version = from_db_version(row.try_get("version")?, "agent_version")?;
|
||||
let agent_id = AgentId::new(row.try_get::<String, _>("agent_id")?);
|
||||
// Точные Resource bindings того же agent_version читаются в этой же
|
||||
// repeatable-read транзакции: resources/version/revision всегда согласованы.
|
||||
let resources = read_agent_resource_bindings(&mut tx, &agent_id, agent_version).await?;
|
||||
// Story 3.14: точные Prompt bindings того же snapshot читаются здесь же, поэтому
|
||||
// prompts/list и prompts/get видят только версии, закреплённые в опубликованной версии.
|
||||
let prompts = read_agent_prompt_bindings(&mut tx, &agent_id, agent_version).await?;
|
||||
let catalog_revision: i64 = row.try_get("catalog_revision")?;
|
||||
tx.commit().await?;
|
||||
|
||||
@@ -47,9 +57,42 @@ impl PostgresRegistry {
|
||||
row.try_get("tool_selection_policy_json")?,
|
||||
)?,
|
||||
tools,
|
||||
resources,
|
||||
prompts,
|
||||
})
|
||||
}
|
||||
|
||||
/// Workspace of the published Agent addressed by slug, for scoped Resource reads.
|
||||
///
|
||||
/// The workspace identity of a slug is immutable, so reading it separately from the catalog is
|
||||
/// not a second, mutable snapshot; a missing/unpublished Agent yields the same safe error as the
|
||||
/// catalog read.
|
||||
pub async fn published_agent_workspace_id(
|
||||
&self,
|
||||
workspace_slug: &str,
|
||||
agent_slug: &str,
|
||||
) -> Result<WorkspaceId, RegistryError> {
|
||||
let row = sqlx::query(
|
||||
"select w.id
|
||||
from workspaces w
|
||||
join agents a on a.workspace_id = w.id
|
||||
join published_agents pa on pa.agent_id = a.id
|
||||
where w.slug = $1
|
||||
and a.slug = $2
|
||||
and a.status = 'published'",
|
||||
)
|
||||
.bind(workspace_slug)
|
||||
.bind(agent_slug)
|
||||
.fetch_optional(self.pool())
|
||||
.await?
|
||||
.ok_or_else(|| RegistryError::PublishedAgentNotFound {
|
||||
workspace_slug: workspace_slug.to_owned(),
|
||||
agent_slug: agent_slug.to_owned(),
|
||||
})?;
|
||||
|
||||
Ok(WorkspaceId::new(row.try_get::<String, _>("id")?))
|
||||
}
|
||||
|
||||
pub async fn get_published_agent_tools_by_slug(
|
||||
&self,
|
||||
workspace_slug: &str,
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
//! Typed exact Prompt bindings Agent (Story 3.13, V22).
|
||||
//!
|
||||
//! `agent_prompt_bindings` — отдельная typed-таблица: строка адресует точную
|
||||
//! Published Prompt Version (`prompt_publications`) для точной версии Agent
|
||||
//! (`agent_versions`). Composite FK на обоих концах фиксирует workspace, поэтому
|
||||
//! ни чужой Agent, ни чужая/неопубликованная Prompt Version не могут стать частью
|
||||
//! binding, а floating `latest` невозможен.
|
||||
//!
|
||||
//! Archive — lifecycle-состояние, а не удаление immutable снимка: строка
|
||||
//! публикации остаётся, поэтому новый binding на archived Prompt обязан
|
||||
//! отклоняться проверкой состояния в той же транзакции, что и запись.
|
||||
|
||||
use super::*;
|
||||
use crank_core::ids::PromptId;
|
||||
use sqlx::{PgConnection, Row};
|
||||
|
||||
impl PostgresRegistry {
|
||||
/// Точные Prompt bindings версии Agent (публичный read path).
|
||||
pub async fn list_agent_prompt_bindings(
|
||||
&self,
|
||||
agent_id: &AgentId,
|
||||
version: u32,
|
||||
) -> Result<Vec<AgentPromptBinding>, RegistryError> {
|
||||
let mut connection = self.pool.acquire().await?;
|
||||
read_agent_prompt_bindings(&mut connection, agent_id, version).await
|
||||
}
|
||||
|
||||
/// Возвращает bindings, для которых в **этом** workspace нет точной строки
|
||||
/// `prompt_publications`. Пустой результат — все версии опубликованы.
|
||||
pub async fn unresolved_published_prompt_versions(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
bindings: &[AgentPromptBinding],
|
||||
) -> Result<Vec<AgentPromptBinding>, RegistryError> {
|
||||
let mut unresolved = Vec::new();
|
||||
for binding in bindings {
|
||||
let version = i32::try_from(binding.prompt_version).map_err(|_| {
|
||||
RegistryError::InvalidNumericValue {
|
||||
field: "prompt_version",
|
||||
value: i64::from(binding.prompt_version),
|
||||
}
|
||||
})?;
|
||||
let exists = sqlx::query_scalar::<_, bool>(
|
||||
"select exists (
|
||||
select 1 from prompt_publications
|
||||
where workspace_id = $1 and prompt_id = $2 and version = $3
|
||||
)",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(binding.prompt_id.as_str())
|
||||
.bind(version)
|
||||
.fetch_one(&self.pool)
|
||||
.await?;
|
||||
if !exists {
|
||||
unresolved.push(binding.clone());
|
||||
}
|
||||
}
|
||||
Ok(unresolved)
|
||||
}
|
||||
}
|
||||
|
||||
/// Полная замена Prompt bindings конкретной версии Agent внутри открытой
|
||||
/// транзакции save/publish/fork. FK-нарушение откатывает всю транзакцию целиком.
|
||||
pub(super) async fn replace_agent_prompt_bindings_rows(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
agent_id: &AgentId,
|
||||
version: u32,
|
||||
bindings: &[AgentPromptBinding],
|
||||
) -> Result<(), RegistryError> {
|
||||
if let Some(archived) = first_archived_prompt(tx, workspace_id, bindings).await? {
|
||||
return Err(RegistryError::PromptArchived {
|
||||
prompt_id: archived,
|
||||
});
|
||||
}
|
||||
|
||||
sqlx::query(
|
||||
"delete from agent_prompt_bindings
|
||||
where agent_id = $1 and agent_version = $2",
|
||||
)
|
||||
.bind(agent_id.as_str())
|
||||
.bind(to_db_version(version))
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
|
||||
for binding in bindings {
|
||||
sqlx::query(
|
||||
"insert into agent_prompt_bindings (
|
||||
workspace_id,
|
||||
agent_id,
|
||||
agent_version,
|
||||
prompt_id,
|
||||
prompt_version
|
||||
) values ($1, $2, $3, $4, $5)",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(agent_id.as_str())
|
||||
.bind(to_db_version(version))
|
||||
.bind(binding.prompt_id.as_str())
|
||||
.bind(to_db_version(binding.prompt_version))
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Archive блокирует только *новые* binding: immutable publication уже созданной
|
||||
/// версии не удаляется. Кандидаты блокируются в детерминированном порядке, чтобы
|
||||
/// concurrent archive либо успел раньше (отказ), либо ждал commit транзакции.
|
||||
async fn first_archived_prompt(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
bindings: &[AgentPromptBinding],
|
||||
) -> Result<Option<String>, RegistryError> {
|
||||
let prompt_ids: Vec<String> = bindings
|
||||
.iter()
|
||||
.map(|binding| binding.prompt_id.as_str().to_owned())
|
||||
.collect();
|
||||
if prompt_ids.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let rows = sqlx::query(
|
||||
"select prompt_id, status
|
||||
from prompts
|
||||
where workspace_id = $1
|
||||
and prompt_id = any($2::text[])
|
||||
order by prompt_id asc
|
||||
for update",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(&prompt_ids)
|
||||
.fetch_all(&mut **tx)
|
||||
.await?;
|
||||
for row in rows {
|
||||
if row.try_get::<String, _>("status")? == "archived" {
|
||||
return Ok(Some(row.try_get("prompt_id")?));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Fail-closed проверка перед публикацией Agent: ни один binding не должен
|
||||
/// указывать на archived Prompt. Отказ не меняет ни snapshot, ни catalog_revision.
|
||||
pub(super) async fn ensure_agent_prompt_bindings_not_archived(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
agent_id: &AgentId,
|
||||
version: u32,
|
||||
) -> Result<(), RegistryError> {
|
||||
let bindings = read_agent_prompt_bindings(tx, agent_id, version).await?;
|
||||
if let Some(archived) = first_archived_prompt(tx, workspace_id, &bindings).await? {
|
||||
return Err(RegistryError::PromptArchived {
|
||||
prompt_id: archived,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn read_agent_prompt_bindings(
|
||||
connection: &mut PgConnection,
|
||||
agent_id: &AgentId,
|
||||
version: u32,
|
||||
) -> Result<Vec<AgentPromptBinding>, RegistryError> {
|
||||
let rows = sqlx::query(
|
||||
"select prompt_id, prompt_version
|
||||
from agent_prompt_bindings
|
||||
where agent_id = $1 and agent_version = $2
|
||||
order by prompt_id asc",
|
||||
)
|
||||
.bind(agent_id.as_str())
|
||||
.bind(to_db_version(version))
|
||||
.fetch_all(&mut *connection)
|
||||
.await?;
|
||||
|
||||
rows.into_iter()
|
||||
.map(|row| {
|
||||
Ok(AgentPromptBinding {
|
||||
prompt_id: PromptId::new(row.try_get::<String, _>("prompt_id")?),
|
||||
prompt_version: from_db_version(row.try_get("prompt_version")?, "prompt_version")?,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
//! Typed exact Resource bindings Agent (Story 3.7 AC04, V18).
|
||||
//!
|
||||
//! `agent_resource_bindings` — отдельная typed-таблица: строка адресует точную
|
||||
//! Published Resource Version (`resource_publications`) для точной версии Agent
|
||||
//! (`agent_versions`). Composite FK на обоих концах фиксирует workspace:
|
||||
//! `(workspace_id, agent_id) -> agents(workspace_id, id)` и
|
||||
//! `(workspace_id, resource_id, resource_version) -> resource_publications`,
|
||||
//! поэтому ни чужой Agent, ни чужая/неопубликованная Resource Version не могут
|
||||
//! стать частью binding.
|
||||
//!
|
||||
//! Здесь же проверка «точная опубликованная версия существует в этом workspace»
|
||||
//! для API-слоя: отсутствующая, чужая и неопубликованная версии дают один и тот
|
||||
//! же sanitized 404 без утечки существования.
|
||||
|
||||
use super::*;
|
||||
use crank_core::ids::ResourceId;
|
||||
use sqlx::{PgConnection, Row};
|
||||
|
||||
impl PostgresRegistry {
|
||||
/// Точные Resource bindings версии Agent (публичный read path).
|
||||
pub async fn list_agent_resource_bindings(
|
||||
&self,
|
||||
agent_id: &AgentId,
|
||||
version: u32,
|
||||
) -> Result<Vec<AgentResourceBinding>, RegistryError> {
|
||||
let mut connection = self.pool.acquire().await?;
|
||||
read_agent_resource_bindings(&mut connection, agent_id, version).await
|
||||
}
|
||||
|
||||
/// Возвращает bindings, для которых в **этом** workspace нет точной строки
|
||||
/// `resource_publications`. Пустой результат — все версии опубликованы.
|
||||
/// Различие «чужая/неопубликованная/отсутствующая» наружу не раскрывается.
|
||||
pub async fn unresolved_published_resource_versions(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
bindings: &[AgentResourceBinding],
|
||||
) -> Result<Vec<AgentResourceBinding>, RegistryError> {
|
||||
let mut unresolved = Vec::new();
|
||||
for binding in bindings {
|
||||
let version = i32::try_from(binding.resource_version).map_err(|_| {
|
||||
RegistryError::InvalidNumericValue {
|
||||
field: "resource_version",
|
||||
value: i64::from(binding.resource_version),
|
||||
}
|
||||
})?;
|
||||
let exists = sqlx::query_scalar::<_, bool>(
|
||||
"select exists (
|
||||
select 1 from resource_publications
|
||||
where workspace_id = $1 and resource_id = $2 and version = $3
|
||||
)",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(binding.resource_id.as_str())
|
||||
.bind(version)
|
||||
.fetch_one(&self.pool)
|
||||
.await?;
|
||||
if !exists {
|
||||
unresolved.push(binding.clone());
|
||||
}
|
||||
}
|
||||
Ok(unresolved)
|
||||
}
|
||||
}
|
||||
|
||||
/// Полная замена Resource bindings конкретной версии Agent внутри уже открытой
|
||||
/// транзакции save/publish/fork. FK-нарушение откатывает всю транзакцию целиком.
|
||||
pub(super) async fn replace_agent_resource_bindings_rows(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
agent_id: &AgentId,
|
||||
version: u32,
|
||||
bindings: &[AgentResourceBinding],
|
||||
) -> Result<(), RegistryError> {
|
||||
// AC04: archive forbids *new* bindings. The immutable `resource_publications` row is untouched by
|
||||
// archive, so the composite FK alone would still accept an archived Resource here; the lifecycle
|
||||
// state is checked in the same transaction that writes the bindings (fail-closed, no partial rows).
|
||||
if let Some(archived) = first_archived_resource(tx, workspace_id, bindings).await? {
|
||||
return Err(RegistryError::ResourceArchived {
|
||||
resource_id: archived,
|
||||
});
|
||||
}
|
||||
// Story 3.8: отзыв блокирует и новые привязки. Tombstones читаются после тех же
|
||||
// упорядоченных `resources` locks, поэтому revoke не может проскочить между
|
||||
// проверкой и INSERT.
|
||||
if let Some(revoked) = first_revoked_resource(tx, workspace_id, bindings).await? {
|
||||
return Err(RegistryError::ResourceRevoked {
|
||||
resource_id: revoked,
|
||||
});
|
||||
}
|
||||
|
||||
sqlx::query(
|
||||
"delete from agent_resource_bindings
|
||||
where agent_id = $1 and agent_version = $2",
|
||||
)
|
||||
.bind(agent_id.as_str())
|
||||
.bind(to_db_version(version))
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
|
||||
for binding in bindings {
|
||||
sqlx::query(
|
||||
"insert into agent_resource_bindings (
|
||||
workspace_id,
|
||||
agent_id,
|
||||
agent_version,
|
||||
resource_id,
|
||||
resource_version
|
||||
) values ($1, $2, $3, $4, $5)",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(agent_id.as_str())
|
||||
.bind(to_db_version(version))
|
||||
.bind(binding.resource_id.as_str())
|
||||
.bind(to_db_version(binding.resource_version))
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The first `archived` Resource among the requested bindings, if any (workspace-scoped).
|
||||
///
|
||||
/// AC04 («archive forbids *new* bindings») must not be a check-then-write race: an unlocked status
|
||||
/// read can miss an archive that commits between this SELECT and the INSERT below, which would
|
||||
/// leave a binding created after the Resource was archived. Every candidate `resources` row is
|
||||
/// therefore locked in deterministic (ascending id) order in this transaction *before* its status is
|
||||
/// inspected, and those locks are held until the binding writes commit. A concurrent archive of any
|
||||
/// candidate then either commits first (its `archived` state is what we read: refused) or waits for
|
||||
/// this transaction to end (the binding legally precedes the archive).
|
||||
async fn first_archived_resource(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
bindings: &[AgentResourceBinding],
|
||||
) -> Result<Option<String>, RegistryError> {
|
||||
let resource_ids: Vec<String> = bindings
|
||||
.iter()
|
||||
.map(|binding| binding.resource_id.as_str().to_owned())
|
||||
.collect();
|
||||
if resource_ids.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
// `for update` after the deterministic `order by`, and *without* the status predicate: a row
|
||||
// filtered out by `status = 'archived'` would never be locked and could be archived mid-write.
|
||||
let rows = sqlx::query(
|
||||
"select r.resource_id, r.status
|
||||
from resources r
|
||||
where r.workspace_id = $1
|
||||
and r.resource_id = any($2::text[])
|
||||
order by r.resource_id asc
|
||||
for update",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(&resource_ids)
|
||||
.fetch_all(&mut **tx)
|
||||
.await?;
|
||||
for row in rows {
|
||||
if row.try_get::<String, _>("status")? == "archived" {
|
||||
return Ok(Some(row.try_get::<String, _>("resource_id")?));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// The first revoked Resource among the requested bindings, if any (workspace-scoped).
|
||||
///
|
||||
/// Callers must already hold the `resources` rows of these bindings (the same
|
||||
/// deterministic ascending order as `first_archived_resource`), so a revoke cannot
|
||||
/// commit between this fresh tombstone query and the following INSERT.
|
||||
async fn first_revoked_resource(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
bindings: &[AgentResourceBinding],
|
||||
) -> Result<Option<String>, RegistryError> {
|
||||
let resource_ids: Vec<String> = bindings
|
||||
.iter()
|
||||
.map(|binding| binding.resource_id.as_str().to_owned())
|
||||
.collect();
|
||||
if resource_ids.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let row = sqlx::query(
|
||||
"select resource_id
|
||||
from resource_security_revocations
|
||||
where workspace_id = $1 and resource_id = any($2::text[])
|
||||
order by resource_id asc
|
||||
limit 1",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(&resource_ids)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?;
|
||||
row.map(|row| row.try_get::<String, _>("resource_id"))
|
||||
.transpose()
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Live security gate for `Agent publish`: re-read the exact bindings of the version
|
||||
/// being published inside the Agent transaction, lock their Resources in `resource_id
|
||||
/// ASC` order and reject revoked ones before any publication mutation.
|
||||
pub(super) async fn ensure_agent_bindings_not_revoked(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
agent_id: &AgentId,
|
||||
version: u32,
|
||||
) -> Result<(), RegistryError> {
|
||||
let bindings = read_agent_resource_bindings(&mut *tx, agent_id, version).await?;
|
||||
let mut resource_ids: Vec<String> = bindings
|
||||
.iter()
|
||||
.map(|binding| binding.resource_id.as_str().to_owned())
|
||||
.collect();
|
||||
resource_ids.sort();
|
||||
resource_ids.dedup();
|
||||
if resource_ids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let locked = sqlx::query(
|
||||
"select resource_id from resources
|
||||
where workspace_id = $1 and resource_id = any($2::text[])
|
||||
order by resource_id asc
|
||||
for share",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(&resource_ids)
|
||||
.fetch_all(&mut **tx)
|
||||
.await?;
|
||||
if locked.len() != resource_ids.len() {
|
||||
return Err(RegistryError::Storage(sqlx::Error::RowNotFound));
|
||||
}
|
||||
if let Some(resource_id) = first_revoked_resource(tx, workspace_id, &bindings).await? {
|
||||
return Err(RegistryError::ResourceRevoked { resource_id });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Чтение exact bindings внутри транзакции: каталог обязан брать resources из
|
||||
/// той же read-транзакции, что `agent_version`/`catalog_revision`/`tools`.
|
||||
pub(super) async fn read_agent_resource_bindings(
|
||||
executor: &mut PgConnection,
|
||||
agent_id: &AgentId,
|
||||
version: u32,
|
||||
) -> Result<Vec<AgentResourceBinding>, RegistryError> {
|
||||
let rows = sqlx::query(
|
||||
"select resource_id, resource_version
|
||||
from agent_resource_bindings
|
||||
where agent_id = $1 and agent_version = $2
|
||||
order by resource_id asc, resource_version asc",
|
||||
)
|
||||
.bind(agent_id.as_str())
|
||||
.bind(to_db_version(version))
|
||||
.fetch_all(&mut *executor)
|
||||
.await?;
|
||||
|
||||
rows.into_iter()
|
||||
.map(|row| {
|
||||
Ok(AgentResourceBinding {
|
||||
resource_id: ResourceId::new(row.try_get::<String, _>("resource_id")?),
|
||||
resource_version: from_db_version(
|
||||
row.try_get::<i32, _>("resource_version")?,
|
||||
"resource_version",
|
||||
)?,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -583,7 +583,7 @@ const SOURCE_SELECT: &str = "select
|
||||
join artifact_blobs b on b.digest = s.blob_digest
|
||||
where s.workspace_id = $1 and s.source_id = $2";
|
||||
|
||||
async fn require_workspace(
|
||||
pub(super) async fn require_workspace(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
) -> Result<(), RegistryError> {
|
||||
@@ -601,7 +601,7 @@ async fn require_workspace(
|
||||
}
|
||||
}
|
||||
|
||||
async fn ensure_blob(
|
||||
pub(super) async fn ensure_blob(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
request: &CreateArtifactSourceRequest<'_>,
|
||||
) -> Result<(), RegistryError> {
|
||||
@@ -736,7 +736,7 @@ async fn global_detached_reference_in_grace(
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
async fn get_source_in_transaction(
|
||||
pub(super) async fn get_source_in_transaction(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
source_id: &ArtifactSourceId,
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
mod agent;
|
||||
mod agent_catalog;
|
||||
mod agent_prompt_bindings;
|
||||
mod agent_resource_bindings;
|
||||
mod api_key;
|
||||
mod approval;
|
||||
mod artifact_source;
|
||||
@@ -15,6 +17,8 @@ mod operation_artifact;
|
||||
mod operation_published;
|
||||
mod pool_config;
|
||||
mod product_event;
|
||||
mod prompt;
|
||||
mod resource;
|
||||
mod secret;
|
||||
mod upstream;
|
||||
mod workspace;
|
||||
@@ -33,26 +37,28 @@ use sqlx::{PgPool, Postgres, Row, Transaction, postgres::PgRow, types::Json};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
pub use pool_config::{PostgresPoolConfig, PostgresPoolConfigError};
|
||||
pub use resource::{AuthorizedResourceRead, BoundResourceAdmission};
|
||||
|
||||
use crate::{
|
||||
error::RegistryError,
|
||||
model::{
|
||||
AdminBootstrapContractRecord, AdminSecurityAuditRequest, AgentSummary, AgentVersionRecord,
|
||||
AppendProductEventOutcome, AppendProductEventRequest, AppliedImportOperation,
|
||||
ApplyImportJobRequest, ApprovalRequestRecord, AuthUserRecord,
|
||||
ConsumeAdminBootstrapContractRequest, CreateAdminBootstrapContractRequest,
|
||||
CreateAgentDraftVersionRequest, CreateAgentRequest, CreateApprovalRequest,
|
||||
CreateImportJobRequest, CreateInvitationRequest, CreateInvocationLogRequest,
|
||||
CreatePlatformApiKeyRequest, CreateSecretRequest, CreateVersionRequest,
|
||||
CreateWorkspaceRequest, CreateYamlImportJobRequest, DecideApprovalRequest,
|
||||
DescriptorMetadata, ExpireApprovalRequest, FinishApprovalRequest, FinishImportJobRequest,
|
||||
ImportConflictMode, ImportJob, ImportJobApplyResult, ImportJobCleanupReport, ImportJobId,
|
||||
ImportJobStatus, InvitationRecord, InvocationHistoryLoss, InvocationHistoryLossCategory,
|
||||
InvocationHistoryWriteOutcome, InvocationLogRecord, InvocationRetentionOutcome,
|
||||
InvocationRetentionPolicy, InvocationRetentionStatus, ListApprovalRequestsQuery,
|
||||
ListInvocationLogsQuery, ListProductEventsQuery, MasterKeyIdentityCandidate,
|
||||
MasterKeyIdentityRecord, MasterKeyRotationRecord, MasterKeyRotationStatus,
|
||||
MembershipRecord, OnboardingEventSnapshot, OnboardingImportChoice, OnboardingImportContext,
|
||||
AdminBootstrapContractRecord, AdminSecurityAuditRequest, AgentPromptBinding,
|
||||
AgentResourceBinding, AgentSummary, AgentVersionRecord, AppendProductEventOutcome,
|
||||
AppendProductEventRequest, AppliedImportOperation, ApplyImportJobRequest,
|
||||
ApprovalRequestRecord, AuthUserRecord, ConsumeAdminBootstrapContractRequest,
|
||||
CreateAdminBootstrapContractRequest, CreateAgentDraftVersionRequest, CreateAgentRequest,
|
||||
CreateApprovalRequest, CreateImportJobRequest, CreateInvitationRequest,
|
||||
CreateInvocationLogRequest, CreatePlatformApiKeyRequest, CreateSecretRequest,
|
||||
CreateVersionRequest, CreateWorkspaceRequest, CreateYamlImportJobRequest,
|
||||
DecideApprovalRequest, DescriptorMetadata, ExpireApprovalRequest, FinishApprovalRequest,
|
||||
FinishImportJobRequest, ImportConflictMode, ImportJob, ImportJobApplyResult,
|
||||
ImportJobCleanupReport, ImportJobId, ImportJobStatus, InvitationRecord,
|
||||
InvocationHistoryLoss, InvocationHistoryLossCategory, InvocationHistoryWriteOutcome,
|
||||
InvocationLogRecord, InvocationRetentionOutcome, InvocationRetentionPolicy,
|
||||
InvocationRetentionStatus, ListApprovalRequestsQuery, ListInvocationLogsQuery,
|
||||
ListProductEventsQuery, MasterKeyIdentityCandidate, MasterKeyIdentityRecord,
|
||||
MasterKeyRotationRecord, MasterKeyRotationStatus, MembershipRecord,
|
||||
OnboardingEventSnapshot, OnboardingImportChoice, OnboardingImportContext,
|
||||
OnboardingImportDrift, OnboardingMilestoneResult, OnboardingPresentationMilestone,
|
||||
OnboardingSnapshot, OperationAgentRef, OperationSampleMetadata, OperationStateExpectation,
|
||||
OperationSummary, OperationUsageSummary, OperationVersionRecord, PlatformApiKeyRecord,
|
||||
@@ -615,6 +621,7 @@ fn build_operation_agent_ref(
|
||||
})
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn build_agent_version_record(
|
||||
summary: &AgentSummary,
|
||||
version: i32,
|
||||
@@ -623,6 +630,8 @@ fn build_agent_version_record(
|
||||
tool_selection_policy_json: Value,
|
||||
created_at: OffsetDateTime,
|
||||
bindings: Vec<AgentOperationBinding>,
|
||||
resource_bindings: Vec<AgentResourceBinding>,
|
||||
prompt_bindings: Vec<AgentPromptBinding>,
|
||||
) -> Result<AgentVersionRecord, RegistryError> {
|
||||
let version = from_db_version(version, "version")?;
|
||||
let status = deserialize_enum_text(&status, "status")?;
|
||||
@@ -634,6 +643,8 @@ fn build_agent_version_record(
|
||||
status,
|
||||
created_at,
|
||||
bindings,
|
||||
resource_bindings,
|
||||
prompt_bindings,
|
||||
snapshot: AgentVersion {
|
||||
agent_id: summary.id.clone(),
|
||||
version,
|
||||
|
||||
@@ -0,0 +1,750 @@
|
||||
use crank_core::{
|
||||
WorkspaceId,
|
||||
ids::{PromptId, ResourceId},
|
||||
prompt::{
|
||||
ArgumentKind, PromptDefinition, PromptDraft, PromptRole, PromptSensitivity, PromptStatus,
|
||||
},
|
||||
prompt_composition::{
|
||||
PromptDependencyPin, PromptDependencySourceClass, effective_sensitivity, unused_dependency,
|
||||
},
|
||||
resource::{ResourceError, ResourceKind},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::{Postgres, Row, types::Json};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use super::{PostgresRegistry, artifact_source::require_workspace};
|
||||
use crate::{
|
||||
RegistryError,
|
||||
model::{
|
||||
AgentPromptBinding, ArchivePromptRequest, CreatePromptDraftRequest, PromptDraftRecord,
|
||||
PromptPublicationRecord, PublishPromptRequest, ResourcePublicationRecord,
|
||||
UpdatePromptDraftRequest,
|
||||
},
|
||||
};
|
||||
|
||||
impl PostgresRegistry {
|
||||
pub async fn create_prompt_draft(
|
||||
&self,
|
||||
request: CreatePromptDraftRequest,
|
||||
) -> Result<PromptDraftRecord, RegistryError> {
|
||||
let dependencies = self
|
||||
.resolve_prompt_dependencies(
|
||||
&request.workspace_id,
|
||||
&request.prompt_id,
|
||||
&request.definition,
|
||||
)
|
||||
.await?;
|
||||
let mut tx = self.pool.begin().await?;
|
||||
require_workspace(&mut tx, &request.workspace_id).await?;
|
||||
sqlx::query("insert into prompts (workspace_id,prompt_id,name,description,status,sensitivity,current_draft_version,created_at,updated_at) values ($1,$2,$3,$4,'draft',$5,1,$6,$6)")
|
||||
.bind(request.workspace_id.as_str()).bind(request.prompt_id.as_str())
|
||||
.bind(request.definition.name()).bind(request.definition.description())
|
||||
.bind(sensitivity_name(request.sensitivity)).bind(request.created_at)
|
||||
.execute(&mut *tx).await?;
|
||||
insert_version(
|
||||
&mut tx,
|
||||
&request.workspace_id,
|
||||
&request.prompt_id,
|
||||
1,
|
||||
&request.definition,
|
||||
&dependencies,
|
||||
request.created_at,
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
self.get_prompt_draft(&request.workspace_id, &request.prompt_id)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn update_prompt_draft(
|
||||
&self,
|
||||
request: UpdatePromptDraftRequest,
|
||||
) -> Result<PromptDraftRecord, RegistryError> {
|
||||
let dependencies = self
|
||||
.resolve_prompt_dependencies(
|
||||
&request.workspace_id,
|
||||
&request.prompt_id,
|
||||
&request.definition,
|
||||
)
|
||||
.await?;
|
||||
let mut tx = self.pool.begin().await?;
|
||||
let row = sqlx::query("select current_draft_version,status,updated_at from prompts where workspace_id=$1 and prompt_id=$2 for update")
|
||||
.bind(request.workspace_id.as_str()).bind(request.prompt_id.as_str())
|
||||
.fetch_optional(&mut *tx).await?.ok_or_else(|| RegistryError::PromptNotFound { prompt_id: request.prompt_id.to_string() })?;
|
||||
let version: i32 = row.try_get("current_draft_version")?;
|
||||
let status: String = row.try_get("status")?;
|
||||
// Правка опубликованного Prompt открывает новый Draft; archived остаётся
|
||||
// терминальным lifecycle-состоянием.
|
||||
if status == "archived" {
|
||||
return Err(RegistryError::PromptNotDraft {
|
||||
prompt_id: request.prompt_id.to_string(),
|
||||
});
|
||||
}
|
||||
let current: OffsetDateTime = row.try_get("updated_at")?;
|
||||
if current != request.expected_updated_at {
|
||||
return Err(RegistryError::PromptStaleRevision {
|
||||
prompt_id: request.prompt_id.to_string(),
|
||||
});
|
||||
}
|
||||
let next = version
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| RegistryError::PromptVersionOverflow {
|
||||
prompt_id: request.prompt_id.to_string(),
|
||||
})?;
|
||||
sqlx::query("update prompts set name=$3,description=$4,sensitivity=$5,status='draft',current_draft_version=$6,updated_at=$7 where workspace_id=$1 and prompt_id=$2")
|
||||
.bind(request.workspace_id.as_str()).bind(request.prompt_id.as_str())
|
||||
.bind(request.definition.name()).bind(request.definition.description()).bind(sensitivity_name(request.sensitivity)).bind(next).bind(request.updated_at)
|
||||
.execute(&mut *tx).await?;
|
||||
insert_version(
|
||||
&mut tx,
|
||||
&request.workspace_id,
|
||||
&request.prompt_id,
|
||||
next,
|
||||
&request.definition,
|
||||
&dependencies,
|
||||
request.updated_at,
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
self.get_prompt_draft(&request.workspace_id, &request.prompt_id)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Публикует текущий Draft как immutable Published Prompt Version.
|
||||
///
|
||||
/// Строка `prompts` блокируется на время транзакции, поэтому два конкурентных
|
||||
/// publish с одинаковым `expected_updated_at` сериализуются: один создаёт
|
||||
/// публикацию, второй видит stale revision и получает 409.
|
||||
pub async fn publish_prompt_draft(
|
||||
&self,
|
||||
request: PublishPromptRequest,
|
||||
) -> Result<PromptDraftRecord, RegistryError> {
|
||||
// Publication re-resolves every pinned dependency in declaration order: a version that was
|
||||
// resolvable when the Draft was saved but is revoked/archived now must block the
|
||||
// publication with the exact position (contract §2), never ship an unusable pin.
|
||||
//
|
||||
// Resolution reads through the pool, so it runs before the write transaction; the version
|
||||
// it resolved is compared with the locked row below, so a concurrent Draft edit can never
|
||||
// publish the pins of another version.
|
||||
let draft = self
|
||||
.get_prompt_draft(&request.workspace_id, &request.prompt_id)
|
||||
.await?;
|
||||
let dependencies = self
|
||||
.resolve_prompt_dependencies(
|
||||
&request.workspace_id,
|
||||
&request.prompt_id,
|
||||
draft.prompt.definition(),
|
||||
)
|
||||
.await?;
|
||||
let mut tx = self.pool.begin().await?;
|
||||
let row = sqlx::query("select current_draft_version,status,updated_at,name,description,sensitivity from prompts where workspace_id=$1 and prompt_id=$2 for update")
|
||||
.bind(request.workspace_id.as_str()).bind(request.prompt_id.as_str())
|
||||
.fetch_optional(&mut *tx).await?.ok_or_else(|| RegistryError::PromptNotFound { prompt_id: request.prompt_id.to_string() })?;
|
||||
let status: String = row.try_get("status")?;
|
||||
if status == "archived" {
|
||||
return Err(RegistryError::PromptNotDraft {
|
||||
prompt_id: request.prompt_id.to_string(),
|
||||
});
|
||||
}
|
||||
let current: OffsetDateTime = row.try_get("updated_at")?;
|
||||
if current != request.expected_updated_at {
|
||||
return Err(RegistryError::PromptStaleRevision {
|
||||
prompt_id: request.prompt_id.to_string(),
|
||||
});
|
||||
}
|
||||
let version: i32 = row.try_get("current_draft_version")?;
|
||||
if i32::try_from(draft.prompt.version()).ok() != Some(version) {
|
||||
return Err(RegistryError::PromptStaleRevision {
|
||||
prompt_id: request.prompt_id.to_string(),
|
||||
});
|
||||
}
|
||||
let already_published = sqlx::query_scalar::<_, bool>(
|
||||
"select exists (select 1 from prompt_publications
|
||||
where workspace_id=$1 and prompt_id=$2 and version=$3)",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.prompt_id.as_str())
|
||||
.bind(version)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
if already_published {
|
||||
return Err(RegistryError::PromptPublicationConflict {
|
||||
prompt_id: request.prompt_id.to_string(),
|
||||
});
|
||||
}
|
||||
let local =
|
||||
parse_sensitivity(&row.try_get::<String, _>("sensitivity")?).ok_or_else(|| {
|
||||
RegistryError::PromptCorrupt {
|
||||
prompt_id: request.prompt_id.to_string(),
|
||||
}
|
||||
})?;
|
||||
// AC3: the publication stores the strictest policy of the prompt and its pins.
|
||||
let effective = effective_sensitivity(local, &dependencies);
|
||||
sqlx::query("insert into prompt_publications (workspace_id,prompt_id,version,name,description,sensitivity,published_at) values ($1,$2,$3,$4,$5,$6,$7)")
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.prompt_id.as_str())
|
||||
.bind(version)
|
||||
.bind(row.try_get::<String, _>("name")?)
|
||||
.bind(row.try_get::<String, _>("description")?)
|
||||
.bind(sensitivity_name(effective))
|
||||
.bind(request.published_at)
|
||||
.execute(&mut *tx).await?;
|
||||
sqlx::query("update prompts set status='published',latest_published_version=$3,updated_at=$4 where workspace_id=$1 and prompt_id=$2")
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.prompt_id.as_str())
|
||||
.bind(version)
|
||||
.bind(request.published_at)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
self.get_prompt_draft(&request.workspace_id, &request.prompt_id)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Архив — lifecycle-состояние, а не security revoke: уже immutable
|
||||
/// публикации и definition остаются доступными по точной версии.
|
||||
pub async fn archive_prompt_draft(
|
||||
&self,
|
||||
request: ArchivePromptRequest,
|
||||
) -> Result<PromptDraftRecord, RegistryError> {
|
||||
let mut tx = self.pool.begin().await?;
|
||||
let row = sqlx::query(
|
||||
"select updated_at from prompts where workspace_id=$1 and prompt_id=$2 for update",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.prompt_id.as_str())
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
.ok_or_else(|| RegistryError::PromptNotFound {
|
||||
prompt_id: request.prompt_id.to_string(),
|
||||
})?;
|
||||
let current: OffsetDateTime = row.try_get("updated_at")?;
|
||||
if current != request.expected_updated_at {
|
||||
return Err(RegistryError::PromptStaleRevision {
|
||||
prompt_id: request.prompt_id.to_string(),
|
||||
});
|
||||
}
|
||||
sqlx::query("update prompts set status='archived',updated_at=$3 where workspace_id=$1 and prompt_id=$2")
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.prompt_id.as_str())
|
||||
.bind(request.archived_at)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
self.get_prompt_draft(&request.workspace_id, &request.prompt_id)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn list_prompt_drafts(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
) -> Result<Vec<PromptDraftRecord>, RegistryError> {
|
||||
let ids = sqlx::query_scalar::<_, String>(
|
||||
"select prompt_id from prompts where workspace_id=$1 order by created_at,prompt_id",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
let mut prompts = Vec::with_capacity(ids.len());
|
||||
for id in ids {
|
||||
prompts.push(
|
||||
self.get_prompt_draft(workspace_id, &PromptId::new(id))
|
||||
.await?,
|
||||
);
|
||||
}
|
||||
Ok(prompts)
|
||||
}
|
||||
|
||||
pub async fn get_prompt_draft(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
prompt_id: &PromptId,
|
||||
) -> Result<PromptDraftRecord, RegistryError> {
|
||||
let row = sqlx::query("select name,description,status,sensitivity,current_draft_version,latest_published_version,created_at,updated_at from prompts where workspace_id=$1 and prompt_id=$2")
|
||||
.bind(workspace_id.as_str()).bind(prompt_id.as_str()).fetch_optional(&self.pool).await?
|
||||
.ok_or_else(|| RegistryError::PromptNotFound { prompt_id: prompt_id.to_string() })?;
|
||||
let version: i32 = row.try_get("current_draft_version")?;
|
||||
let latest_published_version = row
|
||||
.try_get::<Option<i32>, _>("latest_published_version")?
|
||||
.map(|value| db_version(value, prompt_id))
|
||||
.transpose()?;
|
||||
let (definition, dependencies) = read_definition(
|
||||
&self.pool,
|
||||
workspace_id,
|
||||
prompt_id,
|
||||
version,
|
||||
&row.try_get::<String, _>("name")?,
|
||||
&row.try_get::<String, _>("description")?,
|
||||
)
|
||||
.await?;
|
||||
let status = parse_status(&row.try_get::<String, _>("status")?).ok_or_else(|| {
|
||||
RegistryError::PromptCorrupt {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
}
|
||||
})?;
|
||||
let sensitivity =
|
||||
parse_sensitivity(&row.try_get::<String, _>("sensitivity")?).ok_or_else(|| {
|
||||
RegistryError::PromptCorrupt {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
}
|
||||
})?;
|
||||
let version = db_version(version, prompt_id)?;
|
||||
let prompt =
|
||||
PromptDraft::from_parts(prompt_id.clone(), version, status, sensitivity, definition)
|
||||
.map_err(|_| RegistryError::PromptCorrupt {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
})?;
|
||||
Ok(PromptDraftRecord {
|
||||
prompt,
|
||||
latest_published_version,
|
||||
dependencies,
|
||||
created_at: row.try_get("created_at")?,
|
||||
updated_at: row.try_get("updated_at")?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Exact read immutable Published Prompt Version по точному номеру.
|
||||
pub async fn get_published_prompt_version(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
prompt_id: &PromptId,
|
||||
version: u32,
|
||||
) -> Result<PromptPublicationRecord, RegistryError> {
|
||||
let version =
|
||||
i32::try_from(version).map_err(|_| RegistryError::PromptPublicationNotFound {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
})?;
|
||||
let row = sqlx::query("select name,description,sensitivity,published_at from prompt_publications where workspace_id=$1 and prompt_id=$2 and version=$3")
|
||||
.bind(workspace_id.as_str()).bind(prompt_id.as_str()).bind(version)
|
||||
.fetch_optional(&self.pool).await?
|
||||
.ok_or_else(|| RegistryError::PromptPublicationNotFound { prompt_id: prompt_id.to_string() })?;
|
||||
let (definition, dependencies) = read_definition(
|
||||
&self.pool,
|
||||
workspace_id,
|
||||
prompt_id,
|
||||
version,
|
||||
&row.try_get::<String, _>("name")?,
|
||||
&row.try_get::<String, _>("description")?,
|
||||
)
|
||||
.await?;
|
||||
let sensitivity =
|
||||
parse_sensitivity(&row.try_get::<String, _>("sensitivity")?).ok_or_else(|| {
|
||||
RegistryError::PromptCorrupt {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
}
|
||||
})?;
|
||||
Ok(PromptPublicationRecord {
|
||||
prompt_id: prompt_id.clone(),
|
||||
version: db_version(version, prompt_id)?,
|
||||
name: row.try_get("name")?,
|
||||
description: row.try_get("description")?,
|
||||
sensitivity,
|
||||
definition,
|
||||
dependencies,
|
||||
published_at: row.try_get("published_at")?,
|
||||
})
|
||||
}
|
||||
/// Разрешает `dependencies` определения в точные пины в порядке объявления (contract §2).
|
||||
///
|
||||
/// Тот же exact-version read path, что у 3.8/3.14: статическая версия читается из
|
||||
/// `resource_publications`, template-версия — из definition-only публикации 3.10. Отзыв,
|
||||
/// чужая или отсутствующая версия неотличимы (один код и source path), а `binary` не имеет
|
||||
/// текстового представления. Неиспользуемая зависимость отклоняется до любого чтения.
|
||||
async fn resolve_prompt_dependencies(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
prompt_id: &PromptId,
|
||||
definition: &PromptDefinition,
|
||||
) -> Result<Vec<PromptDependencyPin>, RegistryError> {
|
||||
if let Some(position) = unused_dependency(definition) {
|
||||
let dependency = &definition.dependencies()[position];
|
||||
return Err(RegistryError::PromptDependencyUnused {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
position,
|
||||
resource_id: dependency.resource_id.clone(),
|
||||
version: dependency.version,
|
||||
});
|
||||
}
|
||||
let mut pins = Vec::with_capacity(definition.dependencies().len());
|
||||
for (position, dependency) in definition.dependencies().iter().enumerate() {
|
||||
let resource_id = ResourceId::new(dependency.resource_id.clone());
|
||||
let unresolved = || RegistryError::PromptDependencyUnresolved {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
position,
|
||||
resource_id: dependency.resource_id.clone(),
|
||||
version: dependency.version,
|
||||
};
|
||||
let revoked: bool = sqlx::query_scalar(
|
||||
"select exists (select 1 from resource_security_revocations
|
||||
where workspace_id=$1 and resource_id=$2)",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(resource_id.as_str())
|
||||
.fetch_one(&self.pool)
|
||||
.await?;
|
||||
if revoked {
|
||||
return Err(unresolved());
|
||||
}
|
||||
let pin = match self
|
||||
.resolve_resource_publication(
|
||||
workspace_id.as_str(),
|
||||
&resource_id,
|
||||
dependency.version,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(resolved) => pin_from(
|
||||
prompt_id,
|
||||
position,
|
||||
&resolved.publication,
|
||||
PromptDependencySourceClass::Static,
|
||||
),
|
||||
Err(ResourceError::NotFound) => {
|
||||
match self
|
||||
.resolve_resource_template_publication(
|
||||
workspace_id.as_str(),
|
||||
&resource_id,
|
||||
dependency.version,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((publication, _source)) => pin_from(
|
||||
prompt_id,
|
||||
position,
|
||||
&publication,
|
||||
PromptDependencySourceClass::Dynamic,
|
||||
),
|
||||
Err(ResourceError::NotFound) => return Err(unresolved()),
|
||||
Err(_) => {
|
||||
return Err(RegistryError::PromptDependencyUnavailable {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
position,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
return Err(RegistryError::PromptDependencyUnavailable {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
position,
|
||||
});
|
||||
}
|
||||
}?;
|
||||
pins.push(pin);
|
||||
}
|
||||
Ok(pins)
|
||||
}
|
||||
|
||||
/// Exact reads of the immutable Published Prompt Versions bound to one published Agent
|
||||
/// snapshot (Story 3.14).
|
||||
///
|
||||
/// The bindings are the exact `agent_prompt_bindings` rows of that Agent version, so the
|
||||
/// result is the same immutable array on every call: a later Draft edit or archive of the
|
||||
/// Prompt changes neither the resolvable version nor its definition. A binding without its
|
||||
/// exact publication row is a fail-closed error — `prompts/list`/`prompts/get` must never
|
||||
/// serve a silently shortened snapshot.
|
||||
pub async fn resolve_bound_prompt_publications(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
bindings: &[AgentPromptBinding],
|
||||
) -> Result<Vec<PromptPublicationRecord>, RegistryError> {
|
||||
let mut publications = Vec::with_capacity(bindings.len());
|
||||
for binding in bindings {
|
||||
publications.push(
|
||||
self.get_published_prompt_version(
|
||||
workspace_id,
|
||||
&binding.prompt_id,
|
||||
binding.prompt_version,
|
||||
)
|
||||
.await?,
|
||||
);
|
||||
}
|
||||
Ok(publications)
|
||||
}
|
||||
}
|
||||
|
||||
async fn read_definition(
|
||||
pool: &sqlx::PgPool,
|
||||
workspace_id: &WorkspaceId,
|
||||
prompt_id: &PromptId,
|
||||
version: i32,
|
||||
name: &str,
|
||||
description: &str,
|
||||
) -> Result<(PromptDefinition, Vec<PromptDependencyPin>), RegistryError> {
|
||||
let dependencies = read_dependencies(pool, workspace_id, prompt_id, version).await?;
|
||||
let arguments = sqlx::query("select argument_name,argument_type,required,default_value,enumeration from prompt_arguments where workspace_id=$1 and prompt_id=$2 and version=$3 order by position")
|
||||
.bind(workspace_id.as_str()).bind(prompt_id.as_str()).bind(version).fetch_all(pool).await?;
|
||||
let mut args = Vec::with_capacity(arguments.len());
|
||||
for argument in arguments {
|
||||
let default: Option<Json<Value>> = argument.try_get("default_value")?;
|
||||
let enumeration: Option<Json<Value>> = argument.try_get("enumeration")?;
|
||||
let mut item = serde_json::Map::new();
|
||||
item.insert(
|
||||
"name".into(),
|
||||
json!(argument.try_get::<String, _>("argument_name")?),
|
||||
);
|
||||
item.insert(
|
||||
"required".into(),
|
||||
json!(argument.try_get::<bool, _>("required")?),
|
||||
);
|
||||
let mut schema = serde_json::Map::new();
|
||||
schema.insert(
|
||||
"type".into(),
|
||||
json!(argument.try_get::<String, _>("argument_type")?),
|
||||
);
|
||||
if let Some(Json(value)) = enumeration {
|
||||
schema.insert("enum".into(), value);
|
||||
}
|
||||
item.insert("schema".into(), Value::Object(schema));
|
||||
if let Some(Json(value)) = default {
|
||||
item.insert("default".into(), value);
|
||||
}
|
||||
args.push(Value::Object(item));
|
||||
}
|
||||
let messages = sqlx::query("select position,role,content from prompt_messages where workspace_id=$1 and prompt_id=$2 and version=$3 order by position")
|
||||
.bind(workspace_id.as_str()).bind(prompt_id.as_str()).bind(version).fetch_all(pool).await?;
|
||||
let refs = read_resource_refs(pool, workspace_id, prompt_id, version).await?;
|
||||
let mut msgs = Vec::with_capacity(messages.len());
|
||||
for message in messages {
|
||||
let position = message.try_get::<i32, _>("position")?;
|
||||
let mut item = json!({
|
||||
"role": message.try_get::<String, _>("role")?,
|
||||
"content": message.try_get::<String, _>("content")?,
|
||||
});
|
||||
if let Some(indices) = refs.get(&position) {
|
||||
item["resource_refs"] = json!(indices);
|
||||
}
|
||||
msgs.push(item);
|
||||
}
|
||||
let definition = PromptDefinition::parse(&json!({
|
||||
"name": name,
|
||||
"description": description,
|
||||
"arguments": args,
|
||||
"messages": msgs,
|
||||
"dependencies": dependencies
|
||||
.iter()
|
||||
.map(|pin| json!({"resource_id": pin.resource_id, "version": pin.version}))
|
||||
.collect::<Vec<_>>(),
|
||||
}))
|
||||
.map_err(|_| RegistryError::PromptCorrupt {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
})?;
|
||||
Ok((definition, dependencies))
|
||||
}
|
||||
|
||||
/// Упорядоченные точки вставки по номеру сообщения: `message.position -> [dependency index]`.
|
||||
async fn read_resource_refs(
|
||||
pool: &sqlx::PgPool,
|
||||
workspace_id: &WorkspaceId,
|
||||
prompt_id: &PromptId,
|
||||
version: i32,
|
||||
) -> Result<std::collections::BTreeMap<i32, Vec<usize>>, RegistryError> {
|
||||
let rows = sqlx::query(
|
||||
"select message_position,dependency_position
|
||||
from prompt_message_resource_refs
|
||||
where workspace_id=$1 and prompt_id=$2 and version=$3
|
||||
order by message_position,ref_position",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(prompt_id.as_str())
|
||||
.bind(version)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
let mut refs = std::collections::BTreeMap::<i32, Vec<usize>>::new();
|
||||
for row in rows {
|
||||
let message = row.try_get::<i32, _>("message_position")?;
|
||||
let dependency = row.try_get::<i32, _>("dependency_position")?;
|
||||
let dependency = usize::try_from(dependency).map_err(|_| RegistryError::PromptCorrupt {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
})?;
|
||||
refs.entry(message).or_default().push(dependency);
|
||||
}
|
||||
Ok(refs)
|
||||
}
|
||||
|
||||
/// Version-keyed pins in declaration order; a corrupt row is a fail-closed error.
|
||||
async fn read_dependencies(
|
||||
pool: &sqlx::PgPool,
|
||||
workspace_id: &WorkspaceId,
|
||||
prompt_id: &PromptId,
|
||||
version: i32,
|
||||
) -> Result<Vec<PromptDependencyPin>, RegistryError> {
|
||||
let rows = sqlx::query(
|
||||
"select dependency_position,resource_id,resource_version,digest,kind,mime_type,source_class,sensitivity
|
||||
from prompt_dependencies
|
||||
where workspace_id=$1 and prompt_id=$2 and version=$3
|
||||
order by dependency_position",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(prompt_id.as_str())
|
||||
.bind(version)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
rows.iter()
|
||||
.map(|row| {
|
||||
let corrupt = || RegistryError::PromptCorrupt {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
};
|
||||
let position = usize::try_from(row.try_get::<i32, _>("dependency_position")?)
|
||||
.map_err(|_| corrupt())?;
|
||||
let resource_version =
|
||||
u32::try_from(row.try_get::<i32, _>("resource_version")?).map_err(|_| corrupt())?;
|
||||
let kind =
|
||||
ResourceKind::parse(&row.try_get::<String, _>("kind")?).ok_or_else(corrupt)?;
|
||||
let source_class =
|
||||
PromptDependencySourceClass::parse(&row.try_get::<String, _>("source_class")?)
|
||||
.ok_or_else(corrupt)?;
|
||||
let sensitivity =
|
||||
parse_sensitivity(&row.try_get::<String, _>("sensitivity")?).ok_or_else(corrupt)?;
|
||||
Ok(PromptDependencyPin {
|
||||
position,
|
||||
resource_id: row.try_get("resource_id")?,
|
||||
version: resource_version,
|
||||
digest: row.try_get("digest")?,
|
||||
kind,
|
||||
mime_type: row.try_get("mime_type")?,
|
||||
source_class,
|
||||
sensitivity,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn insert_version(
|
||||
tx: &mut sqlx::Transaction<'_, Postgres>,
|
||||
workspace: &WorkspaceId,
|
||||
prompt: &PromptId,
|
||||
version: i32,
|
||||
definition: &PromptDefinition,
|
||||
dependencies: &[PromptDependencyPin],
|
||||
at: OffsetDateTime,
|
||||
) -> Result<(), RegistryError> {
|
||||
sqlx::query("insert into prompt_versions (workspace_id,prompt_id,version,created_at) values ($1,$2,$3,$4)")
|
||||
.bind(workspace.as_str()).bind(prompt.as_str()).bind(version).bind(at).execute(&mut **tx).await?;
|
||||
for (position, argument) in definition.arguments().iter().enumerate() {
|
||||
let kind = match argument.kind() {
|
||||
ArgumentKind::String => "string",
|
||||
ArgumentKind::Number => "number",
|
||||
ArgumentKind::Integer => "integer",
|
||||
ArgumentKind::Boolean => "boolean",
|
||||
};
|
||||
let default = argument.default().cloned().map(Json);
|
||||
let enumeration = if argument.enumeration().is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(Json(Value::Array(argument.enumeration().to_vec())))
|
||||
};
|
||||
sqlx::query("insert into prompt_arguments (workspace_id,prompt_id,version,argument_name,argument_type,required,default_value,enumeration,position) values ($1,$2,$3,$4,$5,$6,$7,$8,$9)")
|
||||
.bind(workspace.as_str()).bind(prompt.as_str()).bind(version).bind(argument.name()).bind(kind).bind(argument.required()).bind(default).bind(enumeration).bind(i32::try_from(position).unwrap_or(i32::MAX)).execute(&mut **tx).await?;
|
||||
}
|
||||
for (position, message) in definition.messages().iter().enumerate() {
|
||||
let role = match message.role {
|
||||
PromptRole::System => "system",
|
||||
PromptRole::User => "user",
|
||||
PromptRole::Assistant => "assistant",
|
||||
};
|
||||
let message_position = i32::try_from(position).unwrap_or(i32::MAX);
|
||||
sqlx::query("insert into prompt_messages (workspace_id,prompt_id,version,position,role,content) values ($1,$2,$3,$4,$5,$6)")
|
||||
.bind(workspace.as_str()).bind(prompt.as_str()).bind(version).bind(message_position).bind(role).bind(&message.content).execute(&mut **tx).await?;
|
||||
for (ref_position, dependency_position) in message.resource_refs.iter().enumerate() {
|
||||
sqlx::query("insert into prompt_message_resource_refs (workspace_id,prompt_id,version,message_position,ref_position,dependency_position) values ($1,$2,$3,$4,$5,$6)")
|
||||
.bind(workspace.as_str())
|
||||
.bind(prompt.as_str())
|
||||
.bind(version)
|
||||
.bind(message_position)
|
||||
.bind(i32::try_from(ref_position).unwrap_or(i32::MAX))
|
||||
.bind(i32::try_from(*dependency_position).unwrap_or(i32::MAX))
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
for pin in dependencies {
|
||||
sqlx::query("insert into prompt_dependencies (workspace_id,prompt_id,version,dependency_position,resource_id,resource_version,digest,kind,mime_type,source_class,sensitivity) values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)")
|
||||
.bind(workspace.as_str())
|
||||
.bind(prompt.as_str())
|
||||
.bind(version)
|
||||
.bind(i32::try_from(pin.position).unwrap_or(i32::MAX))
|
||||
.bind(&pin.resource_id)
|
||||
.bind(i32::try_from(pin.version).unwrap_or(i32::MAX))
|
||||
.bind(&pin.digest)
|
||||
.bind(pin.kind.as_str())
|
||||
.bind(&pin.mime_type)
|
||||
.bind(pin.source_class.as_str())
|
||||
.bind(sensitivity_name(pin.sensitivity))
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn db_version(value: i32, prompt_id: &PromptId) -> Result<u32, RegistryError> {
|
||||
u32::try_from(value).map_err(|_| RegistryError::PromptCorrupt {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
fn sensitivity_name(s: PromptSensitivity) -> &'static str {
|
||||
match s {
|
||||
PromptSensitivity::Public => "public",
|
||||
PromptSensitivity::Internal => "internal",
|
||||
PromptSensitivity::Secret => "secret",
|
||||
}
|
||||
}
|
||||
fn parse_sensitivity(value: &str) -> Option<PromptSensitivity> {
|
||||
match value {
|
||||
"public" => Some(PromptSensitivity::Public),
|
||||
"internal" => Some(PromptSensitivity::Internal),
|
||||
"secret" => Some(PromptSensitivity::Secret),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn parse_status(value: &str) -> Option<PromptStatus> {
|
||||
match value {
|
||||
"draft" => Some(PromptStatus::Draft),
|
||||
"published" => Some(PromptStatus::Published),
|
||||
"archived" => Some(PromptStatus::Archived),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Пин зависимости из точной опубликованной версии Resource; `binary` не имеет текстового
|
||||
/// представления и отклоняется тем же кодом, что и на рендере (contract §4).
|
||||
fn pin_from(
|
||||
prompt_id: &PromptId,
|
||||
position: usize,
|
||||
publication: &ResourcePublicationRecord,
|
||||
source_class: PromptDependencySourceClass,
|
||||
) -> Result<PromptDependencyPin, RegistryError> {
|
||||
let kind = ResourceKind::parse(&publication.kind).ok_or_else(|| {
|
||||
RegistryError::PromptDependencyRepresentationUnsupported {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
position,
|
||||
resource_id: publication.resource_id.as_str().to_owned(),
|
||||
version: publication.version,
|
||||
}
|
||||
})?;
|
||||
if kind == ResourceKind::Binary {
|
||||
return Err(RegistryError::PromptDependencyRepresentationUnsupported {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
position,
|
||||
resource_id: publication.resource_id.as_str().to_owned(),
|
||||
version: publication.version,
|
||||
});
|
||||
}
|
||||
let sensitivity = parse_sensitivity(&publication.sensitivity).ok_or_else(|| {
|
||||
RegistryError::PromptCorrupt {
|
||||
prompt_id: prompt_id.to_string(),
|
||||
}
|
||||
})?;
|
||||
Ok(PromptDependencyPin {
|
||||
position,
|
||||
resource_id: publication.resource_id.as_str().to_owned(),
|
||||
version: publication.version,
|
||||
digest: publication.digest.clone(),
|
||||
kind,
|
||||
mime_type: publication.mime_type.clone(),
|
||||
source_class,
|
||||
sensitivity,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,859 @@
|
||||
//! Persistence Story 3.6: typed static Resource Drafts (V16).
|
||||
//!
|
||||
//! Каждая мутация — **одна** транзакция (D-15). Самокоммитящие
|
||||
//! `create_artifact_source`/`detach_artifact_source` здесь не вызываются: вместо них
|
||||
//! используется локальный SQL в уже открытой транзакции, а из общего кода
|
||||
//! переиспользуются tx-local helper-ы `require_workspace`, `ensure_blob`,
|
||||
//! `get_source_in_transaction` (видимость `pub(super)`, логика не менялась).
|
||||
//!
|
||||
//! Физическое чтение байт сюда **не** входит: `resolve_resource_version` делает
|
||||
//! workspace-scoped join версии/ссылки/blob и все metadata-сверки, а байты читает
|
||||
//! сервис на единственной наблюдаемой точке чтения (D-19).
|
||||
|
||||
use crank_artifacts::ArtifactRef;
|
||||
use crank_core::WorkspaceId;
|
||||
use crank_core::ids::{AgentId, ResourceId};
|
||||
use crank_core::resource::{ResourceError, ResourceSensitivity, ResourceStatus};
|
||||
use sqlx::{Postgres, Row, Transaction, postgres::PgRow};
|
||||
|
||||
use crate::RegistryError;
|
||||
use crate::model::resource::{
|
||||
CreateResourceDraftRequest, MAX_RESOURCE_DRAFT_PAGE_SIZE, PublishResourceVersionRequest,
|
||||
ResolvedResourcePublication, ResolvedResourceVersion, ResourceDraftRecord,
|
||||
ResourcePublicationRecord, ResourceRecord, ResourceVersionRecord, UpdateResourceDraftRequest,
|
||||
};
|
||||
use crate::model::{
|
||||
ArtifactSourceId, ArtifactSourceLifecycle, ArtifactSourceSensitivity,
|
||||
CreateArtifactSourceRequest,
|
||||
};
|
||||
|
||||
use super::PostgresRegistry;
|
||||
use super::artifact_source::{ensure_blob, get_source_in_transaction, require_workspace};
|
||||
|
||||
mod archive;
|
||||
mod publication;
|
||||
mod read;
|
||||
mod revocation;
|
||||
mod template;
|
||||
|
||||
pub use revocation::{AuthorizedResourceRead, BoundResourceAdmission};
|
||||
|
||||
use publication::resolved_publication;
|
||||
|
||||
const RESOURCE_ID_PREFIX: &str = "res_";
|
||||
const MAX_SOURCE_TAIL_BYTES: usize = 96;
|
||||
|
||||
const DRAFT_SELECT: &str = "select
|
||||
r.workspace_id, r.resource_id, r.uri, r.name, r.description, r.status, r.kind,
|
||||
r.current_draft_version, r.created_at as resource_created_at,
|
||||
r.updated_at as resource_updated_at,
|
||||
(select max(p.version) from resource_publications p
|
||||
where p.workspace_id = r.workspace_id and p.resource_id = r.resource_id)
|
||||
as latest_published_version,
|
||||
v.version, v.kind as version_kind, v.mime_type as version_mime_type,
|
||||
v.size_bytes as version_size_bytes, v.digest as version_digest,
|
||||
v.sensitivity as version_sensitivity, v.source_kind as version_source_kind,
|
||||
v.created_at as version_created_at,
|
||||
v.superseded_at
|
||||
from resources r
|
||||
join resource_versions v
|
||||
on v.workspace_id = r.workspace_id
|
||||
and v.resource_id = r.resource_id
|
||||
where r.workspace_id = $1 and r.resource_id = $2 and v.superseded_at is null";
|
||||
|
||||
const DRAFT_LIST_SELECT: &str = "select
|
||||
r.workspace_id, r.resource_id, r.uri, r.name, r.description, r.status, r.kind,
|
||||
r.current_draft_version, r.created_at as resource_created_at,
|
||||
r.updated_at as resource_updated_at,
|
||||
(select max(p.version) from resource_publications p
|
||||
where p.workspace_id = r.workspace_id and p.resource_id = r.resource_id)
|
||||
as latest_published_version,
|
||||
v.version, v.kind as version_kind, v.mime_type as version_mime_type,
|
||||
v.size_bytes as version_size_bytes, v.digest as version_digest,
|
||||
v.sensitivity as version_sensitivity, v.source_kind as version_source_kind,
|
||||
v.created_at as version_created_at,
|
||||
v.superseded_at
|
||||
from resources r
|
||||
join resource_versions v
|
||||
on v.workspace_id = r.workspace_id
|
||||
and v.resource_id = r.resource_id
|
||||
where r.workspace_id = $1 and v.superseded_at is null
|
||||
order by r.created_at asc, r.resource_id asc
|
||||
limit $2";
|
||||
|
||||
const VERSION_SELECT: &str = "select
|
||||
version, kind as version_kind, mime_type as version_mime_type,
|
||||
size_bytes as version_size_bytes, digest as version_digest,
|
||||
sensitivity as version_sensitivity, source_kind as version_source_kind,
|
||||
created_at as version_created_at, superseded_at
|
||||
from resource_versions
|
||||
where workspace_id = $1 and resource_id = $2 and superseded_at is null";
|
||||
|
||||
const PUBLICATION_SELECT: &str = "select
|
||||
p.resource_id, p.version, p.uri, p.name, p.description, p.kind,
|
||||
p.mime_type, p.size_bytes, p.digest, p.sensitivity, p.source_kind, p.published_at,
|
||||
s.blob_digest, s.mime_type as source_mime_type,
|
||||
s.sensitivity as source_sensitivity, s.lifecycle as source_lifecycle,
|
||||
b.artifact_ref, b.size_bytes as blob_size_bytes,
|
||||
b.storage_lifecycle as blob_lifecycle
|
||||
from resource_publications p
|
||||
join artifact_sources s
|
||||
on s.workspace_id = p.workspace_id and s.source_id = p.artifact_source_id
|
||||
join artifact_blobs b on b.digest = s.blob_digest
|
||||
where p.workspace_id = $1 and p.resource_id = $2 and p.version = $3";
|
||||
|
||||
const RESOLVE_SELECT: &str = "select
|
||||
r.resource_id, r.uri, r.name, r.description, r.status, r.kind,
|
||||
r.current_draft_version, r.created_at as resource_created_at,
|
||||
r.updated_at as resource_updated_at,
|
||||
(select max(p.version) from resource_publications p
|
||||
where p.workspace_id = r.workspace_id and p.resource_id = r.resource_id)
|
||||
as latest_published_version,
|
||||
v.version, v.kind as version_kind, v.mime_type as version_mime_type,
|
||||
v.size_bytes as version_size_bytes, v.digest as version_digest,
|
||||
v.sensitivity as version_sensitivity, v.source_kind as version_source_kind,
|
||||
v.created_at as version_created_at,
|
||||
v.superseded_at,
|
||||
s.blob_digest, s.mime_type as source_mime_type,
|
||||
s.sensitivity as source_sensitivity, s.lifecycle as source_lifecycle,
|
||||
b.artifact_ref, b.size_bytes as blob_size_bytes,
|
||||
b.storage_lifecycle as blob_lifecycle
|
||||
from resource_versions v
|
||||
join resources r
|
||||
on r.workspace_id = v.workspace_id and r.resource_id = v.resource_id
|
||||
join artifact_sources s
|
||||
on s.workspace_id = v.workspace_id and s.source_id = v.artifact_source_id
|
||||
join artifact_blobs b on b.digest = s.blob_digest
|
||||
where v.workspace_id = $1 and v.resource_id = $2
|
||||
and (($3::int is null and v.superseded_at is null) or v.version = $3)";
|
||||
|
||||
impl PostgresRegistry {
|
||||
/// Id behind the authenticated published Agent route, for AgentSnapshot execution origin.
|
||||
pub async fn published_agent_id(
|
||||
&self,
|
||||
workspace_slug: &str,
|
||||
agent_slug: &str,
|
||||
) -> Result<AgentId, RegistryError> {
|
||||
let id: Option<String> = sqlx::query_scalar(
|
||||
"select a.id from workspaces w join agents a on a.workspace_id=w.id join published_agents pa on pa.agent_id=a.id where w.slug=$1 and a.slug=$2 and a.status='published'",
|
||||
)
|
||||
.bind(workspace_slug)
|
||||
.bind(agent_slug)
|
||||
.fetch_optional(self.pool())
|
||||
.await?;
|
||||
id.map(AgentId::new)
|
||||
.ok_or_else(|| RegistryError::PublishedAgentNotFound {
|
||||
workspace_slug: workspace_slug.to_owned(),
|
||||
agent_slug: agent_slug.to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Создание Draft: bytes уже durable (`RegisteredArtifact`), реестр добавляет
|
||||
/// blob-метаданные, активную owning-ссылку, строку Resource и версию 1.
|
||||
pub async fn create_resource_draft(
|
||||
&self,
|
||||
request: CreateResourceDraftRequest,
|
||||
) -> Result<ResourceDraftRecord, ResourceError> {
|
||||
let source_id = version_source_id(&request.resource_id, 1)?;
|
||||
let sensitivity = parse_sensitivity(&request.sensitivity)?;
|
||||
let source_request = CreateArtifactSourceRequest {
|
||||
workspace_id: &request.workspace_id,
|
||||
source_id: &source_id,
|
||||
artifact: &request.artifact,
|
||||
mime_type: &request.mime_type,
|
||||
sensitivity,
|
||||
created_at: request.created_at,
|
||||
};
|
||||
|
||||
let mut transaction = self
|
||||
.pool()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
require_workspace(&mut transaction, &request.workspace_id)
|
||||
.await
|
||||
.map_err(map_registry_error)?;
|
||||
ensure_blob(&mut transaction, &source_request)
|
||||
.await
|
||||
.map_err(map_registry_error)?;
|
||||
|
||||
// Строгий insert: повторный create с тем же resource_id обязан упасть
|
||||
// на PK, а не тихо игнорироваться (D-15 шаг 4).
|
||||
sqlx::query(
|
||||
"insert into artifact_sources (
|
||||
workspace_id, source_id, blob_digest, mime_type, sensitivity,
|
||||
lifecycle, created_at, updated_at, detached_at
|
||||
) values ($1, $2, $3, $4, $5, 'active', $6, $6, null)",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(source_id.as_str())
|
||||
.bind(request.artifact.artifact_ref().digest_hex())
|
||||
.bind(&request.mime_type)
|
||||
.bind(&request.sensitivity)
|
||||
.bind(request.created_at)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(map_write_error)?;
|
||||
|
||||
sqlx::query(
|
||||
"insert into resources (
|
||||
workspace_id, resource_id, uri, name, description, status, kind,
|
||||
current_draft_version, created_at, updated_at
|
||||
) values ($1, $2, $3, $4, $5, 'draft', $6, 1, $7, $7)",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.bind(&request.uri)
|
||||
.bind(&request.name)
|
||||
.bind(&request.description)
|
||||
.bind(&request.kind)
|
||||
.bind(request.created_at)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(map_write_error)?;
|
||||
|
||||
sqlx::query(
|
||||
"insert into resource_versions (
|
||||
workspace_id, resource_id, version, kind, mime_type, size_bytes, digest,
|
||||
sensitivity, artifact_source_id, created_at, superseded_at
|
||||
) values ($1, $2, 1, $3, $4, $5, $6, $7, $8, $9, null)",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.bind(&request.kind)
|
||||
.bind(&request.mime_type)
|
||||
.bind(size_bytes(&request.artifact)?)
|
||||
.bind(request.artifact.artifact_ref().digest_hex())
|
||||
.bind(&request.sensitivity)
|
||||
.bind(source_id.as_str())
|
||||
.bind(request.created_at)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(map_write_error)?;
|
||||
|
||||
let record = read_draft(
|
||||
&mut transaction,
|
||||
&request.workspace_id,
|
||||
&request.resource_id,
|
||||
)
|
||||
.await?
|
||||
.ok_or(ResourceError::ArtifactIntegrity)?;
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
Ok(record)
|
||||
}
|
||||
|
||||
/// Обновление Draft. Точная последовательность D-15 (шаги 2–9): row-lock,
|
||||
/// precondition, `ensure_blob`, пометка прежней версии **до** вставки новой,
|
||||
/// новая активная ссылка, новая версия, отсоединение старой ссылки,
|
||||
/// переключение указателя — всё в одной транзакции.
|
||||
pub async fn update_resource_draft(
|
||||
&self,
|
||||
request: UpdateResourceDraftRequest,
|
||||
) -> Result<ResourceVersionRecord, ResourceError> {
|
||||
let mut transaction = self
|
||||
.pool()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
|
||||
// Шаг 2: блокировка строки Resource и optimistic precondition.
|
||||
let row = sqlx::query(
|
||||
"select current_draft_version, updated_at
|
||||
from resources
|
||||
where workspace_id = $1 and resource_id = $2
|
||||
for update",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||||
.ok_or(ResourceError::NotFound)?;
|
||||
let current_version: i32 = row
|
||||
.try_get("current_draft_version")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
let recorded_updated_at: time::OffsetDateTime = row
|
||||
.try_get("updated_at")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
if recorded_updated_at != request.expected_updated_at {
|
||||
return Err(ResourceError::Stale);
|
||||
}
|
||||
let current_version =
|
||||
u32::try_from(current_version).map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
|
||||
// Текущая версия читается только по своим собственным полям; её owning-ссылка,
|
||||
// timestamps и lifecycle берутся из artifact_sources (D-15 шаг 2).
|
||||
let current = sqlx::query(
|
||||
"select artifact_source_id
|
||||
from resource_versions
|
||||
where workspace_id = $1 and resource_id = $2 and superseded_at is null",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||||
.ok_or(ResourceError::ArtifactIntegrity)?;
|
||||
let old_source_id = ArtifactSourceId::new(
|
||||
current
|
||||
.try_get::<String, _>("artifact_source_id")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
);
|
||||
let old_source =
|
||||
get_source_in_transaction(&mut transaction, &request.workspace_id, &old_source_id)
|
||||
.await
|
||||
.map_err(map_registry_error)?
|
||||
.ok_or(ResourceError::ArtifactIntegrity)?;
|
||||
if old_source.lifecycle != ArtifactSourceLifecycle::Active {
|
||||
return Err(ResourceError::ArtifactIntegrity);
|
||||
}
|
||||
let old_source_updated_at = old_source.updated_at;
|
||||
|
||||
let now = truncate_to_micros(time::OffsetDateTime::now_utc());
|
||||
let next_version = current_version
|
||||
.checked_add(1)
|
||||
.ok_or(ResourceError::StorageUnavailable)?;
|
||||
let new_source_id = version_source_id(&request.resource_id, next_version)?;
|
||||
let sensitivity = parse_sensitivity(&request.sensitivity)?;
|
||||
let new_source_request = CreateArtifactSourceRequest {
|
||||
workspace_id: &request.workspace_id,
|
||||
source_id: &new_source_id,
|
||||
artifact: &request.artifact,
|
||||
mime_type: &request.mime_type,
|
||||
sensitivity,
|
||||
created_at: now,
|
||||
};
|
||||
|
||||
// Шаг 3: новые bytes в blob-метаданных. До этого шага версии не тронуты.
|
||||
ensure_blob(&mut transaction, &new_source_request)
|
||||
.await
|
||||
.map_err(map_registry_error)?;
|
||||
|
||||
// Шаг 4: пометить прежнюю версию заменённой — строго до вставки новой,
|
||||
// иначе частичный unique-index отвергнет две текущие версии.
|
||||
let superseded = sqlx::query(
|
||||
"update resource_versions
|
||||
set superseded_at = $1
|
||||
where workspace_id = $2 and resource_id = $3 and superseded_at is null",
|
||||
)
|
||||
.bind(now)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(map_write_error)?
|
||||
.rows_affected();
|
||||
if superseded != 1 {
|
||||
return Err(ResourceError::ArtifactIntegrity);
|
||||
}
|
||||
|
||||
// Шаг 5: новая активная owning-ссылка (обычный insert, без `do nothing`).
|
||||
sqlx::query(
|
||||
"insert into artifact_sources (
|
||||
workspace_id, source_id, blob_digest, mime_type, sensitivity,
|
||||
lifecycle, created_at, updated_at, detached_at
|
||||
) values ($1, $2, $3, $4, $5, 'active', $6, $6, null)",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(new_source_id.as_str())
|
||||
.bind(request.artifact.artifact_ref().digest_hex())
|
||||
.bind(&request.mime_type)
|
||||
.bind(&request.sensitivity)
|
||||
.bind(now)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(map_write_error)?;
|
||||
|
||||
// Шаг 6: новая строка версии (FK на resources и artifact_sources проверяет БД).
|
||||
sqlx::query(
|
||||
"insert into resource_versions (
|
||||
workspace_id, resource_id, version, kind, mime_type, size_bytes, digest,
|
||||
sensitivity, artifact_source_id, created_at, superseded_at
|
||||
) select r.workspace_id, r.resource_id, $3, r.kind, $4, $5, $6, $7, $8, $9, null
|
||||
from resources r
|
||||
where r.workspace_id = $1 and r.resource_id = $2",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.bind(version_number(next_version)?)
|
||||
.bind(&request.mime_type)
|
||||
.bind(size_bytes(&request.artifact)?)
|
||||
.bind(request.artifact.artifact_ref().digest_hex())
|
||||
.bind(&request.sensitivity)
|
||||
.bind(new_source_id.as_str())
|
||||
.bind(now)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(map_write_error)?;
|
||||
|
||||
// Шаг 7: отсоединить прежнюю owning-ссылку с CAS по её `updated_at`.
|
||||
let detached = sqlx::query(
|
||||
"update artifact_sources
|
||||
set lifecycle = 'detached', updated_at = $1, detached_at = $1
|
||||
where workspace_id = $2 and source_id = $3
|
||||
and lifecycle = 'active' and updated_at = $4",
|
||||
)
|
||||
.bind(now)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(old_source_id.as_str())
|
||||
.bind(old_source_updated_at)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(map_write_error)?
|
||||
.rows_affected();
|
||||
if detached != 1 {
|
||||
return Err(ResourceError::ArtifactIntegrity);
|
||||
}
|
||||
|
||||
// Шаг 8: переключение указателя; uri/name/kind неизменяемы (D-16). Правка после
|
||||
// публикации возвращает карточку в Draft, published snapshot не затрагивается.
|
||||
let updated = sqlx::query(
|
||||
"update resources
|
||||
set current_draft_version = $3, updated_at = $4, description = $5, status = 'draft'
|
||||
where workspace_id = $1 and resource_id = $2",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.bind(version_number(next_version)?)
|
||||
.bind(now)
|
||||
.bind(&request.description)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(map_write_error)?
|
||||
.rows_affected();
|
||||
if updated != 1 {
|
||||
return Err(ResourceError::NotFound);
|
||||
}
|
||||
|
||||
let record = read_current_version(
|
||||
&mut transaction,
|
||||
&request.workspace_id,
|
||||
&request.resource_id,
|
||||
)
|
||||
.await?
|
||||
.ok_or(ResourceError::ArtifactIntegrity)?;
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
Ok(record)
|
||||
}
|
||||
|
||||
/// Публикация текущего Draft в immutable Published Version (V17).
|
||||
///
|
||||
/// В одной транзакции: row-lock Resource и CAS precondition → повторная сверка
|
||||
/// version/digest/size текущей версии → отдельная owning-ссылка публикации на тот же
|
||||
/// content-addressed blob → строка `resource_publications` со снимком публичных
|
||||
/// metadata → переключение статуса/ревизии карточки. Отказ не пишет ни строки и не
|
||||
/// сдвигает CAS.
|
||||
pub async fn publish_resource_version(
|
||||
&self,
|
||||
request: PublishResourceVersionRequest,
|
||||
) -> Result<ResourcePublicationRecord, ResourceError> {
|
||||
let mut transaction = self
|
||||
.pool()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
|
||||
let row = sqlx::query(
|
||||
"select uri, name, description, kind, current_draft_version, updated_at
|
||||
from resources
|
||||
where workspace_id = $1 and resource_id = $2
|
||||
for update",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||||
.ok_or(ResourceError::NotFound)?;
|
||||
|
||||
let recorded_updated_at: time::OffsetDateTime = row
|
||||
.try_get("updated_at")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
// Story 3.8: отзыв закрывает Resource целиком и не снимается редактированием.
|
||||
// Проверка идёт под уже взятым FOR UPDATE, поэтому гонка с revoke закрыта:
|
||||
// побеждает тот, кто первым получил строку.
|
||||
if revocation::is_revoked(
|
||||
&mut transaction,
|
||||
request.workspace_id.as_str(),
|
||||
request.resource_id.as_str(),
|
||||
)
|
||||
.await?
|
||||
{
|
||||
return Err(ResourceError::Revoked);
|
||||
}
|
||||
// F: точный precondition. Успешная публикация сдвигает ревизию, поэтому повтор
|
||||
// прежней карточки — stale, а не duplicate publication.
|
||||
if recorded_updated_at != request.expected_updated_at {
|
||||
return Err(ResourceError::Stale);
|
||||
}
|
||||
let current_draft_version = u32::try_from(
|
||||
row.try_get::<i32, _>("current_draft_version")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
)
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
|
||||
let version_row = sqlx::query(
|
||||
"select version, mime_type, size_bytes, digest, sensitivity
|
||||
from resource_versions
|
||||
where workspace_id = $1 and resource_id = $2 and superseded_at is null",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||||
.ok_or(ResourceError::ArtifactIntegrity)?;
|
||||
|
||||
let version = u32::try_from(
|
||||
version_row
|
||||
.try_get::<i32, _>("version")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
)
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
let digest: String = version_row
|
||||
.try_get("digest")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
let size_bytes: i64 = version_row
|
||||
.try_get("size_bytes")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
// TOCTOU: между физической проверкой bytes и этим коммитом Draft мог измениться.
|
||||
// Любое расхождение — stale, публикация не создаётся.
|
||||
if version != request.expected_version
|
||||
|| current_draft_version != version
|
||||
|| digest != request.expected_digest
|
||||
|| size_bytes != request.expected_size_bytes
|
||||
{
|
||||
return Err(ResourceError::Stale);
|
||||
}
|
||||
|
||||
let mime_type: String = version_row
|
||||
.try_get("mime_type")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
let sensitivity: String = version_row
|
||||
.try_get("sensitivity")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
let source_sensitivity = parse_sensitivity(&sensitivity)?;
|
||||
|
||||
// Уже опубликованная версия не публикуется повторно: клиент получил свежую
|
||||
// карточку, но Draft с тех пор не менялся. Это stale-состояние (reload), а не
|
||||
// duplicate row/500.
|
||||
let already_published = sqlx::query_scalar::<_, bool>(
|
||||
"select exists(
|
||||
select 1 from resource_publications
|
||||
where workspace_id = $1 and resource_id = $2 and version = $3
|
||||
)",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.bind(version_number(version)?)
|
||||
.fetch_one(&mut *transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
if already_published {
|
||||
return Err(ResourceError::Stale);
|
||||
}
|
||||
let now = truncate_to_micros(request.published_at);
|
||||
let next_updated_at = if now > recorded_updated_at {
|
||||
now
|
||||
} else {
|
||||
recorded_updated_at + time::Duration::microseconds(1)
|
||||
};
|
||||
let source_id = publication_source_id(&request.resource_id, version)?;
|
||||
let source_request = CreateArtifactSourceRequest {
|
||||
workspace_id: &request.workspace_id,
|
||||
source_id: &source_id,
|
||||
artifact: &request.artifact,
|
||||
mime_type: &mime_type,
|
||||
sensitivity: source_sensitivity,
|
||||
created_at: now,
|
||||
};
|
||||
ensure_blob(&mut transaction, &source_request)
|
||||
.await
|
||||
.map_err(map_registry_error)?;
|
||||
|
||||
// Отдельная owning-ссылка публикации: Draft update отсоединяет только свою
|
||||
// ссылку, поэтому published bytes/metadata остаются живыми независимо.
|
||||
sqlx::query(
|
||||
"insert into artifact_sources (
|
||||
workspace_id, source_id, blob_digest, mime_type, sensitivity,
|
||||
lifecycle, created_at, updated_at, detached_at
|
||||
) values ($1, $2, $3, $4, $5, 'active', $6, $6, null)",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(source_id.as_str())
|
||||
.bind(digest.as_str())
|
||||
.bind(&mime_type)
|
||||
.bind(&sensitivity)
|
||||
.bind(now)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(map_write_error)?;
|
||||
|
||||
sqlx::query(
|
||||
"insert into resource_publications (
|
||||
workspace_id, resource_id, version, uri, name, description, kind,
|
||||
mime_type, size_bytes, digest, sensitivity, artifact_source_id, published_at
|
||||
) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.bind(version_number(version)?)
|
||||
.bind(row.try_get::<String, _>("uri").map_err(integrity)?)
|
||||
.bind(row.try_get::<String, _>("name").map_err(integrity)?)
|
||||
.bind(row.try_get::<String, _>("description").map_err(integrity)?)
|
||||
.bind(row.try_get::<String, _>("kind").map_err(integrity)?)
|
||||
.bind(&mime_type)
|
||||
.bind(size_bytes)
|
||||
.bind(digest.as_str())
|
||||
.bind(&sensitivity)
|
||||
.bind(source_id.as_str())
|
||||
.bind(now)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(map_write_error)?;
|
||||
|
||||
let updated = sqlx::query(
|
||||
"update resources
|
||||
set status = 'published', updated_at = $3
|
||||
where workspace_id = $1 and resource_id = $2 and updated_at = $4",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.bind(next_updated_at)
|
||||
.bind(recorded_updated_at)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(map_write_error)?
|
||||
.rows_affected();
|
||||
if updated != 1 {
|
||||
return Err(ResourceError::Stale);
|
||||
}
|
||||
|
||||
let record = read_publication(
|
||||
&mut transaction,
|
||||
&request.workspace_id,
|
||||
&request.resource_id,
|
||||
version,
|
||||
)
|
||||
.await?
|
||||
.ok_or(ResourceError::ArtifactIntegrity)?;
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
Ok(record)
|
||||
}
|
||||
}
|
||||
|
||||
async fn read_draft(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
resource_id: &ResourceId,
|
||||
) -> Result<Option<ResourceDraftRecord>, ResourceError> {
|
||||
let row = sqlx::query(DRAFT_SELECT)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(resource_id.as_str())
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
row.as_ref().map(map_draft).transpose()
|
||||
}
|
||||
|
||||
async fn read_current_version(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
resource_id: &ResourceId,
|
||||
) -> Result<Option<ResourceVersionRecord>, ResourceError> {
|
||||
let row = sqlx::query(VERSION_SELECT)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(resource_id.as_str())
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
row.as_ref().map(map_version).transpose()
|
||||
}
|
||||
|
||||
async fn read_publication(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
resource_id: &ResourceId,
|
||||
version: u32,
|
||||
) -> Result<Option<ResourcePublicationRecord>, ResourceError> {
|
||||
let row = sqlx::query(PUBLICATION_SELECT)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(resource_id.as_str())
|
||||
.bind(version_number(version)?)
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
row.as_ref().map(map_publication).transpose()
|
||||
}
|
||||
|
||||
fn map_draft(row: &PgRow) -> Result<ResourceDraftRecord, ResourceError> {
|
||||
let resource = ResourceRecord {
|
||||
resource_id: ResourceId::new(row.try_get::<String, _>("resource_id").map_err(integrity)?),
|
||||
uri: row.try_get("uri").map_err(integrity)?,
|
||||
name: row.try_get("name").map_err(integrity)?,
|
||||
description: row.try_get("description").map_err(integrity)?,
|
||||
status: parse_status(&row.try_get::<String, _>("status").map_err(integrity)?)?,
|
||||
kind: row.try_get("kind").map_err(integrity)?,
|
||||
current_draft_version: u32::try_from(
|
||||
row.try_get::<i32, _>("current_draft_version")
|
||||
.map_err(integrity)?,
|
||||
)
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
latest_published_version: row
|
||||
.try_get::<Option<i32>, _>("latest_published_version")
|
||||
.map_err(integrity)?
|
||||
.map(u32::try_from)
|
||||
.transpose()
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
created_at: row.try_get("resource_created_at").map_err(integrity)?,
|
||||
updated_at: row.try_get("resource_updated_at").map_err(integrity)?,
|
||||
};
|
||||
let version = map_version(row)?;
|
||||
Ok(ResourceDraftRecord { resource, version })
|
||||
}
|
||||
|
||||
fn parse_status(value: &str) -> Result<ResourceStatus, ResourceError> {
|
||||
match value {
|
||||
"draft" => Ok(ResourceStatus::Draft),
|
||||
"published" => Ok(ResourceStatus::Published),
|
||||
"archived" => Ok(ResourceStatus::Archived),
|
||||
_ => Err(ResourceError::ArtifactIntegrity),
|
||||
}
|
||||
}
|
||||
|
||||
fn map_version(row: &PgRow) -> Result<ResourceVersionRecord, ResourceError> {
|
||||
Ok(ResourceVersionRecord {
|
||||
version: u32::try_from(row.try_get::<i32, _>("version").map_err(integrity)?)
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
kind: row.try_get("version_kind").map_err(integrity)?,
|
||||
mime_type: row.try_get("version_mime_type").map_err(integrity)?,
|
||||
size_bytes: row.try_get("version_size_bytes").map_err(integrity)?,
|
||||
digest: row.try_get("version_digest").map_err(integrity)?,
|
||||
sensitivity: row.try_get("version_sensitivity").map_err(integrity)?,
|
||||
source_kind: row.try_get("version_source_kind").map_err(integrity)?,
|
||||
created_at: row.try_get("version_created_at").map_err(integrity)?,
|
||||
superseded_at: row.try_get("superseded_at").map_err(integrity)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn map_publication(row: &PgRow) -> Result<ResourcePublicationRecord, ResourceError> {
|
||||
Ok(ResourcePublicationRecord {
|
||||
resource_id: ResourceId::new(row.try_get::<String, _>("resource_id").map_err(integrity)?),
|
||||
version: u32::try_from(row.try_get::<i32, _>("version").map_err(integrity)?)
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
uri: row.try_get("uri").map_err(integrity)?,
|
||||
name: row.try_get("name").map_err(integrity)?,
|
||||
description: row.try_get("description").map_err(integrity)?,
|
||||
kind: row.try_get("kind").map_err(integrity)?,
|
||||
mime_type: row.try_get("mime_type").map_err(integrity)?,
|
||||
size_bytes: row.try_get("size_bytes").map_err(integrity)?,
|
||||
digest: row.try_get("digest").map_err(integrity)?,
|
||||
sensitivity: row.try_get("sensitivity").map_err(integrity)?,
|
||||
source_kind: row.try_get("source_kind").map_err(integrity)?,
|
||||
published_at: row.try_get("published_at").map_err(integrity)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn integrity(_: sqlx::Error) -> ResourceError {
|
||||
ResourceError::ArtifactIntegrity
|
||||
}
|
||||
|
||||
fn parse_sensitivity(value: &str) -> Result<ArtifactSourceSensitivity, ResourceError> {
|
||||
match ResourceSensitivity::parse(value) {
|
||||
Some(ResourceSensitivity::Public) => Ok(ArtifactSourceSensitivity::Public),
|
||||
Some(ResourceSensitivity::Internal) => Ok(ArtifactSourceSensitivity::Internal),
|
||||
Some(ResourceSensitivity::Secret) => Ok(ArtifactSourceSensitivity::Secret),
|
||||
None => Err(ResourceError::StorageUnavailable),
|
||||
}
|
||||
}
|
||||
|
||||
fn size_bytes(artifact: &crank_artifacts::RegisteredArtifact) -> Result<i64, ResourceError> {
|
||||
i64::try_from(artifact.size_bytes()).map_err(|_| ResourceError::StorageUnavailable)
|
||||
}
|
||||
|
||||
/// Версия вне представимого БД диапазона не может существовать как Published
|
||||
/// Version: exact publication lookup отвечает sanitized NotFound, а не отказом
|
||||
/// хранилища (TL F4). Draft-разрешение сохраняет прежнюю taxonomy.
|
||||
fn published_version_number(version: u32) -> Result<i32, ResourceError> {
|
||||
i32::try_from(version).map_err(|_| ResourceError::NotFound)
|
||||
}
|
||||
|
||||
fn version_number(version: u32) -> Result<i32, ResourceError> {
|
||||
i32::try_from(version).map_err(|_| ResourceError::StorageUnavailable)
|
||||
}
|
||||
|
||||
/// Детерминированный owning ref версии: `src_<resource-tail>_v<version>`.
|
||||
fn version_source_id(
|
||||
resource_id: &ResourceId,
|
||||
version: u32,
|
||||
) -> Result<ArtifactSourceId, ResourceError> {
|
||||
let tail = resource_tail(resource_id)?;
|
||||
Ok(ArtifactSourceId::new(format!("src_{tail}_v{version}")))
|
||||
}
|
||||
|
||||
/// Owning ref публикации: отдельный от Draft-ссылки, поэтому Draft update не может
|
||||
/// отсоединить published bytes.
|
||||
fn publication_source_id(
|
||||
resource_id: &ResourceId,
|
||||
version: u32,
|
||||
) -> Result<ArtifactSourceId, ResourceError> {
|
||||
let tail = resource_tail(resource_id)?;
|
||||
Ok(ArtifactSourceId::new(format!("src_{tail}_v{version}_pub")))
|
||||
}
|
||||
|
||||
fn resource_tail(resource_id: &ResourceId) -> Result<String, ResourceError> {
|
||||
let tail = resource_id
|
||||
.as_str()
|
||||
.strip_prefix(RESOURCE_ID_PREFIX)
|
||||
.unwrap_or_else(|| resource_id.as_str());
|
||||
if tail.is_empty()
|
||||
|| tail.len() > MAX_SOURCE_TAIL_BYTES
|
||||
|| !tail
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
|
||||
{
|
||||
return Err(ResourceError::StorageUnavailable);
|
||||
}
|
||||
Ok(tail.to_owned())
|
||||
}
|
||||
|
||||
/// Микросекундная точность: Postgres `timestamptz` хранит микросекунды, поэтому
|
||||
/// optimistic-precondition не должен зависеть от наносекунд клиента.
|
||||
pub(crate) fn truncate_to_micros(value: time::OffsetDateTime) -> time::OffsetDateTime {
|
||||
let nanos = value.nanosecond();
|
||||
value
|
||||
.replace_nanosecond(nanos - nanos % 1_000)
|
||||
.unwrap_or(value)
|
||||
}
|
||||
|
||||
fn map_registry_error(error: RegistryError) -> ResourceError {
|
||||
match error {
|
||||
RegistryError::WorkspaceNotFound { .. } => ResourceError::NotFound,
|
||||
_ => ResourceError::StorageUnavailable,
|
||||
}
|
||||
}
|
||||
|
||||
/// Классификация отказа записи: конфликты uniqueness дают стабильные 409-коды,
|
||||
/// прочие FK/CHECK-отказы — 500 с фиксированным сообщением (D-20 шаг I).
|
||||
fn map_write_error(error: sqlx::Error) -> ResourceError {
|
||||
let Some(database) = error.as_database_error() else {
|
||||
return ResourceError::StorageUnavailable;
|
||||
};
|
||||
if database.code().as_deref() != Some("23505") {
|
||||
return ResourceError::StorageUnavailable;
|
||||
}
|
||||
match database.constraint() {
|
||||
Some("resources_workspace_uri_unique") => ResourceError::UriDuplicate,
|
||||
Some("resources_workspace_name_unique") => ResourceError::NameDuplicate,
|
||||
_ => ResourceError::StorageUnavailable,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
//! Архив Resource (Story 3.7 AC05): exact CAS и lifecycle-переход в одной транзакции.
|
||||
//!
|
||||
//! Вынесен из `postgres/resource.rs`, чтобы файл оставался в пределах
|
||||
//! rust-code-health; поведение и SQL не менялись. Меняются только
|
||||
//! `status`/`updated_at` строки `resources`: уже созданные publications, их owning
|
||||
//! refs и блобы не трогаются, поэтому точные Published Version остаются читаемыми
|
||||
//! и неизменными.
|
||||
|
||||
use crank_core::resource::{ResourceError, ResourceLifecycle, ResourceLifecycleAction};
|
||||
use sqlx::Row;
|
||||
|
||||
use crate::model::resource::{ArchiveResourceRequest, ResourceDraftRecord};
|
||||
|
||||
use super::super::PostgresRegistry;
|
||||
use super::{integrity, map_write_error, parse_status, read_draft, truncate_to_micros};
|
||||
|
||||
impl PostgresRegistry {
|
||||
/// Архив Resource: меняется только lifecycle/ревизия карточки.
|
||||
pub async fn archive_resource(
|
||||
&self,
|
||||
request: ArchiveResourceRequest,
|
||||
) -> Result<ResourceDraftRecord, ResourceError> {
|
||||
let mut transaction = self
|
||||
.pool()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
|
||||
let row = sqlx::query(
|
||||
"select status, updated_at
|
||||
from resources
|
||||
where workspace_id = $1 and resource_id = $2
|
||||
for update",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||||
.ok_or(ResourceError::NotFound)?;
|
||||
|
||||
let recorded_updated_at: time::OffsetDateTime = row
|
||||
.try_get("updated_at")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
// F: точный precondition. Старый CAS обязан победить lifecycle-отказ: повтор
|
||||
// архива прежней карточкой — stale (428), а не «уже архивирован».
|
||||
if recorded_updated_at != request.expected_updated_at {
|
||||
return Err(ResourceError::Stale);
|
||||
}
|
||||
let status = parse_status(&row.try_get::<String, _>("status").map_err(integrity)?)?;
|
||||
// Archived -> Archived недопустим: актуальный CAS на уже архивном Resource
|
||||
// даёт sanitized lifecycle-отказ (409), без 500 и без mutation.
|
||||
ResourceLifecycle::transition(status, ResourceLifecycleAction::Archive)?;
|
||||
|
||||
let archived_at = truncate_to_micros(request.archived_at);
|
||||
let next_updated_at = if archived_at > recorded_updated_at {
|
||||
archived_at
|
||||
} else {
|
||||
recorded_updated_at + time::Duration::microseconds(1)
|
||||
};
|
||||
let updated = sqlx::query(
|
||||
"update resources
|
||||
set status = 'archived', updated_at = $3
|
||||
where workspace_id = $1 and resource_id = $2 and updated_at = $4",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.bind(next_updated_at)
|
||||
.bind(recorded_updated_at)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(map_write_error)?
|
||||
.rows_affected();
|
||||
if updated != 1 {
|
||||
return Err(ResourceError::Stale);
|
||||
}
|
||||
|
||||
let record = read_draft(
|
||||
&mut transaction,
|
||||
&request.workspace_id,
|
||||
&request.resource_id,
|
||||
)
|
||||
.await?
|
||||
.ok_or(ResourceError::ArtifactIntegrity)?;
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
Ok(record)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
//! Сверка строки `PUBLICATION_SELECT` (вынесено из `postgres/resource.rs` под
|
||||
//! лимит rust-code-health).
|
||||
//!
|
||||
//! Сырой Admin-resolver и живой MCP-gate используют одну и ту же metadata/integrity
|
||||
//! проверку; gate добавляет отдельную tombstone-проверку, а не заменяет её.
|
||||
|
||||
use crank_artifacts::ArtifactRef;
|
||||
use crank_core::resource::ResourceError;
|
||||
use sqlx::Row;
|
||||
use sqlx::postgres::PgRow;
|
||||
|
||||
use crate::model::resource::{ResolvedResourcePublication, ResourcePublicationRecord};
|
||||
|
||||
use super::{integrity, map_publication};
|
||||
|
||||
/// Metadata/integrity-сверка строки `PUBLICATION_SELECT`.
|
||||
pub(super) fn validated_publication(
|
||||
row: &PgRow,
|
||||
) -> Result<ResourcePublicationRecord, ResourceError> {
|
||||
let blob_digest: String = row.try_get("blob_digest").map_err(integrity)?;
|
||||
let source_mime_type: String = row.try_get("source_mime_type").map_err(integrity)?;
|
||||
let source_sensitivity: String = row.try_get("source_sensitivity").map_err(integrity)?;
|
||||
let source_lifecycle: String = row.try_get("source_lifecycle").map_err(integrity)?;
|
||||
let blob_size_bytes: i64 = row.try_get("blob_size_bytes").map_err(integrity)?;
|
||||
let blob_lifecycle: String = row.try_get("blob_lifecycle").map_err(integrity)?;
|
||||
|
||||
let publication = map_publication(row)?;
|
||||
if blob_digest != publication.digest
|
||||
|| source_mime_type != publication.mime_type
|
||||
|| source_sensitivity != publication.sensitivity
|
||||
|| source_lifecycle != "active"
|
||||
|| blob_lifecycle != "available"
|
||||
|| blob_size_bytes != publication.size_bytes
|
||||
{
|
||||
return Err(ResourceError::ArtifactIntegrity);
|
||||
}
|
||||
Ok(publication)
|
||||
}
|
||||
|
||||
/// Полная разрешённая публикация из строки `PUBLICATION_SELECT` (metadata + ref).
|
||||
pub(super) fn resolved_publication(
|
||||
row: &PgRow,
|
||||
) -> Result<ResolvedResourcePublication, ResourceError> {
|
||||
let publication = validated_publication(row)?;
|
||||
let artifact_ref = ArtifactRef::parse(
|
||||
&row.try_get::<String, _>("artifact_ref")
|
||||
.map_err(integrity)?,
|
||||
)
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
if artifact_ref.digest_hex() != publication.digest {
|
||||
return Err(ResourceError::ArtifactIntegrity);
|
||||
}
|
||||
Ok(ResolvedResourcePublication {
|
||||
publication,
|
||||
artifact_ref,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
use super::*;
|
||||
|
||||
impl PostgresRegistry {
|
||||
/// Отозван ли Resource (Story 3.8). Точная проверка живой eligibility без чтения
|
||||
/// metadata или bytes: используется рендером Prompt, чтобы pinned-версия не отдавалась
|
||||
/// после отзыва (Story 3.16, AC6/AC8).
|
||||
pub async fn resource_is_revoked(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
resource_id: &ResourceId,
|
||||
) -> Result<bool, ResourceError> {
|
||||
sqlx::query_scalar::<_, bool>(
|
||||
"select exists (
|
||||
select 1 from resource_security_revocations
|
||||
where workspace_id = $1 and resource_id = $2
|
||||
)",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(resource_id.as_str())
|
||||
.fetch_one(self.pool())
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)
|
||||
}
|
||||
|
||||
/// Точная Published Version с полной сверкой owning-ссылки и blob metadata.
|
||||
pub async fn resolve_resource_publication(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
resource_id: &ResourceId,
|
||||
version: u32,
|
||||
) -> Result<ResolvedResourcePublication, ResourceError> {
|
||||
let row = sqlx::query(PUBLICATION_SELECT)
|
||||
.bind(workspace_id)
|
||||
.bind(resource_id.as_str())
|
||||
.bind(published_version_number(version)?)
|
||||
.fetch_optional(self.pool())
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||||
.ok_or(ResourceError::NotFound)?;
|
||||
|
||||
let publication = resolved_publication(&row)?;
|
||||
Ok(publication)
|
||||
}
|
||||
|
||||
/// Workspace-local разрешение explicit `include:` цели: только уже опубликованная
|
||||
/// metadata этого workspace. Глобального поиска и раскрытия чужих сущностей нет.
|
||||
pub async fn published_resource_sensitivity_by_uri(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
uri: &str,
|
||||
) -> Result<Option<String>, ResourceError> {
|
||||
let sensitivity = sqlx::query(
|
||||
"select p.sensitivity
|
||||
from resource_publications p
|
||||
where p.workspace_id = $1 and p.uri = $2
|
||||
order by p.published_at desc, p.version desc
|
||||
limit 1",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(uri)
|
||||
.fetch_optional(self.pool())
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||||
.map(|row| row.try_get::<String, _>("sensitivity"))
|
||||
.transpose()
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
Ok(sensitivity)
|
||||
}
|
||||
|
||||
/// Карточка Draft: строка Resource и её текущая версия.
|
||||
pub async fn get_resource_draft(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
resource_id: &ResourceId,
|
||||
) -> Result<ResourceDraftRecord, ResourceError> {
|
||||
let row = sqlx::query(DRAFT_SELECT)
|
||||
.bind(workspace_id)
|
||||
.bind(resource_id.as_str())
|
||||
.fetch_optional(self.pool())
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||||
.ok_or(ResourceError::NotFound)?;
|
||||
map_draft(&row)
|
||||
}
|
||||
|
||||
/// Ограниченная страница Draft-ов workspace.
|
||||
pub async fn list_resource_drafts(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
limit: u32,
|
||||
) -> Result<Vec<ResourceDraftRecord>, ResourceError> {
|
||||
let limit = limit.clamp(1, MAX_RESOURCE_DRAFT_PAGE_SIZE);
|
||||
let rows = sqlx::query(DRAFT_LIST_SELECT)
|
||||
.bind(workspace_id)
|
||||
.bind(i64::from(limit))
|
||||
.fetch_all(self.pool())
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
rows.iter().map(map_draft).collect()
|
||||
}
|
||||
|
||||
/// Workspace-scoped разрешение конкретной версии с полной metadata-сверкой.
|
||||
pub async fn resolve_resource_version(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
resource_id: &ResourceId,
|
||||
version: u32,
|
||||
) -> Result<ResolvedResourceVersion, ResourceError> {
|
||||
self.resolve_version(workspace_id, resource_id, Some(version))
|
||||
.await
|
||||
}
|
||||
|
||||
/// Workspace-scoped разрешение текущей черновой версии.
|
||||
pub async fn resolve_current_resource_version(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
resource_id: &ResourceId,
|
||||
) -> Result<ResolvedResourceVersion, ResourceError> {
|
||||
self.resolve_version(workspace_id, resource_id, None).await
|
||||
}
|
||||
|
||||
async fn resolve_version(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
resource_id: &ResourceId,
|
||||
version: Option<u32>,
|
||||
) -> Result<ResolvedResourceVersion, ResourceError> {
|
||||
let row = sqlx::query(RESOLVE_SELECT)
|
||||
.bind(workspace_id)
|
||||
.bind(resource_id.as_str())
|
||||
.bind(version.map(version_number).transpose()?)
|
||||
.fetch_optional(self.pool())
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||||
.ok_or(ResourceError::NotFound)?;
|
||||
|
||||
let blob_digest: String = row.try_get("blob_digest").map_err(integrity)?;
|
||||
let source_mime_type: String = row.try_get("source_mime_type").map_err(integrity)?;
|
||||
let source_sensitivity: String = row.try_get("source_sensitivity").map_err(integrity)?;
|
||||
let source_lifecycle: String = row.try_get("source_lifecycle").map_err(integrity)?;
|
||||
let artifact_ref_text: String = row.try_get("artifact_ref").map_err(integrity)?;
|
||||
let blob_size_bytes: i64 = row.try_get("blob_size_bytes").map_err(integrity)?;
|
||||
let blob_lifecycle: String = row.try_get("blob_lifecycle").map_err(integrity)?;
|
||||
|
||||
// Снимок строк `resources`/`resource_versions` того же запроса: metadata
|
||||
// ответа и bytes берутся из него, а не из второго чтения (P3).
|
||||
let snapshot = map_draft(&row)?;
|
||||
let digest = snapshot.version.digest.clone();
|
||||
let mime_type = snapshot.version.mime_type.clone();
|
||||
let sensitivity = snapshot.version.sensitivity.clone();
|
||||
let size_bytes = snapshot.version.size_bytes;
|
||||
|
||||
if blob_digest != digest
|
||||
|| source_mime_type != mime_type
|
||||
|| source_sensitivity != sensitivity
|
||||
|| source_lifecycle != "active"
|
||||
|| blob_lifecycle != "available"
|
||||
|| blob_size_bytes != size_bytes
|
||||
{
|
||||
return Err(ResourceError::ArtifactIntegrity);
|
||||
}
|
||||
let artifact_ref =
|
||||
ArtifactRef::parse(&artifact_ref_text).map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
if artifact_ref.digest_hex() != digest {
|
||||
return Err(ResourceError::ArtifactIntegrity);
|
||||
}
|
||||
|
||||
Ok(ResolvedResourceVersion {
|
||||
snapshot,
|
||||
artifact_ref,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,505 @@
|
||||
//! Resource security revocation (Story 3.8, owner decision A).
|
||||
//!
|
||||
//! Один tombstone на (workspace, Resource) — одновременно авторитетное состояние
|
||||
//! доступа и неизменяемая запись перехода. Отзыв закрывает все версии Resource во
|
||||
//! всех Agents, включая уже опубликованные snapshots; архив, immutable bytes и
|
||||
//! защищённое административное чтение сохраняются.
|
||||
//!
|
||||
//! Живая проверка доступа к MCP — только PostgreSQL, без cache/Valkey. Порядок
|
||||
//! блокировок: строка `resources` (якорь, FOR SHARE у чтения / FOR UPDATE у
|
||||
//! отзыва), затем свежий tombstone-lookup. `FOR SHARE` конфликтует с `FOR
|
||||
//! UPDATE`, поэтому revoke-first закрывает чтение до artifact bytes, а read-first
|
||||
//! линеаризует чтение до отзыва. Уже отправленные клиенту байты не отзываются.
|
||||
|
||||
use crank_core::ids::ResourceId;
|
||||
use crank_core::resource::ResourceError;
|
||||
use sqlx::postgres::PgRow;
|
||||
use sqlx::{Postgres, Row, Transaction};
|
||||
|
||||
use crate::AgentResourceBinding;
|
||||
use crate::model::resource::{
|
||||
BoundResourceTemplate, ResolvedResourcePublication, ResourcePublicationRecord,
|
||||
ResourceTemplateSourceRecord, RevokeResourceRequest,
|
||||
};
|
||||
|
||||
use super::super::PostgresRegistry;
|
||||
use super::publication::resolved_publication;
|
||||
use super::{PUBLICATION_SELECT, published_version_number};
|
||||
|
||||
/// Строка `resource_publications` шаблонной версии вместе с её определением: у шаблона нет
|
||||
/// owning artifact-ссылки, поэтому artifact-join из `PUBLICATION_SELECT` его не находит.
|
||||
const ADMITTED_TEMPLATE_SELECT: &str = "select p.resource_id, p.version, p.uri, p.name, p.description, p.kind, p.mime_type, p.size_bytes, p.digest, p.sensitivity, p.source_kind, p.published_at, s.definition_json, s.definition_digest from resource_publications p left join resource_template_sources s using(workspace_id, resource_id, version) where p.workspace_id=$1 and p.resource_id=$2 and p.version=$3 and p.source_kind='template'";
|
||||
|
||||
/// Transaction guard held while a template dispatch uses its shared Resource identity.
|
||||
pub struct AuthorizedResourceTemplateRead {
|
||||
transaction: Option<Transaction<'static, Postgres>>,
|
||||
}
|
||||
|
||||
impl AuthorizedResourceTemplateRead {
|
||||
pub async fn commit(mut self) -> Result<(), ResourceError> {
|
||||
self.transaction
|
||||
.take()
|
||||
.ok_or(ResourceError::StorageUnavailable)?
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)
|
||||
}
|
||||
}
|
||||
|
||||
pub enum BoundResourceAdmission {
|
||||
/// Boxed: the resolved publication is much larger than the empty denial variant.
|
||||
Admitted(Box<ResolvedResourcePublication>),
|
||||
/// Valid published Resource template: it has no artifact/blob to resolve for a physical read,
|
||||
/// and its concrete URIs are the expanded ones discovered through `resources/templates/list`.
|
||||
Template,
|
||||
Revoked,
|
||||
}
|
||||
|
||||
/// Разрешённое чтение, удерживающее `FOR SHARE` на строке Resource до успешного
|
||||
/// commit. Пока guard жив, конкурентный отзыв ждёт; после отзыва новые проверки
|
||||
/// доступа запрещают чтение, а `Drop` без commit откатывает блокировку.
|
||||
pub struct AuthorizedResourceRead {
|
||||
publication: ResolvedResourcePublication,
|
||||
transaction: Option<Transaction<'static, Postgres>>,
|
||||
}
|
||||
|
||||
impl AuthorizedResourceRead {
|
||||
pub fn publication(&self) -> &ResolvedResourcePublication {
|
||||
&self.publication
|
||||
}
|
||||
|
||||
/// Успешное завершение удерживаемой транзакции. Ошибка commit — отказ чтения,
|
||||
/// а не выдача подготовленного content.
|
||||
pub async fn commit(mut self) -> Result<(), ResourceError> {
|
||||
let Some(transaction) = self.transaction.take() else {
|
||||
return Err(ResourceError::StorageUnavailable);
|
||||
};
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)
|
||||
}
|
||||
}
|
||||
|
||||
impl PostgresRegistry {
|
||||
/// Resolve and admit exact template metadata while holding every Resource lock for the page.
|
||||
pub async fn list_admitted_resource_templates(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
bindings: &[AgentResourceBinding],
|
||||
) -> Result<Vec<BoundResourceTemplate>, ResourceError> {
|
||||
if bindings.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let mut ids: Vec<String> = bindings
|
||||
.iter()
|
||||
.map(|b| b.resource_id.as_str().to_owned())
|
||||
.collect();
|
||||
ids.sort();
|
||||
ids.dedup();
|
||||
let mut tx = self
|
||||
.pool()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
let locked = sqlx::query("select resource_id from resources where workspace_id=$1 and resource_id=any($2::text[]) order by resource_id asc for share")
|
||||
.bind(workspace_id).bind(&ids).fetch_all(&mut *tx).await.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
if locked.len() != ids.len() {
|
||||
return Err(ResourceError::NotFound);
|
||||
}
|
||||
let revoked = revoked_resource_ids(&mut tx, workspace_id, &ids).await?;
|
||||
let mut admitted = Vec::new();
|
||||
for binding in bindings {
|
||||
if revoked.iter().any(|id| id == binding.resource_id.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let row = sqlx::query(ADMITTED_TEMPLATE_SELECT)
|
||||
.bind(workspace_id)
|
||||
.bind(binding.resource_id.as_str())
|
||||
.bind(published_version_number(binding.resource_version)?)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
let Some(row) = row else { continue };
|
||||
admitted.push(bound_template_from_row(&row)?);
|
||||
}
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
Ok(admitted)
|
||||
}
|
||||
|
||||
/// Hold Resource identity stable and reject a revoked Resource while the admin
|
||||
/// test-read uses it, matching the same lock order as live template reads.
|
||||
pub async fn begin_authorized_resource_test_read(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
resource_id: &ResourceId,
|
||||
version: u32,
|
||||
digest: &str,
|
||||
) -> Result<AuthorizedResourceTemplateRead, ResourceError> {
|
||||
let version = super::published_version_number(version)?;
|
||||
let mut transaction = self
|
||||
.pool()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
lock_resource_shared(&mut transaction, workspace_id, resource_id.as_str()).await?;
|
||||
if is_revoked(&mut transaction, workspace_id, resource_id.as_str()).await? {
|
||||
return Err(ResourceError::Revoked);
|
||||
}
|
||||
let row = sqlx::query("select r.status, r.current_draft_version, v.digest from resources r join resource_versions v on v.workspace_id=r.workspace_id and v.resource_id=r.resource_id and v.version=r.current_draft_version where r.workspace_id=$1 and r.resource_id=$2")
|
||||
.bind(workspace_id).bind(resource_id.as_str()).fetch_optional(&mut *transaction).await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?.ok_or(ResourceError::NotFound)?;
|
||||
let status: String = row
|
||||
.try_get("status")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
let current_version: i32 = row
|
||||
.try_get("current_draft_version")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
let current_digest: String = row
|
||||
.try_get("digest")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
if status == "archived" {
|
||||
return Err(ResourceError::InvalidLifecycleTransition {
|
||||
from: crank_core::resource::ResourceStatus::Archived,
|
||||
to: crank_core::resource::ResourceStatus::Draft,
|
||||
});
|
||||
}
|
||||
if current_version != version || current_digest != digest {
|
||||
return Err(ResourceError::Stale);
|
||||
}
|
||||
Ok(AuthorizedResourceTemplateRead {
|
||||
transaction: Some(transaction),
|
||||
})
|
||||
}
|
||||
|
||||
/// Keep the live Resource revocation lock until a dynamic template read completes.
|
||||
pub async fn begin_authorized_resource_template_read(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
resource_id: &ResourceId,
|
||||
version: u32,
|
||||
) -> Result<AuthorizedResourceTemplateRead, ResourceError> {
|
||||
let version = published_version_number(version)?;
|
||||
let mut transaction = self
|
||||
.pool()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
lock_resource_shared(&mut transaction, workspace_id, resource_id.as_str()).await?;
|
||||
if is_revoked(&mut transaction, workspace_id, resource_id.as_str()).await? {
|
||||
return Err(ResourceError::Revoked);
|
||||
}
|
||||
let exists: bool = sqlx::query_scalar("select exists(select 1 from resource_template_sources s join resource_publications p using(workspace_id,resource_id,version) where s.workspace_id=$1 and s.resource_id=$2 and s.version=$3 and p.source_kind='template')")
|
||||
.bind(workspace_id).bind(resource_id.as_str()).bind(version)
|
||||
.fetch_one(&mut *transaction).await.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
if !exists {
|
||||
return Err(ResourceError::NotFound);
|
||||
}
|
||||
Ok(AuthorizedResourceTemplateRead {
|
||||
transaction: Some(transaction),
|
||||
})
|
||||
}
|
||||
|
||||
/// Необратимый audited отзыв Resource.
|
||||
///
|
||||
/// READ COMMITTED: `resources FOR UPDATE` → отдельный свежий tombstone-lookup →
|
||||
/// INSERT первого события → COMMIT. Повтор и две конкурентные команды дают одну
|
||||
/// строку с actor/time первого успеха; ошибка INSERT/commit не даёт ложный 204.
|
||||
pub async fn revoke_resource(
|
||||
&self,
|
||||
request: RevokeResourceRequest,
|
||||
) -> Result<(), ResourceError> {
|
||||
let mut transaction = self
|
||||
.pool()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
|
||||
let locked = sqlx::query(
|
||||
"select 1 from resources
|
||||
where workspace_id = $1 and resource_id = $2
|
||||
for update",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
if locked.is_none() {
|
||||
return Err(ResourceError::NotFound);
|
||||
}
|
||||
|
||||
// Отдельный statement после блокировки: видит только закоммиченный отзыв,
|
||||
// поэтому конкурент, ждавший на FOR UPDATE, не пишет второе событие.
|
||||
if !is_revoked(
|
||||
&mut transaction,
|
||||
request.workspace_id.as_str(),
|
||||
request.resource_id.as_str(),
|
||||
)
|
||||
.await?
|
||||
{
|
||||
sqlx::query(
|
||||
"insert into resource_security_revocations (
|
||||
workspace_id, resource_id, revoked_at, actor_user_id, request_id, trace_id
|
||||
) values ($1, $2, $3, $4, $5, $6)",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.bind(request.revoked_at)
|
||||
.bind(request.actor_user_id.as_str())
|
||||
.bind(request.request_id.as_str())
|
||||
.bind(request.trace_id.as_str())
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
}
|
||||
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)
|
||||
}
|
||||
|
||||
/// Живой MCP-gate чтения: `FOR SHARE` на Resource, свежий tombstone-check,
|
||||
/// затем metadata/integrity. `Revoked` возвращается до любого artifact byte.
|
||||
pub async fn begin_authorized_resource_read(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
resource_id: &ResourceId,
|
||||
version: u32,
|
||||
) -> Result<AuthorizedResourceRead, ResourceError> {
|
||||
let version = published_version_number(version)?;
|
||||
let mut transaction = self
|
||||
.pool()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
lock_resource_shared(&mut transaction, workspace_id, resource_id.as_str()).await?;
|
||||
if is_revoked(&mut transaction, workspace_id, resource_id.as_str()).await? {
|
||||
return Err(ResourceError::Revoked);
|
||||
}
|
||||
let row = sqlx::query(PUBLICATION_SELECT)
|
||||
.bind(workspace_id)
|
||||
.bind(resource_id.as_str())
|
||||
.bind(version)
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||||
.ok_or(ResourceError::NotFound)?;
|
||||
let publication = resolved_publication(&row)?;
|
||||
Ok(AuthorizedResourceRead {
|
||||
publication,
|
||||
transaction: Some(transaction),
|
||||
})
|
||||
}
|
||||
|
||||
/// Живой MCP-gate страницы списка: shared-блокировки всех Resource диапазона в
|
||||
/// порядке `resource_id ASC`, затем свежие tombstones. Revoked пропускается;
|
||||
/// corruption/отсутствие publication — ошибка страницы, не partial success.
|
||||
pub async fn list_admitted_resource_publications(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
bindings: &[AgentResourceBinding],
|
||||
) -> Result<Vec<BoundResourceAdmission>, ResourceError> {
|
||||
if bindings.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let mut resource_ids: Vec<String> = bindings
|
||||
.iter()
|
||||
.map(|binding| binding.resource_id.as_str().to_owned())
|
||||
.collect();
|
||||
resource_ids.sort();
|
||||
resource_ids.dedup();
|
||||
|
||||
let mut transaction = self
|
||||
.pool()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
let locked = sqlx::query(
|
||||
"select resource_id from resources
|
||||
where workspace_id = $1 and resource_id = any($2::text[])
|
||||
order by resource_id asc
|
||||
for share",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(&resource_ids)
|
||||
.fetch_all(&mut *transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
if locked.len() != resource_ids.len() {
|
||||
return Err(ResourceError::NotFound);
|
||||
}
|
||||
let revoked = revoked_resource_ids(&mut transaction, workspace_id, &resource_ids).await?;
|
||||
|
||||
let mut admissions = Vec::with_capacity(bindings.len());
|
||||
for binding in bindings {
|
||||
if revoked.iter().any(|id| id == binding.resource_id.as_str()) {
|
||||
admissions.push(BoundResourceAdmission::Revoked);
|
||||
continue;
|
||||
}
|
||||
let version = published_version_number(binding.resource_version)?;
|
||||
// A published Resource template has no owning artifact, so the artifact join of
|
||||
// `PUBLICATION_SELECT` can never match it: resolve its own metadata instead of
|
||||
// turning a valid binding into an internal error for the whole page.
|
||||
let template_row = sqlx::query(ADMITTED_TEMPLATE_SELECT)
|
||||
.bind(workspace_id)
|
||||
.bind(binding.resource_id.as_str())
|
||||
.bind(version)
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
if let Some(row) = template_row {
|
||||
// Integrity contract kept: publication digest must equal the definition digest.
|
||||
bound_template_from_row(&row)?;
|
||||
admissions.push(BoundResourceAdmission::Template);
|
||||
continue;
|
||||
}
|
||||
let row = sqlx::query(PUBLICATION_SELECT)
|
||||
.bind(workspace_id)
|
||||
.bind(binding.resource_id.as_str())
|
||||
.bind(version)
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||||
.ok_or(ResourceError::NotFound)?;
|
||||
admissions.push(BoundResourceAdmission::Admitted(Box::new(
|
||||
resolved_publication(&row)?,
|
||||
)));
|
||||
}
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
Ok(admissions)
|
||||
}
|
||||
}
|
||||
|
||||
/// Точная шаблонная публикация из строки `ADMITTED_TEMPLATE_SELECT`: metadata плюс определение.
|
||||
/// Digest определения обязан совпадать с digest публикации, иначе это integrity-отказ, а не
|
||||
/// «нет шаблона».
|
||||
fn bound_template_from_row(row: &PgRow) -> Result<BoundResourceTemplate, ResourceError> {
|
||||
let version = u32::try_from(
|
||||
row.try_get::<i32, _>("version")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
)
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
let publication = ResourcePublicationRecord {
|
||||
resource_id: ResourceId::new(
|
||||
row.try_get::<String, _>("resource_id")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
),
|
||||
version,
|
||||
uri: row
|
||||
.try_get("uri")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
name: row
|
||||
.try_get("name")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
description: row
|
||||
.try_get("description")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
kind: row
|
||||
.try_get("kind")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
mime_type: row
|
||||
.try_get("mime_type")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
size_bytes: row
|
||||
.try_get("size_bytes")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
digest: row
|
||||
.try_get("digest")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
sensitivity: row
|
||||
.try_get("sensitivity")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
source_kind: row
|
||||
.try_get("source_kind")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
published_at: row
|
||||
.try_get("published_at")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
};
|
||||
let source = ResourceTemplateSourceRecord {
|
||||
definition_json: row
|
||||
.try_get("definition_json")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
definition_digest: row
|
||||
.try_get("definition_digest")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?,
|
||||
};
|
||||
if source.definition_digest != publication.digest {
|
||||
return Err(ResourceError::ArtifactIntegrity);
|
||||
}
|
||||
Ok(BoundResourceTemplate {
|
||||
publication,
|
||||
source,
|
||||
})
|
||||
}
|
||||
|
||||
/// Есть ли закоммиченный отзыв этого Resource в текущей транзакции.
|
||||
pub(super) async fn is_revoked(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &str,
|
||||
resource_id: &str,
|
||||
) -> Result<bool, ResourceError> {
|
||||
sqlx::query_scalar::<_, bool>(
|
||||
"select exists (
|
||||
select 1 from resource_security_revocations
|
||||
where workspace_id = $1 and resource_id = $2
|
||||
)",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(resource_id)
|
||||
.fetch_one(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)
|
||||
}
|
||||
|
||||
/// Shared-блокировка якорной строки Resource; отсутствующая/чужая строка — NotFound.
|
||||
async fn lock_resource_shared(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &str,
|
||||
resource_id: &str,
|
||||
) -> Result<(), ResourceError> {
|
||||
let locked = sqlx::query(
|
||||
"select 1 from resources
|
||||
where workspace_id = $1 and resource_id = $2
|
||||
for share",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(resource_id)
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
if locked.is_none() {
|
||||
return Err(ResourceError::NotFound);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Id отозванных Resource из заданного набора (одна свежая проверка на страницу).
|
||||
async fn revoked_resource_ids(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &str,
|
||||
resource_ids: &[String],
|
||||
) -> Result<Vec<String>, ResourceError> {
|
||||
let rows = sqlx::query(
|
||||
"select resource_id from resource_security_revocations
|
||||
where workspace_id = $1 and resource_id = any($2::text[])",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(resource_ids)
|
||||
.fetch_all(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
rows.iter()
|
||||
.map(|row| {
|
||||
row.try_get::<String, _>("resource_id")
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,576 @@
|
||||
//! Persistence Story 3.10 (FR-16): byte-less REST-backed Resource templates (V20).
|
||||
//!
|
||||
//! Определение шаблона хранится version-keyed строкой `resource_template_sources`;
|
||||
//! версия помечена `source_kind='template'`, не имеет owning artifact-ссылки и
|
||||
//! несёт `size_bytes = 0`, а `digest` — детерминированный digest определения.
|
||||
//! Прежние artifact-строки сохраняют собственные CHECK/FK без изменений.
|
||||
//!
|
||||
//! Все мутации — одна транзакция: строка `resources` блокируется первой, затем
|
||||
//! optimistic precondition, затем версия/определение. Publication snapshot
|
||||
//! неизменяем, потому что определение insert-only (UPDATE запрещён trigger-ом).
|
||||
|
||||
use crank_core::ids::ResourceId;
|
||||
use crank_core::resource::ResourceError;
|
||||
use sqlx::{Postgres, Row, Transaction};
|
||||
|
||||
use crate::model::resource::{
|
||||
CreateResourceTemplateDraftRequest, PublishResourceTemplateVersionRequest,
|
||||
ResourcePublicationRecord, ResourceTemplateDraftRecord, ResourceTemplateSourceRecord,
|
||||
UpdateResourceTemplateDraftRequest,
|
||||
};
|
||||
|
||||
use super::super::PostgresRegistry;
|
||||
use super::super::artifact_source::require_workspace;
|
||||
use super::{
|
||||
DRAFT_SELECT, integrity, map_registry_error, map_write_error, read_draft, revocation,
|
||||
truncate_to_micros, version_number,
|
||||
};
|
||||
|
||||
const TEMPLATE_SOURCE_SELECT: &str = "select definition_json, definition_digest
|
||||
from resource_template_sources
|
||||
where workspace_id = $1 and resource_id = $2 and version = $3";
|
||||
|
||||
const TEMPLATE_PUBLICATION_SELECT: &str = "select
|
||||
p.resource_id, p.version, p.uri, p.name, p.description, p.kind,
|
||||
p.mime_type, p.size_bytes, p.digest, p.sensitivity, p.source_kind, p.published_at
|
||||
from resource_publications p
|
||||
where p.workspace_id = $1 and p.resource_id = $2 and p.version = $3
|
||||
and p.source_kind = 'template'";
|
||||
|
||||
impl PostgresRegistry {
|
||||
/// Создание template Draft без байтов: ресурс, версия 1 и определение в одной транзакции.
|
||||
pub async fn create_resource_template_draft(
|
||||
&self,
|
||||
request: CreateResourceTemplateDraftRequest,
|
||||
) -> Result<ResourceTemplateDraftRecord, ResourceError> {
|
||||
let mut transaction = self
|
||||
.pool()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
require_workspace(&mut transaction, &request.workspace_id)
|
||||
.await
|
||||
.map_err(map_registry_error)?;
|
||||
|
||||
sqlx::query(
|
||||
"insert into resources (
|
||||
workspace_id, resource_id, uri, name, description, status, kind,
|
||||
current_draft_version, created_at, updated_at
|
||||
) values ($1, $2, $3, $4, $5, 'draft', $6, 1, $7, $7)",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.bind(&request.uri)
|
||||
.bind(&request.name)
|
||||
.bind(&request.description)
|
||||
.bind(&request.kind)
|
||||
.bind(request.created_at)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(map_write_error)?;
|
||||
|
||||
// Template-версия: artifact_source_id null и size 0 допускаются только
|
||||
// CHECK-ом для source_kind='template'.
|
||||
sqlx::query(
|
||||
"insert into resource_versions (
|
||||
workspace_id, resource_id, version, kind, mime_type, size_bytes, digest,
|
||||
sensitivity, artifact_source_id, source_kind, created_at, superseded_at
|
||||
) values ($1, $2, 1, $3, $4, 0, $5, $6, null, 'template', $7, null)",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.bind(&request.kind)
|
||||
.bind(&request.mime_type)
|
||||
.bind(&request.definition_digest)
|
||||
.bind(&request.sensitivity)
|
||||
.bind(request.created_at)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(map_write_error)?;
|
||||
|
||||
insert_definition(
|
||||
&mut transaction,
|
||||
&request.workspace_id,
|
||||
&request.resource_id,
|
||||
1,
|
||||
&request.definition_json,
|
||||
&request.definition_digest,
|
||||
request.created_at,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let record = read_template(
|
||||
&mut transaction,
|
||||
&request.workspace_id,
|
||||
&request.resource_id,
|
||||
)
|
||||
.await?
|
||||
.ok_or(ResourceError::ArtifactIntegrity)?;
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
Ok(record)
|
||||
}
|
||||
|
||||
/// Новая версия template Draft: прежняя версия остаётся (superseded) вместе со
|
||||
/// своим определением, поэтому уже опубликованный snapshot не меняется.
|
||||
pub async fn update_resource_template_draft(
|
||||
&self,
|
||||
request: UpdateResourceTemplateDraftRequest,
|
||||
) -> Result<ResourceTemplateDraftRecord, ResourceError> {
|
||||
let mut transaction = self
|
||||
.pool()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
|
||||
let row = sqlx::query(
|
||||
"select current_draft_version, updated_at
|
||||
from resources
|
||||
where workspace_id = $1 and resource_id = $2
|
||||
for update",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||||
.ok_or(ResourceError::NotFound)?;
|
||||
let current_version: i32 = row.try_get("current_draft_version").map_err(integrity)?;
|
||||
let recorded_updated_at: time::OffsetDateTime =
|
||||
row.try_get("updated_at").map_err(integrity)?;
|
||||
if recorded_updated_at != request.expected_updated_at {
|
||||
return Err(ResourceError::Stale);
|
||||
}
|
||||
let current_version =
|
||||
u32::try_from(current_version).map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
|
||||
let source_kind: String = sqlx::query(
|
||||
"select source_kind
|
||||
from resource_versions
|
||||
where workspace_id = $1 and resource_id = $2 and superseded_at is null",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||||
.ok_or(ResourceError::ArtifactIntegrity)?
|
||||
.try_get("source_kind")
|
||||
.map_err(integrity)?;
|
||||
if source_kind != "template" {
|
||||
return Err(ResourceError::ArtifactIntegrity);
|
||||
}
|
||||
|
||||
let now = truncate_to_micros(time::OffsetDateTime::now_utc());
|
||||
let next_version = current_version
|
||||
.checked_add(1)
|
||||
.ok_or(ResourceError::StorageUnavailable)?;
|
||||
|
||||
let superseded = sqlx::query(
|
||||
"update resource_versions
|
||||
set superseded_at = $1
|
||||
where workspace_id = $2 and resource_id = $3 and superseded_at is null",
|
||||
)
|
||||
.bind(now)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(map_write_error)?
|
||||
.rows_affected();
|
||||
if superseded != 1 {
|
||||
return Err(ResourceError::ArtifactIntegrity);
|
||||
}
|
||||
|
||||
sqlx::query(
|
||||
"insert into resource_versions (
|
||||
workspace_id, resource_id, version, kind, mime_type, size_bytes, digest,
|
||||
sensitivity, artifact_source_id, source_kind, created_at, superseded_at
|
||||
) select r.workspace_id, r.resource_id, $3, r.kind, $4, 0, $5, $6, null,
|
||||
'template', $7, null
|
||||
from resources r
|
||||
where r.workspace_id = $1 and r.resource_id = $2",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.bind(version_number(next_version)?)
|
||||
.bind(&request.mime_type)
|
||||
.bind(&request.definition_digest)
|
||||
.bind(&request.sensitivity)
|
||||
.bind(now)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(map_write_error)?;
|
||||
|
||||
insert_definition(
|
||||
&mut transaction,
|
||||
&request.workspace_id,
|
||||
&request.resource_id,
|
||||
next_version,
|
||||
&request.definition_json,
|
||||
&request.definition_digest,
|
||||
now,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let updated = sqlx::query(
|
||||
"update resources
|
||||
set current_draft_version = $3, updated_at = $4, description = $5, status = 'draft'
|
||||
where workspace_id = $1 and resource_id = $2",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.bind(version_number(next_version)?)
|
||||
.bind(now)
|
||||
.bind(&request.description)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(map_write_error)?
|
||||
.rows_affected();
|
||||
if updated != 1 {
|
||||
return Err(ResourceError::NotFound);
|
||||
}
|
||||
|
||||
let record = read_template(
|
||||
&mut transaction,
|
||||
&request.workspace_id,
|
||||
&request.resource_id,
|
||||
)
|
||||
.await?
|
||||
.ok_or(ResourceError::ArtifactIntegrity)?;
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
Ok(record)
|
||||
}
|
||||
|
||||
/// Публикация template Draft: publication-снимок ссылается на ту же
|
||||
/// version-keyed definition-строку (artifact-ссылки нет).
|
||||
pub async fn publish_resource_template_version(
|
||||
&self,
|
||||
request: PublishResourceTemplateVersionRequest,
|
||||
) -> Result<(ResourcePublicationRecord, ResourceTemplateSourceRecord), ResourceError> {
|
||||
let mut transaction = self
|
||||
.pool()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
|
||||
let row = sqlx::query(
|
||||
"select uri, name, description, kind, current_draft_version, updated_at
|
||||
from resources
|
||||
where workspace_id = $1 and resource_id = $2
|
||||
for update",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||||
.ok_or(ResourceError::NotFound)?;
|
||||
let recorded_updated_at: time::OffsetDateTime =
|
||||
row.try_get("updated_at").map_err(integrity)?;
|
||||
if revocation::is_revoked(
|
||||
&mut transaction,
|
||||
request.workspace_id.as_str(),
|
||||
request.resource_id.as_str(),
|
||||
)
|
||||
.await?
|
||||
{
|
||||
return Err(ResourceError::Revoked);
|
||||
}
|
||||
if recorded_updated_at != request.expected_updated_at {
|
||||
return Err(ResourceError::Stale);
|
||||
}
|
||||
let current_draft_version = u32::try_from(
|
||||
row.try_get::<i32, _>("current_draft_version")
|
||||
.map_err(integrity)?,
|
||||
)
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
|
||||
let version_row = sqlx::query(
|
||||
"select version, mime_type, size_bytes, digest, sensitivity, source_kind
|
||||
from resource_versions
|
||||
where workspace_id = $1 and resource_id = $2 and superseded_at is null",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||||
.ok_or(ResourceError::ArtifactIntegrity)?;
|
||||
let version = u32::try_from(
|
||||
version_row
|
||||
.try_get::<i32, _>("version")
|
||||
.map_err(integrity)?,
|
||||
)
|
||||
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
||||
let digest: String = version_row.try_get("digest").map_err(integrity)?;
|
||||
let size_bytes: i64 = version_row.try_get("size_bytes").map_err(integrity)?;
|
||||
let mime_type: String = version_row.try_get("mime_type").map_err(integrity)?;
|
||||
let sensitivity: String = version_row.try_get("sensitivity").map_err(integrity)?;
|
||||
let source_kind: String = version_row.try_get("source_kind").map_err(integrity)?;
|
||||
// TOCTOU: Draft мог измениться между проверкой и коммитом — stale, не дубль.
|
||||
if source_kind != "template"
|
||||
|| size_bytes != 0
|
||||
|| version != request.expected_version
|
||||
|| current_draft_version != version
|
||||
|| digest != request.expected_digest
|
||||
{
|
||||
return Err(ResourceError::Stale);
|
||||
}
|
||||
|
||||
let already_published = sqlx::query_scalar::<_, bool>(
|
||||
"select exists(
|
||||
select 1 from resource_publications
|
||||
where workspace_id = $1 and resource_id = $2 and version = $3
|
||||
)",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.bind(version_number(version)?)
|
||||
.fetch_one(&mut *transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
if already_published {
|
||||
return Err(ResourceError::Stale);
|
||||
}
|
||||
|
||||
let now = truncate_to_micros(request.published_at);
|
||||
let next_updated_at = if now > recorded_updated_at {
|
||||
now
|
||||
} else {
|
||||
recorded_updated_at + time::Duration::microseconds(1)
|
||||
};
|
||||
sqlx::query(
|
||||
"insert into resource_publications (
|
||||
workspace_id, resource_id, version, uri, name, description, kind,
|
||||
mime_type, size_bytes, digest, sensitivity, artifact_source_id, source_kind,
|
||||
published_at
|
||||
) values ($1, $2, $3, $4, $5, $6, $7, $8, 0, $9, $10, null, 'template', $11)",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.bind(version_number(version)?)
|
||||
.bind(row.try_get::<String, _>("uri").map_err(integrity)?)
|
||||
.bind(row.try_get::<String, _>("name").map_err(integrity)?)
|
||||
.bind(row.try_get::<String, _>("description").map_err(integrity)?)
|
||||
.bind(row.try_get::<String, _>("kind").map_err(integrity)?)
|
||||
.bind(&mime_type)
|
||||
.bind(&digest)
|
||||
.bind(&sensitivity)
|
||||
.bind(now)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(map_write_error)?;
|
||||
|
||||
let updated = sqlx::query(
|
||||
"update resources
|
||||
set status = 'published', updated_at = $3
|
||||
where workspace_id = $1 and resource_id = $2 and updated_at = $4",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.resource_id.as_str())
|
||||
.bind(next_updated_at)
|
||||
.bind(recorded_updated_at)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(map_write_error)?
|
||||
.rows_affected();
|
||||
if updated != 1 {
|
||||
return Err(ResourceError::Stale);
|
||||
}
|
||||
|
||||
let publication = read_template_publication(
|
||||
&mut transaction,
|
||||
&request.workspace_id,
|
||||
&request.resource_id,
|
||||
version,
|
||||
)
|
||||
.await?
|
||||
.ok_or(ResourceError::ArtifactIntegrity)?;
|
||||
let source = read_definition(
|
||||
&mut transaction,
|
||||
&request.workspace_id,
|
||||
&request.resource_id,
|
||||
version,
|
||||
)
|
||||
.await?
|
||||
.ok_or(ResourceError::ArtifactIntegrity)?;
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
Ok((publication, source))
|
||||
}
|
||||
|
||||
/// Текущий template Draft вместе с определением. `NotFound` для static Resource.
|
||||
pub async fn get_resource_template_draft(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
resource_id: &ResourceId,
|
||||
) -> Result<ResourceTemplateDraftRecord, ResourceError> {
|
||||
let row = sqlx::query(DRAFT_SELECT)
|
||||
.bind(workspace_id)
|
||||
.bind(resource_id.as_str())
|
||||
.fetch_optional(self.pool())
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||||
.ok_or(ResourceError::NotFound)?;
|
||||
let source_kind: String = row.try_get("version_source_kind").map_err(integrity)?;
|
||||
if source_kind != "template" {
|
||||
return Err(ResourceError::NotFound);
|
||||
}
|
||||
let snapshot = super::map_draft(&row)?;
|
||||
let source =
|
||||
read_definition_on_pool(self, workspace_id, resource_id, snapshot.version.version)
|
||||
.await?
|
||||
.ok_or(ResourceError::ArtifactIntegrity)?;
|
||||
Ok(ResourceTemplateDraftRecord { snapshot, source })
|
||||
}
|
||||
|
||||
/// Определение точной версии (draft или published — строка та же).
|
||||
pub async fn get_resource_template_source(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
resource_id: &ResourceId,
|
||||
version: u32,
|
||||
) -> Result<ResourceTemplateSourceRecord, ResourceError> {
|
||||
let row = sqlx::query(TEMPLATE_SOURCE_SELECT)
|
||||
.bind(workspace_id)
|
||||
.bind(resource_id.as_str())
|
||||
.bind(version_number(version)?)
|
||||
.fetch_optional(self.pool())
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||||
.ok_or(ResourceError::NotFound)?;
|
||||
map_definition(&row)
|
||||
}
|
||||
|
||||
/// Точная Published Version шаблона вместе с его определения снимком.
|
||||
pub async fn resolve_resource_template_publication(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
resource_id: &ResourceId,
|
||||
version: u32,
|
||||
) -> Result<(ResourcePublicationRecord, ResourceTemplateSourceRecord), ResourceError> {
|
||||
let row = sqlx::query(TEMPLATE_PUBLICATION_SELECT)
|
||||
.bind(workspace_id)
|
||||
.bind(resource_id.as_str())
|
||||
// Exact published version вне i32-диапазона — sanitized NotFound, не storage.
|
||||
.bind(super::published_version_number(version)?)
|
||||
.fetch_optional(self.pool())
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?
|
||||
.ok_or(ResourceError::NotFound)?;
|
||||
let publication = super::map_publication(&row)?;
|
||||
let source = self
|
||||
.get_resource_template_source(workspace_id, resource_id, version)
|
||||
.await?;
|
||||
if source.definition_digest != publication.digest {
|
||||
return Err(ResourceError::ArtifactIntegrity);
|
||||
}
|
||||
Ok((publication, source))
|
||||
}
|
||||
}
|
||||
|
||||
async fn insert_definition(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
resource_id: &ResourceId,
|
||||
version: u32,
|
||||
definition_json: &str,
|
||||
definition_digest: &str,
|
||||
created_at: time::OffsetDateTime,
|
||||
) -> Result<(), ResourceError> {
|
||||
sqlx::query(
|
||||
"insert into resource_template_sources (
|
||||
workspace_id, resource_id, version, definition_json, definition_digest, created_at
|
||||
) values ($1, $2, $3, $4, $5, $6)",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(resource_id.as_str())
|
||||
.bind(version_number(version)?)
|
||||
.bind(definition_json)
|
||||
.bind(definition_digest)
|
||||
.bind(created_at)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(map_write_error)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn read_definition(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
resource_id: &ResourceId,
|
||||
version: u32,
|
||||
) -> Result<Option<ResourceTemplateSourceRecord>, ResourceError> {
|
||||
let row = sqlx::query(TEMPLATE_SOURCE_SELECT)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(resource_id.as_str())
|
||||
.bind(version_number(version)?)
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
row.as_ref().map(map_definition).transpose()
|
||||
}
|
||||
|
||||
async fn read_definition_on_pool(
|
||||
registry: &PostgresRegistry,
|
||||
workspace_id: &str,
|
||||
resource_id: &ResourceId,
|
||||
version: u32,
|
||||
) -> Result<Option<ResourceTemplateSourceRecord>, ResourceError> {
|
||||
let row = sqlx::query(TEMPLATE_SOURCE_SELECT)
|
||||
.bind(workspace_id)
|
||||
.bind(resource_id.as_str())
|
||||
.bind(version_number(version)?)
|
||||
.fetch_optional(registry.pool())
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
row.as_ref().map(map_definition).transpose()
|
||||
}
|
||||
|
||||
async fn read_template(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
resource_id: &ResourceId,
|
||||
) -> Result<Option<ResourceTemplateDraftRecord>, ResourceError> {
|
||||
let Some(snapshot) = read_draft(transaction, workspace_id, resource_id).await? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let version = snapshot.version.version;
|
||||
let source = read_definition(transaction, workspace_id, resource_id, version)
|
||||
.await?
|
||||
.ok_or(ResourceError::ArtifactIntegrity)?;
|
||||
Ok(Some(ResourceTemplateDraftRecord { snapshot, source }))
|
||||
}
|
||||
|
||||
async fn read_template_publication(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &crank_core::WorkspaceId,
|
||||
resource_id: &ResourceId,
|
||||
version: u32,
|
||||
) -> Result<Option<ResourcePublicationRecord>, ResourceError> {
|
||||
let row = sqlx::query(TEMPLATE_PUBLICATION_SELECT)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(resource_id.as_str())
|
||||
.bind(version_number(version)?)
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| ResourceError::StorageUnavailable)?;
|
||||
row.as_ref().map(super::map_publication).transpose()
|
||||
}
|
||||
|
||||
fn map_definition(
|
||||
row: &sqlx::postgres::PgRow,
|
||||
) -> Result<ResourceTemplateSourceRecord, ResourceError> {
|
||||
Ok(ResourceTemplateSourceRecord {
|
||||
definition_json: row.try_get("definition_json").map_err(integrity)?,
|
||||
definition_digest: row.try_get("definition_digest").map_err(integrity)?,
|
||||
})
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
mod integration {
|
||||
mod agent_resource_bindings;
|
||||
mod agents_usage;
|
||||
mod approval;
|
||||
mod artifact_reconciliation;
|
||||
@@ -11,5 +12,9 @@ mod integration {
|
||||
mod observability;
|
||||
mod onboarding;
|
||||
mod operations_artifacts;
|
||||
mod prompt_composition;
|
||||
mod prompt_drafts;
|
||||
mod prompt_publication;
|
||||
mod resource_drafts;
|
||||
mod workspace_access;
|
||||
}
|
||||
@@ -0,0 +1,916 @@
|
||||
//! Story 3.7 / AC04 regression: typed exact Resource bindings Agent (V18).
|
||||
//!
|
||||
//! Проверяется на реальном PostgreSQL, что integrity держится **схемой**, а не только
|
||||
//! JSON-ответом API:
|
||||
//! - workspace-равенство на обоих концах composite FK (Agent и Resource publication);
|
||||
//! - published Agent Version bindings иммутабельны (V9 guard function);
|
||||
//! - закреплённая exact v1 не меняется после публикации Resource v2;
|
||||
//! - failed save/publish откатываются без partial rows/pointer/revision;
|
||||
//! - published catalog reader отдаёт resources из того же снимка, что
|
||||
//! agent_version/catalog_revision/tools.
|
||||
|
||||
use std::{
|
||||
fs,
|
||||
os::unix::fs::PermissionsExt,
|
||||
path::PathBuf,
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
};
|
||||
|
||||
use super::common::*;
|
||||
|
||||
mod archive_race;
|
||||
mod revocation_race;
|
||||
mod revocation_write_race;
|
||||
mod rollback;
|
||||
|
||||
use crank_artifacts::{ArtifactStore, RegisteredArtifact};
|
||||
use crank_core::ids::ResourceId;
|
||||
use crank_core::{Agent, AgentStatus, AgentVersion, Workspace, WorkspaceId, WorkspaceStatus};
|
||||
use crank_registry::model::resource::{
|
||||
CreateResourceDraftRequest, PublishResourceVersionRequest, UpdateResourceDraftRequest,
|
||||
};
|
||||
use crank_registry::{
|
||||
AgentResourceBinding, CreateAgentRequest, CreateWorkspaceRequest, PostgresRegistry,
|
||||
PublishAgentRequest, SaveAgentCatalogConfigRequest,
|
||||
};
|
||||
use serde_json::json;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct TestRoot(PathBuf);
|
||||
|
||||
impl TestRoot {
|
||||
fn new(name: &str) -> Self {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"crank-registry-agent-resource-bindings-{name}-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT_ROOT.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
fs::create_dir(&path).expect("private artifact root must be creatable");
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o700))
|
||||
.expect("private artifact root must be 0700");
|
||||
Self(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestRoot {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::set_permissions(&self.0, fs::Permissions::from_mode(0o700));
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
struct Sandbox {
|
||||
registry: PostgresRegistry,
|
||||
pool: sqlx::PgPool,
|
||||
store: ArtifactStore,
|
||||
_root: TestRoot,
|
||||
database: TestDatabase,
|
||||
}
|
||||
|
||||
async fn sandbox(name: &str) -> Sandbox {
|
||||
let database = TestDatabase::new().await;
|
||||
let registry = database.registry().await;
|
||||
let pool = database.raw_pool().await;
|
||||
let root = TestRoot::new(name);
|
||||
let store = ArtifactStore::open(root.0.clone()).expect("private artifact store must open");
|
||||
Sandbox {
|
||||
registry,
|
||||
pool,
|
||||
store,
|
||||
_root: root,
|
||||
database,
|
||||
}
|
||||
}
|
||||
|
||||
impl Sandbox {
|
||||
async fn cleanup(&self) {
|
||||
self.database.cleanup().await;
|
||||
}
|
||||
}
|
||||
|
||||
fn registered(sandbox: &Sandbox, bytes: &[u8]) -> RegisteredArtifact {
|
||||
sandbox
|
||||
.store
|
||||
.put_registered(bytes)
|
||||
.expect("fixture bytes must be registered durably")
|
||||
}
|
||||
|
||||
async fn seed_workspace(sandbox: &Sandbox, workspace_id: &str, slug: &str) {
|
||||
let now = OffsetDateTime::now_utc();
|
||||
sandbox
|
||||
.registry
|
||||
.create_workspace(CreateWorkspaceRequest {
|
||||
workspace: &Workspace {
|
||||
id: WorkspaceId::new(workspace_id),
|
||||
slug: slug.to_owned(),
|
||||
display_name: slug.to_owned(),
|
||||
status: WorkspaceStatus::Active,
|
||||
settings: json!({}),
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("synthetic workspace must be created");
|
||||
}
|
||||
|
||||
/// Draft → Published Resource v1 через принятый Story 3.6/3.7 registry-контракт.
|
||||
async fn published_resource(
|
||||
sandbox: &Sandbox,
|
||||
workspace_id: &str,
|
||||
resource_id: &str,
|
||||
uri: &str,
|
||||
bytes: &[u8],
|
||||
) -> ResourceId {
|
||||
let id = ResourceId::new(resource_id);
|
||||
sandbox
|
||||
.registry
|
||||
.create_resource_draft(CreateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new(workspace_id),
|
||||
resource_id: id.clone(),
|
||||
uri: uri.to_owned(),
|
||||
name: "binding_doc".to_owned(),
|
||||
description: String::new(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
artifact: registered(sandbox, bytes),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("resource draft must be created");
|
||||
publish_current_resource(sandbox, workspace_id, &id, bytes).await;
|
||||
id
|
||||
}
|
||||
|
||||
async fn publish_current_resource(
|
||||
sandbox: &Sandbox,
|
||||
workspace_id: &str,
|
||||
resource_id: &ResourceId,
|
||||
bytes: &[u8],
|
||||
) -> u32 {
|
||||
let current = sandbox
|
||||
.registry
|
||||
.get_resource_draft(workspace_id, resource_id)
|
||||
.await
|
||||
.expect("draft must be readable");
|
||||
let publication = sandbox
|
||||
.registry
|
||||
.publish_resource_version(PublishResourceVersionRequest {
|
||||
workspace_id: WorkspaceId::new(workspace_id),
|
||||
resource_id: resource_id.clone(),
|
||||
expected_updated_at: current.resource.updated_at,
|
||||
expected_version: current.version.version,
|
||||
expected_digest: current.version.digest.clone(),
|
||||
expected_size_bytes: current.version.size_bytes,
|
||||
artifact: registered(sandbox, bytes),
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("valid current draft must publish");
|
||||
publication.version
|
||||
}
|
||||
|
||||
async fn draft_next_resource_version(
|
||||
sandbox: &Sandbox,
|
||||
workspace_id: &str,
|
||||
resource_id: &ResourceId,
|
||||
bytes: &[u8],
|
||||
) {
|
||||
let current = sandbox
|
||||
.registry
|
||||
.get_resource_draft(workspace_id, resource_id)
|
||||
.await
|
||||
.expect("draft must be readable");
|
||||
sandbox
|
||||
.registry
|
||||
.update_resource_draft(UpdateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new(workspace_id),
|
||||
resource_id: resource_id.clone(),
|
||||
description: "edited after publication".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
expected_updated_at: current.resource.updated_at,
|
||||
artifact: registered(sandbox, bytes),
|
||||
})
|
||||
.await
|
||||
.expect("draft edit after publication must succeed");
|
||||
}
|
||||
|
||||
async fn create_draft_agent(
|
||||
sandbox: &Sandbox,
|
||||
workspace_id: &str,
|
||||
agent_id: &str,
|
||||
slug: &str,
|
||||
) -> crank_core::AgentId {
|
||||
let id = crank_core::AgentId::new(agent_id);
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let agent = Agent {
|
||||
id: id.clone(),
|
||||
workspace_id: WorkspaceId::new(workspace_id),
|
||||
slug: slug.to_owned(),
|
||||
display_name: slug.to_owned(),
|
||||
description: "Story 3.7 typed binding fixture".to_owned(),
|
||||
status: AgentStatus::Draft,
|
||||
current_draft_version: 1,
|
||||
latest_published_version: None,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
published_at: None,
|
||||
};
|
||||
let version = AgentVersion {
|
||||
agent_id: id.clone(),
|
||||
version: 1,
|
||||
status: AgentStatus::Draft,
|
||||
instructions: json!({}),
|
||||
tool_selection_policy: Default::default(),
|
||||
created_at: now,
|
||||
};
|
||||
sandbox
|
||||
.registry
|
||||
.create_agent(CreateAgentRequest {
|
||||
agent: &agent,
|
||||
version: &version,
|
||||
bindings: &[],
|
||||
})
|
||||
.await
|
||||
.expect("draft Agent must be created");
|
||||
id
|
||||
}
|
||||
|
||||
async fn save_resource_bindings(
|
||||
sandbox: &Sandbox,
|
||||
workspace_id: &str,
|
||||
agent_id: &crank_core::AgentId,
|
||||
bindings: &[AgentResourceBinding],
|
||||
) -> Result<(), crank_registry::RegistryError> {
|
||||
sandbox
|
||||
.registry
|
||||
.save_agent_catalog_config(SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &WorkspaceId::new(workspace_id),
|
||||
agent_id,
|
||||
agent_version: 1,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &Default::default(),
|
||||
resource_bindings: bindings,
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
async fn binding_rows(sandbox: &Sandbox, agent_id: &str) -> i64 {
|
||||
sqlx::query_scalar("select count(*) from agent_resource_bindings where agent_id = $1")
|
||||
.bind(agent_id)
|
||||
.fetch_one(&sandbox.pool)
|
||||
.await
|
||||
.expect("binding rows must be queryable")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story37_v18_typed_fk_enforces_workspace_on_both_ends() {
|
||||
let sandbox = sandbox("v18_fk_scope").await;
|
||||
seed_workspace(&sandbox, "ws_other", "other").await;
|
||||
let own = published_resource(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"res_v18_default",
|
||||
"crank://v18/default",
|
||||
b"default v1",
|
||||
)
|
||||
.await;
|
||||
let foreign = published_resource(
|
||||
&sandbox,
|
||||
"ws_other",
|
||||
"res_v18_foreign",
|
||||
"crank://v18/foreign",
|
||||
b"foreign v1",
|
||||
)
|
||||
.await;
|
||||
let agent = create_draft_agent(&sandbox, "ws_default", "agent_v18_fk", "v18-fk").await;
|
||||
let other_agent =
|
||||
create_draft_agent(&sandbox, "ws_other", "agent_v18_other", "v18-other").await;
|
||||
let foreign_binding = AgentResourceBinding {
|
||||
resource_id: foreign.clone(),
|
||||
resource_version: 1,
|
||||
};
|
||||
|
||||
// Чужой Agent в binding.workspace_id отвергается composite FK на Agent-конце.
|
||||
let agent_scope = sqlx::query(
|
||||
"insert into agent_resource_bindings
|
||||
(workspace_id, agent_id, agent_version, resource_id, resource_version)
|
||||
values ('ws_default', $1, 1, $2, 1)",
|
||||
)
|
||||
.bind(other_agent.as_str())
|
||||
.bind(own.as_str())
|
||||
.execute(&sandbox.pool)
|
||||
.await
|
||||
.expect_err("a foreign-workspace Agent must be rejected by the Agent-side FK");
|
||||
assert_eq!(
|
||||
database_error_code(&agent_scope),
|
||||
"23503",
|
||||
"Agent workspace mismatch must be a foreign-key violation: {agent_scope}"
|
||||
);
|
||||
|
||||
// Чужая Resource publication отвергается composite FK на Resource-конце.
|
||||
let resource_scope = sqlx::query(
|
||||
"insert into agent_resource_bindings
|
||||
(workspace_id, agent_id, agent_version, resource_id, resource_version)
|
||||
values ('ws_default', $1, 1, $2, 1)",
|
||||
)
|
||||
.bind(agent.as_str())
|
||||
.bind(foreign_binding.resource_id.as_str())
|
||||
.execute(&sandbox.pool)
|
||||
.await
|
||||
.expect_err("a foreign-workspace Resource publication must be rejected");
|
||||
assert_eq!(
|
||||
database_error_code(&resource_scope),
|
||||
"23503",
|
||||
"Resource workspace mismatch must be a foreign-key violation: {resource_scope}"
|
||||
);
|
||||
|
||||
// Positive control: та же вставка в своём workspace проходит и видна читателю.
|
||||
save_resource_bindings(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
&agent,
|
||||
&[AgentResourceBinding {
|
||||
resource_id: own.clone(),
|
||||
resource_version: 1,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.expect("a same-workspace exact binding must be accepted");
|
||||
let record = sandbox
|
||||
.registry
|
||||
.get_agent_version(&WorkspaceId::new("ws_default"), &agent, 1)
|
||||
.await
|
||||
.expect("agent version must be readable")
|
||||
.expect("agent version must exist");
|
||||
assert_eq!(
|
||||
record.resource_bindings,
|
||||
vec![AgentResourceBinding {
|
||||
resource_id: own,
|
||||
resource_version: 1
|
||||
}]
|
||||
);
|
||||
assert_eq!(binding_rows(&sandbox, agent.as_str()).await, 1);
|
||||
sandbox.cleanup().await;
|
||||
}
|
||||
|
||||
fn database_error_code(error: &sqlx::Error) -> String {
|
||||
match error {
|
||||
sqlx::Error::Database(database) => database.code().unwrap_or_default().to_string(),
|
||||
other => panic!("expected a database error, got {other}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story37_v18_published_agent_resource_bindings_are_immutable() {
|
||||
let sandbox = sandbox("v18_immutable").await;
|
||||
let resource = published_resource(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"res_v18_immutable",
|
||||
"crank://v18/immutable",
|
||||
b"immutable v1",
|
||||
)
|
||||
.await;
|
||||
let agent = create_draft_agent(&sandbox, "ws_default", "agent_v18_immutable", "v18-imm").await;
|
||||
save_resource_bindings(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
&agent,
|
||||
&[AgentResourceBinding {
|
||||
resource_id: resource.clone(),
|
||||
resource_version: 1,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.expect("draft binding must be saved");
|
||||
sandbox
|
||||
.registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &WorkspaceId::new("ws_default"),
|
||||
agent_id: &agent,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: None,
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("resource-only Agent must publish at registry level");
|
||||
|
||||
let update = sqlx::query(
|
||||
"update agent_resource_bindings set resource_version = 2
|
||||
where agent_id = $1 and agent_version = 1",
|
||||
)
|
||||
.bind(agent.as_str())
|
||||
.execute(&sandbox.pool)
|
||||
.await
|
||||
.expect_err("a published Agent binding must not be updated");
|
||||
assert_eq!(
|
||||
database_error_code(&update),
|
||||
"23514",
|
||||
"immutability guard must raise a check violation: {update}"
|
||||
);
|
||||
let delete = sqlx::query("delete from agent_resource_bindings where agent_id = $1")
|
||||
.bind(agent.as_str())
|
||||
.execute(&sandbox.pool)
|
||||
.await
|
||||
.expect_err("a published Agent binding must not be deleted");
|
||||
assert_eq!(
|
||||
database_error_code(&delete),
|
||||
"23514",
|
||||
"immutability guard must reject deletes: {delete}"
|
||||
);
|
||||
assert_eq!(
|
||||
binding_rows(&sandbox, agent.as_str()).await,
|
||||
1,
|
||||
"refused mutations must keep the published snapshot"
|
||||
);
|
||||
sandbox.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story37_v18_published_binding_cannot_move_to_a_draft_agent_or_version() {
|
||||
let sandbox = sandbox("v18_immutable_move").await;
|
||||
let resource = published_resource(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"res_v18_move",
|
||||
"crank://v18/move",
|
||||
b"move v1",
|
||||
)
|
||||
.await;
|
||||
let published_agent =
|
||||
create_draft_agent(&sandbox, "ws_default", "agent_v18_move_pub", "v18-move-pub").await;
|
||||
let draft_agent = create_draft_agent(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"agent_v18_move_draft",
|
||||
"v18-move-draft",
|
||||
)
|
||||
.await;
|
||||
save_resource_bindings(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
&published_agent,
|
||||
&[AgentResourceBinding {
|
||||
resource_id: resource.clone(),
|
||||
resource_version: 1,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.expect("draft binding must be saved");
|
||||
sandbox
|
||||
.registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &WorkspaceId::new("ws_default"),
|
||||
agent_id: &published_agent,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: None,
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("resource-only Agent must publish");
|
||||
|
||||
// Перенос Published snapshot -> Draft Agent другого id: оба composite FK остаются
|
||||
// валидными (тот же workspace), поэтому отказать обязан immutable guard по OLD-ключу.
|
||||
let to_draft_agent = sqlx::query(
|
||||
"update agent_resource_bindings set agent_id = $1
|
||||
where agent_id = $2 and agent_version = 1",
|
||||
)
|
||||
.bind(draft_agent.as_str())
|
||||
.bind(published_agent.as_str())
|
||||
.execute(&sandbox.pool)
|
||||
.await
|
||||
.expect_err("moving a published binding to a Draft Agent must be rejected");
|
||||
assert_eq!(
|
||||
database_error_code(&to_draft_agent),
|
||||
"23514",
|
||||
"V18 guard must reject relocation away from the published source: {to_draft_agent}"
|
||||
);
|
||||
|
||||
// Draft-версия того же Agent создаётся штатным editable fork (v2 без bindings).
|
||||
let forked = sandbox
|
||||
.registry
|
||||
.save_agent_catalog_config_editable(SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &WorkspaceId::new("ws_default"),
|
||||
agent_id: &published_agent,
|
||||
agent_version: 1,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &Default::default(),
|
||||
resource_bindings: &[],
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("editing a published Agent must fork a Draft version");
|
||||
assert_eq!(forked, 2, "editable fork must create Agent version 2");
|
||||
let to_draft_version = sqlx::query(
|
||||
"update agent_resource_bindings set agent_version = $1
|
||||
where agent_id = $2 and agent_version = 1",
|
||||
)
|
||||
.bind(i32::try_from(forked).expect("forked version must fit the DB integer domain"))
|
||||
.bind(published_agent.as_str())
|
||||
.execute(&sandbox.pool)
|
||||
.await
|
||||
.expect_err("moving a published binding to a Draft version must be rejected");
|
||||
assert_eq!(
|
||||
database_error_code(&to_draft_version),
|
||||
"23514",
|
||||
"V18 guard must reject relocation to a Draft version: {to_draft_version}"
|
||||
);
|
||||
|
||||
draft_next_resource_version(&sandbox, "ws_default", &resource, b"move v2").await;
|
||||
assert_eq!(
|
||||
publish_current_resource(&sandbox, "ws_default", &resource, b"move v2").await,
|
||||
2
|
||||
);
|
||||
// NEW-конец тоже защищён: нельзя добавить binding в уже опубликованный snapshot.
|
||||
let insert_into_published = sqlx::query(
|
||||
"insert into agent_resource_bindings
|
||||
(workspace_id, agent_id, agent_version, resource_id, resource_version)
|
||||
values ('ws_default', $1, 1, $2, 2)",
|
||||
)
|
||||
.bind(published_agent.as_str())
|
||||
.bind(resource.as_str())
|
||||
.execute(&sandbox.pool)
|
||||
.await
|
||||
.expect_err("inserting a binding into a published Agent version must be rejected");
|
||||
assert_eq!(
|
||||
database_error_code(&insert_into_published),
|
||||
"23514",
|
||||
"V18 guard must reject new rows for a published version: {insert_into_published}"
|
||||
);
|
||||
|
||||
// Positive control: Draft binding по-прежнему изменяем (обычный UPDATE).
|
||||
save_resource_bindings(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
&draft_agent,
|
||||
&[AgentResourceBinding {
|
||||
resource_id: resource.clone(),
|
||||
resource_version: 1,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.expect("a Draft Agent binding must be accepted");
|
||||
let draft_move = sqlx::query(
|
||||
"update agent_resource_bindings set resource_version = 2
|
||||
where agent_id = $1 and agent_version = 1",
|
||||
)
|
||||
.bind(draft_agent.as_str())
|
||||
.execute(&sandbox.pool)
|
||||
.await
|
||||
.expect("a Draft binding must remain mutable");
|
||||
assert_eq!(draft_move.rows_affected(), 1);
|
||||
|
||||
// Отказы не тронули published snapshot и каталог.
|
||||
assert_eq!(binding_rows(&sandbox, published_agent.as_str()).await, 1);
|
||||
let pinned = sandbox
|
||||
.registry
|
||||
.get_agent_version(&WorkspaceId::new("ws_default"), &published_agent, 1)
|
||||
.await
|
||||
.expect("agent version must be readable")
|
||||
.expect("agent version must exist");
|
||||
assert_eq!(
|
||||
pinned.resource_bindings,
|
||||
vec![AgentResourceBinding {
|
||||
resource_id: resource.clone(),
|
||||
resource_version: 1
|
||||
}],
|
||||
"refused relocations must keep the published exact v1"
|
||||
);
|
||||
let catalog = sandbox
|
||||
.registry
|
||||
.get_published_agent_catalog_by_slug("default", "v18-move-pub")
|
||||
.await
|
||||
.expect("published catalog must be readable");
|
||||
assert_eq!(catalog.agent_version, 1);
|
||||
assert_eq!(
|
||||
catalog.resources,
|
||||
vec![AgentResourceBinding {
|
||||
resource_id: resource,
|
||||
resource_version: 1
|
||||
}],
|
||||
"the published catalog must keep the original exact snapshot"
|
||||
);
|
||||
sandbox.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story37_v18_exact_v1_survives_resource_v2_and_catalog_reader_is_coherent() {
|
||||
let sandbox = sandbox("v18_exact_v1").await;
|
||||
let resource = published_resource(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"res_v18_exact",
|
||||
"crank://v18/exact",
|
||||
b"exact v1",
|
||||
)
|
||||
.await;
|
||||
let agent = create_draft_agent(&sandbox, "ws_default", "agent_v18_exact", "v18-exact").await;
|
||||
save_resource_bindings(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
&agent,
|
||||
&[AgentResourceBinding {
|
||||
resource_id: resource.clone(),
|
||||
resource_version: 1,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.expect("draft exact v1 must be saved");
|
||||
sandbox
|
||||
.registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &WorkspaceId::new("ws_default"),
|
||||
agent_id: &agent,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: None,
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("Agent must publish");
|
||||
let summary_before = sandbox
|
||||
.registry
|
||||
.get_agent_summary(&WorkspaceId::new("ws_default"), &agent)
|
||||
.await
|
||||
.expect("summary must be readable")
|
||||
.expect("summary must exist");
|
||||
|
||||
draft_next_resource_version(&sandbox, "ws_default", &resource, b"exact v2").await;
|
||||
assert_eq!(
|
||||
publish_current_resource(&sandbox, "ws_default", &resource, b"exact v2").await,
|
||||
2,
|
||||
"the edited Draft must publish as exact v2"
|
||||
);
|
||||
|
||||
let pinned = sandbox
|
||||
.registry
|
||||
.get_agent_version(&WorkspaceId::new("ws_default"), &agent, 1)
|
||||
.await
|
||||
.expect("agent version must be readable")
|
||||
.expect("agent version must exist");
|
||||
assert_eq!(
|
||||
pinned.resource_bindings,
|
||||
vec![AgentResourceBinding {
|
||||
resource_id: resource.clone(),
|
||||
resource_version: 1
|
||||
}],
|
||||
"Resource v2 must not replace the pinned exact v1"
|
||||
);
|
||||
let summary_after = sandbox
|
||||
.registry
|
||||
.get_agent_summary(&WorkspaceId::new("ws_default"), &agent)
|
||||
.await
|
||||
.expect("summary must be readable")
|
||||
.expect("summary must exist");
|
||||
assert_eq!(
|
||||
summary_after.catalog_revision, summary_before.catalog_revision,
|
||||
"a Resource publication must not bump the Agent catalog_revision"
|
||||
);
|
||||
|
||||
let catalog = sandbox
|
||||
.registry
|
||||
.get_published_agent_catalog_by_slug("default", "v18-exact")
|
||||
.await
|
||||
.expect("published catalog must be readable");
|
||||
assert_eq!(
|
||||
catalog.agent_version, 1,
|
||||
"catalog must keep the published Agent version"
|
||||
);
|
||||
assert_eq!(
|
||||
catalog.catalog_revision,
|
||||
format!(
|
||||
"agent-version-1-catalog-revision-{}",
|
||||
summary_after.catalog_revision
|
||||
),
|
||||
"resources and revision must come from the same published snapshot"
|
||||
);
|
||||
assert_eq!(
|
||||
catalog.resources,
|
||||
vec![AgentResourceBinding {
|
||||
resource_id: resource,
|
||||
resource_version: 1
|
||||
}],
|
||||
"catalog reader must expose the exact pinned Resource Version"
|
||||
);
|
||||
|
||||
// Явный republish Agent фиксирует новый snapshot, старый остаётся exact v1.
|
||||
sandbox
|
||||
.registry
|
||||
.save_agent_catalog_config_editable(SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &WorkspaceId::new("ws_default"),
|
||||
agent_id: &agent,
|
||||
agent_version: 1,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &Default::default(),
|
||||
resource_bindings: &[AgentResourceBinding {
|
||||
resource_id: ResourceId::new("res_v18_exact"),
|
||||
resource_version: 2,
|
||||
}],
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("editing a published Agent must fork a new Draft with v2");
|
||||
sandbox
|
||||
.registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &WorkspaceId::new("ws_default"),
|
||||
agent_id: &agent,
|
||||
version: 2,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: None,
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("republished Agent version 2 must publish");
|
||||
let catalog_v2 = sandbox
|
||||
.registry
|
||||
.get_published_agent_catalog_by_slug("default", "v18-exact")
|
||||
.await
|
||||
.expect("published catalog must be readable");
|
||||
assert_eq!(catalog_v2.agent_version, 2);
|
||||
assert_eq!(
|
||||
catalog_v2.resources,
|
||||
vec![AgentResourceBinding {
|
||||
resource_id: ResourceId::new("res_v18_exact"),
|
||||
resource_version: 2
|
||||
}],
|
||||
"an explicit republish must switch the catalog to the new exact snapshot"
|
||||
);
|
||||
let still_v1 = sandbox
|
||||
.registry
|
||||
.get_agent_version(&WorkspaceId::new("ws_default"), &agent, 1)
|
||||
.await
|
||||
.expect("agent version must be readable")
|
||||
.expect("agent version must exist");
|
||||
assert_eq!(
|
||||
still_v1.resource_bindings,
|
||||
vec![AgentResourceBinding {
|
||||
resource_id: ResourceId::new("res_v18_exact"),
|
||||
resource_version: 1
|
||||
}],
|
||||
"the earlier published snapshot must stay exact v1"
|
||||
);
|
||||
sandbox.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story37_v18_failed_write_and_publication_leave_no_partial_state() {
|
||||
let sandbox = sandbox("v18_rollback").await;
|
||||
let resource = published_resource(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"res_v18_rollback",
|
||||
"crank://v18/rollback",
|
||||
b"rollback v1",
|
||||
)
|
||||
.await;
|
||||
// Draft v2 существует, но не опубликован: exact version недоступна для binding.
|
||||
draft_next_resource_version(&sandbox, "ws_default", &resource, b"rollback v2").await;
|
||||
let agent = create_draft_agent(&sandbox, "ws_default", "agent_v18_rollback", "v18-rb").await;
|
||||
|
||||
let failed_save = save_resource_bindings(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
&agent,
|
||||
&[AgentResourceBinding {
|
||||
resource_id: resource.clone(),
|
||||
resource_version: 2,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.expect_err("an unpublished Resource version must fail the write");
|
||||
assert!(
|
||||
matches!(failed_save, crank_registry::RegistryError::Storage(_)),
|
||||
"the FK refusal must surface as a storage error: {failed_save}"
|
||||
);
|
||||
assert_eq!(
|
||||
binding_rows(&sandbox, agent.as_str()).await,
|
||||
0,
|
||||
"a failed save must not leave partial binding rows"
|
||||
);
|
||||
let versions: i64 =
|
||||
sqlx::query_scalar("select count(*) from agent_versions where agent_id = $1")
|
||||
.bind(agent.as_str())
|
||||
.fetch_one(&sandbox.pool)
|
||||
.await
|
||||
.expect("agent versions must be queryable");
|
||||
assert_eq!(versions, 1, "a failed save must not add a version row");
|
||||
let summary = sandbox
|
||||
.registry
|
||||
.get_agent_summary(&WorkspaceId::new("ws_default"), &agent)
|
||||
.await
|
||||
.expect("summary must be readable")
|
||||
.expect("summary must exist");
|
||||
assert_eq!(
|
||||
summary.current_draft_version, 1,
|
||||
"a failed save must not move the Draft pointer"
|
||||
);
|
||||
|
||||
// Stale publication: отказ до записи, pointer/revision/rows не меняются.
|
||||
save_resource_bindings(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
&agent,
|
||||
&[AgentResourceBinding {
|
||||
resource_id: resource.clone(),
|
||||
resource_version: 1,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.expect("a published exact v1 must be accepted");
|
||||
let stale_state = crank_registry::AgentStateExpectation {
|
||||
status: AgentStatus::Draft,
|
||||
current_draft_version: 1,
|
||||
latest_published_version: None,
|
||||
catalog_revision: summary.catalog_revision,
|
||||
updated_at: summary.updated_at,
|
||||
};
|
||||
let failed_publish = sandbox
|
||||
.registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &WorkspaceId::new("ws_default"),
|
||||
agent_id: &agent,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: None,
|
||||
expected_state: Some(&stale_state),
|
||||
})
|
||||
.await
|
||||
.expect_err("a stale publication precondition must fail");
|
||||
assert!(
|
||||
matches!(
|
||||
failed_publish,
|
||||
crank_registry::RegistryError::AgentStaleRevision { .. }
|
||||
),
|
||||
"stale publication must keep the Agent taxonomy: {failed_publish}"
|
||||
);
|
||||
let published_rows: i64 =
|
||||
sqlx::query_scalar("select count(*) from published_agents where agent_id = $1")
|
||||
.bind(agent.as_str())
|
||||
.fetch_one(&sandbox.pool)
|
||||
.await
|
||||
.expect("published pointer must be queryable");
|
||||
assert_eq!(
|
||||
published_rows, 0,
|
||||
"a failed publish must not write a pointer"
|
||||
);
|
||||
let after = sandbox
|
||||
.registry
|
||||
.get_agent_summary(&WorkspaceId::new("ws_default"), &agent)
|
||||
.await
|
||||
.expect("summary must be readable")
|
||||
.expect("summary must exist");
|
||||
assert_eq!(after.catalog_revision, summary.catalog_revision);
|
||||
assert_eq!(after.latest_published_version, None);
|
||||
assert_eq!(
|
||||
binding_rows(&sandbox, agent.as_str()).await,
|
||||
1,
|
||||
"a failed publish must not drop the draft binding"
|
||||
);
|
||||
|
||||
// Positive control: корректная публикация атомарно двигает pointer и revision.
|
||||
sandbox
|
||||
.registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &WorkspaceId::new("ws_default"),
|
||||
agent_id: &agent,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: None,
|
||||
expected_state: Some(&crank_registry::AgentStateExpectation {
|
||||
status: after.status,
|
||||
current_draft_version: after.current_draft_version,
|
||||
latest_published_version: after.latest_published_version,
|
||||
catalog_revision: after.catalog_revision,
|
||||
updated_at: after.updated_at,
|
||||
}),
|
||||
})
|
||||
.await
|
||||
.expect("a fresh precondition must publish");
|
||||
let published = sandbox
|
||||
.registry
|
||||
.get_agent_summary(&WorkspaceId::new("ws_default"), &agent)
|
||||
.await
|
||||
.expect("summary must be readable")
|
||||
.expect("summary must exist");
|
||||
assert_eq!(published.latest_published_version, Some(1));
|
||||
assert_eq!(
|
||||
published.catalog_revision,
|
||||
after.catalog_revision + 1,
|
||||
"publication must raise catalog_revision by exactly one"
|
||||
);
|
||||
assert_eq!(
|
||||
published.status,
|
||||
AgentStatus::Published,
|
||||
"publication must atomically switch the Agent pointer"
|
||||
);
|
||||
sandbox.cleanup().await;
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
//! Story 3.8 / AC04 regression: archive and a *new* Resource binding are serialized by the
|
||||
//! database, not decided by an unlocked check-then-write.
|
||||
//!
|
||||
//! The binding write must lock every candidate `resources` row before it inspects the lifecycle
|
||||
//! status, so:
|
||||
//! - an archive that already committed wins and the binding is refused (no partial writes);
|
||||
//! - a binding that already holds the rows commits first and the archive legally follows it.
|
||||
//!
|
||||
//! Both orders are orchestrated by real lock state (`pg_locks`, test container is per test binary
|
||||
//! and `--test-threads=1` keeps it exclusive), never by sleep timing, and both use the real
|
||||
//! registry calls (`save_agent_catalog_config` / `archive_resource`).
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use crank_core::WorkspaceId;
|
||||
use crank_registry::model::resource::ArchiveResourceRequest;
|
||||
use crank_registry::{AgentResourceBinding, RegistryError, SaveAgentCatalogConfigRequest};
|
||||
use sqlx::Row;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Advisory-lock key of the test-only insert gate below (test schema only, released with the txn).
|
||||
const BINDING_GATE_KEY: i64 = 3810;
|
||||
|
||||
/// Bounded wait for a *waiting* lock of `locktype`: the orchestration follows observable PostgreSQL
|
||||
/// lock state instead of guessing with sleeps. Returns whether the wait was observed within the
|
||||
/// deadline, so a caller can turn a missing wait into a meaningful assertion failure.
|
||||
async fn await_lock_wait(pool: &sqlx::PgPool, locktype: &str) -> bool {
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
|
||||
loop {
|
||||
let waiting: i64 =
|
||||
sqlx::query_scalar("select count(*) from pg_locks where locktype = $1 and not granted")
|
||||
.bind(locktype)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.expect("pg_locks must be observable in the test database");
|
||||
if waiting > 0 {
|
||||
return true;
|
||||
}
|
||||
if tokio::time::Instant::now() >= deadline {
|
||||
return false;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
}
|
||||
|
||||
fn requested_binding(resource: &ResourceId) -> AgentResourceBinding {
|
||||
AgentResourceBinding {
|
||||
resource_id: resource.clone(),
|
||||
resource_version: 1,
|
||||
}
|
||||
}
|
||||
|
||||
fn stored_binding_rows(rows: Vec<sqlx::postgres::PgRow>) -> Vec<AgentResourceBinding> {
|
||||
rows.iter()
|
||||
.map(|row| AgentResourceBinding {
|
||||
resource_id: ResourceId::new(
|
||||
row.try_get::<String, _>("resource_id")
|
||||
.expect("binding resource id must decode"),
|
||||
),
|
||||
resource_version: 1,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Archive wins the race: it holds the Resource row lock (exactly like `archive_resource`) while the
|
||||
/// binding attempt starts, so the binding must observe `archived` and refuse without writing.
|
||||
#[tokio::test]
|
||||
async fn story38_archive_first_refuses_a_new_binding_without_partial_writes() {
|
||||
let sandbox = sandbox("archive_race_archive_first").await;
|
||||
let resource = published_resource(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"res_race_archive_first",
|
||||
"crank://race/archive-first",
|
||||
b"archive first v1",
|
||||
)
|
||||
.await;
|
||||
let agent = create_draft_agent(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"agent_race_archive_first",
|
||||
"race-af",
|
||||
)
|
||||
.await;
|
||||
let before = sandbox
|
||||
.registry
|
||||
.get_agent_summary(&WorkspaceId::new("ws_default"), &agent)
|
||||
.await
|
||||
.expect("agent summary must be readable")
|
||||
.expect("agent summary must exist");
|
||||
|
||||
// The archiver locks and archives the row in one transaction, then commits only after the
|
||||
// binding attempt is observably waiting for that transaction.
|
||||
let concurrent = sandbox.database.concurrent_registry(8).await;
|
||||
let orchestration = concurrent.pool();
|
||||
let mut archiver = orchestration
|
||||
.begin()
|
||||
.await
|
||||
.expect("archiver transaction must start");
|
||||
let status: String = sqlx::query_scalar(
|
||||
"select status
|
||||
from resources
|
||||
where workspace_id = $1 and resource_id = $2
|
||||
for update",
|
||||
)
|
||||
.bind("ws_default")
|
||||
.bind(resource.as_str())
|
||||
.fetch_one(&mut *archiver)
|
||||
.await
|
||||
.expect("the archive candidate must be lockable");
|
||||
assert_eq!(status, "published");
|
||||
sqlx::query(
|
||||
"update resources
|
||||
set status = 'archived', updated_at = now()
|
||||
where workspace_id = $1 and resource_id = $2",
|
||||
)
|
||||
.bind("ws_default")
|
||||
.bind(resource.as_str())
|
||||
.execute(&mut *archiver)
|
||||
.await
|
||||
.expect("the locked Resource row must accept the archive transition");
|
||||
|
||||
let writer = concurrent.clone();
|
||||
let writer_binding = requested_binding(&resource);
|
||||
let writer_agent = agent.clone();
|
||||
let binding = tokio::spawn(async move {
|
||||
writer
|
||||
.save_agent_catalog_config(SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &WorkspaceId::new("ws_default"),
|
||||
agent_id: &writer_agent,
|
||||
agent_version: 1,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &Default::default(),
|
||||
resource_bindings: std::slice::from_ref(&writer_binding),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
});
|
||||
|
||||
// The binding write must wait for the archiver's transaction: it cannot pass the lifecycle
|
||||
// check before that transaction ends.
|
||||
let waited = await_lock_wait(orchestration, "transactionid").await;
|
||||
archiver
|
||||
.commit()
|
||||
.await
|
||||
.expect("the archive must commit after the binding is waiting");
|
||||
|
||||
let outcome = binding.await.expect("the binding task must finish");
|
||||
assert!(
|
||||
waited,
|
||||
"the binding write must wait for the in-flight archive instead of racing it: {outcome:?}"
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
outcome,
|
||||
Err(RegistryError::ResourceArchived { ref resource_id })
|
||||
if resource_id == resource.as_str()
|
||||
),
|
||||
"a binding that loses against a committed archive must be refused: {outcome:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
binding_rows(&sandbox, agent.as_str()).await,
|
||||
0,
|
||||
"a refused binding must not leave partial rows"
|
||||
);
|
||||
let after = sandbox
|
||||
.registry
|
||||
.get_agent_summary(&WorkspaceId::new("ws_default"), &agent)
|
||||
.await
|
||||
.expect("agent summary must be readable")
|
||||
.expect("agent summary must exist");
|
||||
assert_eq!(
|
||||
after.updated_at, before.updated_at,
|
||||
"a refused binding must not move the Agent updated_at"
|
||||
);
|
||||
assert_eq!(
|
||||
after.catalog_revision, before.catalog_revision,
|
||||
"a refused binding must not bump catalog_revision"
|
||||
);
|
||||
let archived: String = sqlx::query_scalar(
|
||||
"select status from resources where workspace_id = $1 and resource_id = $2",
|
||||
)
|
||||
.bind("ws_default")
|
||||
.bind(resource.as_str())
|
||||
.fetch_one(&sandbox.pool)
|
||||
.await
|
||||
.expect("the archived Resource must be readable");
|
||||
assert_eq!(archived, "archived");
|
||||
sandbox.cleanup().await;
|
||||
}
|
||||
|
||||
/// Binding wins the race: the binding transaction holds the Resource row locks and is held inside
|
||||
/// its insert by a test-only gate, an archive that starts meanwhile must wait, and after the
|
||||
/// binding commits the archive legally follows it (both rows, no deadlock, no rolled-back archive).
|
||||
#[tokio::test]
|
||||
async fn story38_binding_first_serializes_before_a_later_archive() {
|
||||
let sandbox = sandbox("archive_race_binding_first").await;
|
||||
let resource = published_resource(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"res_race_binding_first",
|
||||
"crank://race/binding-first",
|
||||
b"binding first v1",
|
||||
)
|
||||
.await;
|
||||
let agent = create_draft_agent(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"agent_race_binding_first",
|
||||
"race-bf",
|
||||
)
|
||||
.await;
|
||||
|
||||
// Test-only gate: the insert already runs after the Resource rows are locked, so holding this
|
||||
// advisory lock deterministically places the archive behind those row locks.
|
||||
sqlx::raw_sql(
|
||||
"create function crank_test_gate_binding_write()
|
||||
returns trigger language plpgsql as $$
|
||||
begin
|
||||
perform pg_advisory_xact_lock(3810);
|
||||
return new;
|
||||
end;
|
||||
$$;
|
||||
create trigger crank_test_gate_binding_write_gate
|
||||
before insert on agent_resource_bindings
|
||||
for each row execute function crank_test_gate_binding_write();",
|
||||
)
|
||||
.execute(&sandbox.pool)
|
||||
.await
|
||||
.expect("the test-only binding gate trigger must install");
|
||||
let concurrent = sandbox.database.concurrent_registry(8).await;
|
||||
let orchestration = concurrent.pool();
|
||||
let mut gate = orchestration
|
||||
.acquire()
|
||||
.await
|
||||
.expect("the gate connection must be acquired");
|
||||
sqlx::query("select pg_advisory_lock($1)")
|
||||
.bind(BINDING_GATE_KEY)
|
||||
.execute(&mut *gate)
|
||||
.await
|
||||
.expect("the gate advisory lock must be taken");
|
||||
|
||||
let writer = concurrent.clone();
|
||||
let writer_binding = requested_binding(&resource);
|
||||
let writer_agent = agent.clone();
|
||||
let binding = tokio::spawn(async move {
|
||||
writer
|
||||
.save_agent_catalog_config(SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &WorkspaceId::new("ws_default"),
|
||||
agent_id: &writer_agent,
|
||||
agent_version: 1,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &Default::default(),
|
||||
resource_bindings: std::slice::from_ref(&writer_binding),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
});
|
||||
// The binding transaction is now past the Resource row locks and parked on the gate.
|
||||
assert!(
|
||||
await_lock_wait(orchestration, "advisory").await,
|
||||
"the binding transaction must reach its insert (and therefore already hold the Resource row locks)"
|
||||
);
|
||||
|
||||
let current = sandbox
|
||||
.registry
|
||||
.get_resource_draft("ws_default", &resource)
|
||||
.await
|
||||
.expect("the Resource draft must be readable before archive");
|
||||
let archiver_registry = sandbox.registry.clone();
|
||||
let archiver_resource = resource.clone();
|
||||
let expected_updated_at = current.resource.updated_at;
|
||||
let archiver = tokio::spawn(async move {
|
||||
archiver_registry
|
||||
.archive_resource(ArchiveResourceRequest {
|
||||
workspace_id: WorkspaceId::new("ws_default"),
|
||||
resource_id: archiver_resource,
|
||||
expected_updated_at,
|
||||
archived_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
});
|
||||
// The archive cannot overtake the binding: it waits for the binding transaction.
|
||||
assert!(
|
||||
await_lock_wait(orchestration, "transactionid").await,
|
||||
"the archive must wait for the binding transaction that holds the Resource row locks"
|
||||
);
|
||||
|
||||
sqlx::query("select pg_advisory_unlock($1)")
|
||||
.bind(BINDING_GATE_KEY)
|
||||
.execute(&mut *gate)
|
||||
.await
|
||||
.expect("the gate advisory lock must be releasable");
|
||||
drop(gate);
|
||||
|
||||
binding
|
||||
.await
|
||||
.expect("the binding task must finish")
|
||||
.expect("a binding that commits before the archive must be accepted");
|
||||
archiver
|
||||
.await
|
||||
.expect("the archive task must finish")
|
||||
.expect("the archive must follow the committed binding");
|
||||
|
||||
let rows: Vec<sqlx::postgres::PgRow> = sqlx::query(
|
||||
"select resource_id
|
||||
from agent_resource_bindings
|
||||
where agent_id = $1 and agent_version = 1",
|
||||
)
|
||||
.bind(agent.as_str())
|
||||
.fetch_all(&sandbox.pool)
|
||||
.await
|
||||
.expect("binding rows must be queryable");
|
||||
assert_eq!(
|
||||
stored_binding_rows(rows),
|
||||
vec![requested_binding(&resource)],
|
||||
"the binding that won the race must stay written"
|
||||
);
|
||||
let archived: String = sqlx::query_scalar(
|
||||
"select status from resources where workspace_id = $1 and resource_id = $2",
|
||||
)
|
||||
.bind("ws_default")
|
||||
.bind(resource.as_str())
|
||||
.fetch_one(&sandbox.pool)
|
||||
.await
|
||||
.expect("the archived Resource must be readable");
|
||||
assert_eq!(
|
||||
archived, "archived",
|
||||
"the archive must complete once the binding transaction ended"
|
||||
);
|
||||
// The immutable published snapshot is untouched by the archive.
|
||||
let snapshot = sandbox
|
||||
.registry
|
||||
.resolve_resource_publication("ws_default", &resource, 1)
|
||||
.await
|
||||
.expect("the exact published version must stay readable after archive");
|
||||
let published = registered(&sandbox, b"binding first v1");
|
||||
assert_eq!(
|
||||
snapshot.publication.digest.as_str(),
|
||||
published.artifact_ref().digest_hex(),
|
||||
"archive must not rewrite the published digest"
|
||||
);
|
||||
sandbox.cleanup().await;
|
||||
}
|
||||
@@ -0,0 +1,572 @@
|
||||
//! Story 3.8 / AT-3.8-04: real concurrency between the live read guard and the revoke
|
||||
//! transition (owner decision A).
|
||||
//!
|
||||
//! Every scenario drives the *production* registry operations on separate multi-connection
|
||||
//! registries over one test schema. The orchestration is a PostgreSQL barrier: each backend
|
||||
//! carries its own `application_name`, `pg_blocking_pids` names the actual blocker, and a
|
||||
//! test-only advisory-lock trigger parks the revoke transaction after it took its row lock.
|
||||
//! Nothing here waits on timing alone, and no helper stubs the product.
|
||||
//!
|
||||
//! - revoke-first: a read that starts after the revoke took its lock waits, then is denied
|
||||
//! (`Revoked`) without ever receiving a publication, so no artifact byte can be opened;
|
||||
//! - read-first: the revoke waits for the in-flight guard and only then commits, so a read
|
||||
//! linearized before the revoke may still finish;
|
||||
//! - two first revokes on different connections produce exactly one audit event and keep the
|
||||
//! first actor/correlation;
|
||||
//! - dropping a guard releases the lock, and cancelling a waiting revoke leaves no tombstone.
|
||||
|
||||
use std::str::FromStr;
|
||||
use std::time::Duration;
|
||||
|
||||
use crank_core::WorkspaceId;
|
||||
use crank_core::ids::ResourceId;
|
||||
use crank_core::resource::ResourceError;
|
||||
use crank_registry::model::resource::RevokeResourceRequest;
|
||||
use crank_registry::{PostgresPoolConfig, PostgresRegistry};
|
||||
use sqlx::postgres::PgConnectOptions;
|
||||
use sqlx::{PgPool, Row};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Advisory gate key used by the test-only tombstone-insert trigger (test schema only).
|
||||
pub(super) const REVOCATION_GATE_KEY: i64 = 3821;
|
||||
|
||||
/// A registry whose backends are identifiable in `pg_stat_activity` by `application_name`.
|
||||
pub(super) async fn attributed_registry(
|
||||
sandbox: &Sandbox,
|
||||
application_name: &str,
|
||||
) -> PostgresRegistry {
|
||||
let base_url = crank_test_support::postgres_database_url().await;
|
||||
let schema: String = sqlx::query_scalar("select current_schema()")
|
||||
.fetch_one(&sandbox.pool)
|
||||
.await
|
||||
.expect("the test schema must be resolvable");
|
||||
let url = format!(
|
||||
"{base_url}?options=-csearch_path%3D{schema}%20-capplication_name%3D{application_name}"
|
||||
);
|
||||
let options = PgConnectOptions::from_str(&url).expect("attributed connect options must parse");
|
||||
PostgresRegistry::connect_with_options_and_pool_config(
|
||||
options,
|
||||
PostgresPoolConfig {
|
||||
max_connections: 6,
|
||||
min_connections: 0,
|
||||
acquire_timeout_ms: 10_000,
|
||||
idle_timeout_ms: 600_000,
|
||||
max_lifetime_ms: 1_800_000,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("the attributed test registry must connect")
|
||||
}
|
||||
|
||||
/// Install a test-only gate: a BEFORE trigger on `table` parks the writing transaction on an
|
||||
/// advisory lock, so the operation observably holds every lock it already took while the test
|
||||
/// starts the competitor. The trigger lives only in this test's private schema.
|
||||
pub(super) async fn install_advisory_gate(
|
||||
sandbox: &Sandbox,
|
||||
function: &str,
|
||||
table: &str,
|
||||
key: i64,
|
||||
) {
|
||||
let sql = format!(
|
||||
"create function {function}() returns trigger language plpgsql as $$
|
||||
begin
|
||||
perform pg_advisory_xact_lock({key});
|
||||
return new;
|
||||
end $$;
|
||||
create trigger {function}_gate
|
||||
before insert or update on {table}
|
||||
for each row execute function {function}();"
|
||||
);
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(sql))
|
||||
.execute(&sandbox.pool)
|
||||
.await
|
||||
.expect("the test-only advisory gate trigger must install");
|
||||
}
|
||||
|
||||
/// Install the gate inside the audited tombstone insert.
|
||||
pub(super) async fn install_revocation_gate(sandbox: &Sandbox) {
|
||||
install_advisory_gate(
|
||||
sandbox,
|
||||
"crank_test_gate_revocation_insert",
|
||||
"resource_security_revocations",
|
||||
REVOCATION_GATE_KEY,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Take the session-level advisory lock a gate function waits for.
|
||||
pub(super) async fn take_gate(sandbox: &Sandbox, key: i64) -> PgPool {
|
||||
let base_url = crank_test_support::postgres_database_url().await;
|
||||
let schema: String = sqlx::query_scalar("select current_schema()")
|
||||
.fetch_one(&sandbox.pool)
|
||||
.await
|
||||
.expect("the test schema must be resolvable");
|
||||
let url =
|
||||
format!("{base_url}?options=-csearch_path%3D{schema}%20-capplication_name%3Dstory38-gate");
|
||||
let pool = PgPool::connect(&url)
|
||||
.await
|
||||
.expect("the gate pool must connect to the test schema");
|
||||
sqlx::query("select pg_advisory_lock($1)")
|
||||
.bind(key)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("the gate advisory lock must be taken");
|
||||
pool
|
||||
}
|
||||
|
||||
pub(super) async fn release_gate(gate: PgPool, key: i64) {
|
||||
sqlx::query("select pg_advisory_unlock($1)")
|
||||
.bind(key)
|
||||
.execute(&gate)
|
||||
.await
|
||||
.expect("the gate advisory lock must be releasable");
|
||||
drop(gate);
|
||||
}
|
||||
|
||||
/// Precise barrier: `waiter` is blocked by a backend whose `application_name` is `blocker`.
|
||||
/// Returns false after the deadline so the caller turns a missing wait into a real assertion.
|
||||
pub(super) async fn await_blocked_by(pool: &PgPool, waiter: &str, blocker: &str) -> bool {
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(15);
|
||||
loop {
|
||||
let waiters: Vec<i32> = sqlx::query_scalar(
|
||||
"select pid from pg_stat_activity
|
||||
where datname = current_database() and application_name = $1",
|
||||
)
|
||||
.bind(waiter)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.expect("pg_stat_activity must be observable");
|
||||
for pid in waiters {
|
||||
let blockers: Vec<i32> = sqlx::query_scalar("select unnest(pg_blocking_pids($1))")
|
||||
.bind(pid)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.expect("pg_blocking_pids must be observable");
|
||||
if blockers.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let names: Vec<String> = sqlx::query_scalar(
|
||||
"select application_name from pg_stat_activity where pid = any($1)",
|
||||
)
|
||||
.bind(&blockers)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.expect("blocking backends must be observable");
|
||||
if names.iter().any(|name| name == blocker) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if tokio::time::Instant::now() >= deadline {
|
||||
return false;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn revoke_request(resource: &ResourceId, request_id: &str) -> RevokeResourceRequest {
|
||||
RevokeResourceRequest {
|
||||
workspace_id: WorkspaceId::new("ws_default"),
|
||||
resource_id: resource.clone(),
|
||||
actor_user_id: "user_default_owner".to_owned(),
|
||||
request_id: request_id.to_owned(),
|
||||
trace_id: format!("{request_id}-trace"),
|
||||
revoked_at: OffsetDateTime::now_utc(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Draft → Published v1 with a caller-chosen unique name (the fixture name is unique per
|
||||
/// workspace, so a second Resource in the same schema needs its own).
|
||||
async fn published_named_resource(
|
||||
sandbox: &Sandbox,
|
||||
workspace: &str,
|
||||
resource_id: &str,
|
||||
uri: &str,
|
||||
name: &str,
|
||||
bytes: &[u8],
|
||||
) -> ResourceId {
|
||||
let resource = ResourceId::new(resource_id);
|
||||
sandbox
|
||||
.registry
|
||||
.create_resource_draft(
|
||||
crank_registry::model::resource::CreateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new(workspace),
|
||||
resource_id: resource.clone(),
|
||||
uri: uri.to_owned(),
|
||||
name: name.to_owned(),
|
||||
description: String::new(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
artifact: registered(sandbox, bytes),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("the named resource draft must be created");
|
||||
publish_current_resource(sandbox, workspace, &resource, bytes).await;
|
||||
resource
|
||||
}
|
||||
|
||||
pub(super) async fn tombstone_rows(pool: &PgPool) -> i64 {
|
||||
sqlx::query_scalar("select count(*) from resource_security_revocations")
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.expect("tombstones must be queryable")
|
||||
}
|
||||
|
||||
/// Revoke wins: the read that starts behind the revoke lock is denied before any publication
|
||||
/// (and therefore before any artifact read), while the revoke itself is a normal 204 path.
|
||||
#[tokio::test]
|
||||
async fn story38_revoke_first_denies_a_waiting_read_without_a_publication() {
|
||||
let sandbox = sandbox("revocation_race_revoke_first").await;
|
||||
let resource = published_resource(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"res_race_revoke_first",
|
||||
"crank://race/revoke-first",
|
||||
b"revoke first v1",
|
||||
)
|
||||
.await;
|
||||
install_revocation_gate(&sandbox).await;
|
||||
let gate = take_gate(&sandbox, REVOCATION_GATE_KEY).await;
|
||||
|
||||
let revoker = attributed_registry(&sandbox, "story38-revoker").await;
|
||||
let revoke_resource = resource.clone();
|
||||
let revoke = tokio::spawn(async move {
|
||||
revoker
|
||||
.revoke_resource(revoke_request(
|
||||
&revoke_resource,
|
||||
"story38-race-revoke-first",
|
||||
))
|
||||
.await
|
||||
});
|
||||
assert!(
|
||||
await_blocked_by(&sandbox.pool, "story38-revoker", "story38-gate").await,
|
||||
"the revoke transaction must reach its tombstone insert and hold the Resource row lock"
|
||||
);
|
||||
|
||||
// This read starts after the revoke took `resources FOR UPDATE`: it cannot pass the guard.
|
||||
let reader = attributed_registry(&sandbox, "story38-reader").await;
|
||||
let read_resource = resource.clone();
|
||||
let read = tokio::spawn(async move {
|
||||
reader
|
||||
.begin_authorized_resource_read("ws_default", &read_resource, 1)
|
||||
.await
|
||||
.map(|guard| guard.publication().publication.uri.clone())
|
||||
});
|
||||
assert!(
|
||||
await_blocked_by(&sandbox.pool, "story38-reader", "story38-revoker").await,
|
||||
"the read must wait for the in-flight revoke instead of racing it"
|
||||
);
|
||||
assert!(
|
||||
!read.is_finished(),
|
||||
"a read behind the revoke must not complete while the revoke holds the row"
|
||||
);
|
||||
|
||||
release_gate(gate, REVOCATION_GATE_KEY).await;
|
||||
tokio::time::timeout(Duration::from_secs(15), revoke)
|
||||
.await
|
||||
.expect("revoke must finish once the gate is released")
|
||||
.expect("revoke task must not panic")
|
||||
.expect("revoke must commit");
|
||||
let outcome = tokio::time::timeout(Duration::from_secs(15), read)
|
||||
.await
|
||||
.expect("the waiting read must finish after the revoke commits")
|
||||
.expect("read task must not panic");
|
||||
assert!(
|
||||
matches!(outcome, Err(ResourceError::Revoked)),
|
||||
"revoke-first must deny the read with the typed Revoked outcome, got {outcome:?}"
|
||||
);
|
||||
assert_eq!(tombstone_rows(&sandbox.pool).await, 1);
|
||||
sandbox.cleanup().await;
|
||||
}
|
||||
|
||||
/// Read wins: the revoke waits for the in-flight guard and commits afterwards; the read is
|
||||
/// linearized before the revoke and only post-revoke reads see `Revoked`.
|
||||
#[tokio::test]
|
||||
async fn story38_read_first_serializes_a_revoke_after_the_in_flight_guard() {
|
||||
let sandbox = sandbox("revocation_race_read_first").await;
|
||||
let resource = published_resource(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"res_race_read_first",
|
||||
"crank://race/read-first",
|
||||
b"read first v1",
|
||||
)
|
||||
.await;
|
||||
|
||||
let reader = attributed_registry(&sandbox, "story38-reader").await;
|
||||
let guard = reader
|
||||
.begin_authorized_resource_read("ws_default", &resource, 1)
|
||||
.await
|
||||
.expect("an unrevoked Resource must open the live guard");
|
||||
assert_eq!(
|
||||
guard.publication().publication.uri,
|
||||
"crank://race/read-first"
|
||||
);
|
||||
|
||||
let revoker = attributed_registry(&sandbox, "story38-revoker").await;
|
||||
let revoke_resource = resource.clone();
|
||||
let revoke = tokio::spawn(async move {
|
||||
revoker
|
||||
.revoke_resource(revoke_request(&revoke_resource, "story38-race-read-first"))
|
||||
.await
|
||||
});
|
||||
assert!(
|
||||
await_blocked_by(&sandbox.pool, "story38-revoker", "story38-reader").await,
|
||||
"revoke must wait for the in-flight read guard, not bypass its shared lock"
|
||||
);
|
||||
assert!(
|
||||
!revoke.is_finished(),
|
||||
"revoke must not commit while the read guard still holds the row"
|
||||
);
|
||||
|
||||
guard.commit().await.expect("the read must commit");
|
||||
tokio::time::timeout(Duration::from_secs(15), revoke)
|
||||
.await
|
||||
.expect("revoke must finish once the guard is released")
|
||||
.expect("revoke task must not panic")
|
||||
.expect("revoke must commit after the read");
|
||||
assert_eq!(tombstone_rows(&sandbox.pool).await, 1);
|
||||
|
||||
let after = reader
|
||||
.begin_authorized_resource_read("ws_default", &resource, 1)
|
||||
.await
|
||||
.map(|_| ());
|
||||
assert!(
|
||||
matches!(after, Err(ResourceError::Revoked)),
|
||||
"a read that starts after the committed revoke must be denied: {after:?}"
|
||||
);
|
||||
sandbox.cleanup().await;
|
||||
}
|
||||
|
||||
/// Two first revokes on different connections: both succeed, exactly one event is written and
|
||||
/// the first actor/correlation/time survive the second command.
|
||||
#[tokio::test]
|
||||
async fn story38_two_first_revokes_on_different_connections_write_one_event() {
|
||||
let sandbox = sandbox("revocation_race_first_event").await;
|
||||
let resource = published_resource(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"res_race_first_event",
|
||||
"crank://race/first-event",
|
||||
b"first event v1",
|
||||
)
|
||||
.await;
|
||||
install_revocation_gate(&sandbox).await;
|
||||
let gate = take_gate(&sandbox, REVOCATION_GATE_KEY).await;
|
||||
|
||||
let first = attributed_registry(&sandbox, "story38-revoker-a").await;
|
||||
let first_resource = resource.clone();
|
||||
let first_revoke = tokio::spawn(async move {
|
||||
first
|
||||
.revoke_resource(revoke_request(&first_resource, "story38-first-a"))
|
||||
.await
|
||||
});
|
||||
assert!(
|
||||
await_blocked_by(&sandbox.pool, "story38-revoker-a", "story38-gate").await,
|
||||
"the first revoke must hold its row lock inside the audited insert"
|
||||
);
|
||||
|
||||
let second = attributed_registry(&sandbox, "story38-revoker-b").await;
|
||||
let second_resource = resource.clone();
|
||||
let second_revoke = tokio::spawn(async move {
|
||||
second
|
||||
.revoke_resource(revoke_request(&second_resource, "story38-first-b"))
|
||||
.await
|
||||
});
|
||||
assert!(
|
||||
await_blocked_by(&sandbox.pool, "story38-revoker-b", "story38-revoker-a").await,
|
||||
"the second first-revoke must wait for the row lock of the first"
|
||||
);
|
||||
|
||||
release_gate(gate, REVOCATION_GATE_KEY).await;
|
||||
for (name, handle) in [("a", first_revoke), ("b", second_revoke)] {
|
||||
tokio::time::timeout(Duration::from_secs(15), handle)
|
||||
.await
|
||||
.unwrap_or_else(|_| panic!("revoke {name} must finish"))
|
||||
.unwrap_or_else(|_| panic!("revoke {name} task must not panic"))
|
||||
.unwrap_or_else(|error| panic!("revoke {name} must succeed: {error:?}"));
|
||||
}
|
||||
|
||||
assert_eq!(tombstone_rows(&sandbox.pool).await, 1, "one audit event");
|
||||
let row = sqlx::query(
|
||||
"select actor_user_id, request_id, trace_id, revoked_at
|
||||
from resource_security_revocations",
|
||||
)
|
||||
.fetch_one(&sandbox.pool)
|
||||
.await
|
||||
.expect("the single tombstone must be readable");
|
||||
assert_eq!(
|
||||
row.try_get::<String, _>("request_id").unwrap(),
|
||||
"story38-first-a",
|
||||
"the first correlation must be preserved"
|
||||
);
|
||||
assert_eq!(
|
||||
row.try_get::<String, _>("actor_user_id").unwrap(),
|
||||
"user_default_owner"
|
||||
);
|
||||
assert_eq!(
|
||||
row.try_get::<String, _>("trace_id").unwrap(),
|
||||
"story38-first-a-trace"
|
||||
);
|
||||
sandbox.cleanup().await;
|
||||
}
|
||||
|
||||
/// A guard dropped without commit releases the row lock; a cancelled waiting revoke leaves no
|
||||
/// audit event and no stuck lock.
|
||||
#[tokio::test]
|
||||
async fn story38_dropped_guard_and_cancelled_revoke_leave_no_stuck_lock() {
|
||||
let sandbox = sandbox("revocation_race_cancel").await;
|
||||
let resource = published_resource(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"res_race_cancel",
|
||||
"crank://race/cancel",
|
||||
b"cancel v1",
|
||||
)
|
||||
.await;
|
||||
|
||||
let reader = attributed_registry(&sandbox, "story38-reader").await;
|
||||
let guard = reader
|
||||
.begin_authorized_resource_read("ws_default", &resource, 1)
|
||||
.await
|
||||
.expect("the guard must open before the revoke");
|
||||
drop(guard);
|
||||
|
||||
let revoker = attributed_registry(&sandbox, "story38-revoker").await;
|
||||
let revoke_resource = resource.clone();
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(15),
|
||||
revoker.revoke_resource(revoke_request(&revoke_resource, "story38-after-drop")),
|
||||
)
|
||||
.await
|
||||
.expect("a revoke after a dropped guard must not hang")
|
||||
.expect("the revoke must succeed once the guard is dropped");
|
||||
assert_eq!(tombstone_rows(&sandbox.pool).await, 1);
|
||||
|
||||
// Second Resource: a revoke cancelled while waiting must not write anything.
|
||||
let other = published_named_resource(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"res_race_cancel_two",
|
||||
"crank://race/cancel-two",
|
||||
"cancel_two_doc",
|
||||
b"cancel v2",
|
||||
)
|
||||
.await;
|
||||
install_revocation_gate(&sandbox).await;
|
||||
let gate = take_gate(&sandbox, REVOCATION_GATE_KEY).await;
|
||||
let cancelled = attributed_registry(&sandbox, "story38-revoker-cancelled").await;
|
||||
let cancelled_resource = other.clone();
|
||||
let waiting = tokio::spawn(async move {
|
||||
cancelled
|
||||
.revoke_resource(revoke_request(&cancelled_resource, "story38-cancelled"))
|
||||
.await
|
||||
});
|
||||
assert!(
|
||||
await_blocked_by(&sandbox.pool, "story38-revoker-cancelled", "story38-gate").await,
|
||||
"the cancelled revoke must be waiting inside its insert"
|
||||
);
|
||||
waiting.abort();
|
||||
let _ = waiting.await;
|
||||
release_gate(gate, REVOCATION_GATE_KEY).await;
|
||||
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(15),
|
||||
revoker.revoke_resource(revoke_request(&other, "story38-retry-after-cancel")),
|
||||
)
|
||||
.await
|
||||
.expect("the retry must not hang behind the cancelled command")
|
||||
.expect("the retry must succeed");
|
||||
let rows: i64 = sqlx::query_scalar(
|
||||
"select count(*) from resource_security_revocations where resource_id = $1",
|
||||
)
|
||||
.bind(other.as_str())
|
||||
.fetch_one(&sandbox.pool)
|
||||
.await
|
||||
.expect("tombstones must be queryable");
|
||||
assert_eq!(rows, 1, "a cancelled revoke must leave no event behind");
|
||||
sandbox.cleanup().await;
|
||||
}
|
||||
|
||||
/// A COMMIT that PostgreSQL itself refuses is a safe unavailable outcome: the read returns no
|
||||
/// prepared content, no tombstone is written, and a fresh read still works.
|
||||
#[tokio::test]
|
||||
async fn story38_read_guard_commit_failure_is_a_safe_unavailable() {
|
||||
let sandbox = sandbox("revocation_race_guard_commit").await;
|
||||
let resource = published_resource(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"res_race_guard_commit",
|
||||
"crank://race/guard-commit",
|
||||
b"guard commit v1",
|
||||
)
|
||||
.await;
|
||||
|
||||
let base_url = crank_test_support::postgres_database_url().await;
|
||||
let schema: String = sqlx::query_scalar("select current_schema()")
|
||||
.fetch_one(&sandbox.pool)
|
||||
.await
|
||||
.expect("the test schema must be resolvable");
|
||||
let url = format!(
|
||||
"{base_url}?options=-csearch_path%3D{schema}%20-capplication_name%3Dstory38-guard-commit"
|
||||
);
|
||||
let options = PgConnectOptions::from_str(&url).expect("guard connect options must parse");
|
||||
let registry = PostgresRegistry::connect_with_options_and_pool_config(
|
||||
options,
|
||||
PostgresPoolConfig {
|
||||
max_connections: 1,
|
||||
min_connections: 0,
|
||||
acquire_timeout_ms: 10_000,
|
||||
idle_timeout_ms: 600_000,
|
||||
max_lifetime_ms: 1_800_000,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("the single-connection guard registry must connect");
|
||||
|
||||
let guard = registry
|
||||
.begin_authorized_resource_read("ws_default", &resource, 1)
|
||||
.await
|
||||
.expect("the guard must open on an unrevoked Resource");
|
||||
let pids: Vec<i32> = sqlx::query_scalar(
|
||||
"select pid from pg_stat_activity
|
||||
where datname = current_database() and application_name = 'story38-guard-commit'",
|
||||
)
|
||||
.fetch_all(&sandbox.pool)
|
||||
.await
|
||||
.expect("the guard backend must be observable");
|
||||
assert_eq!(pids.len(), 1, "exactly one guard backend must exist");
|
||||
let terminated: bool = sqlx::query_scalar("select pg_terminate_backend($1)")
|
||||
.bind(pids[0])
|
||||
.fetch_one(&sandbox.pool)
|
||||
.await
|
||||
.expect("the guard backend must be terminable");
|
||||
assert!(terminated);
|
||||
|
||||
let outcome = guard.commit().await;
|
||||
assert!(
|
||||
matches!(outcome, Err(ResourceError::StorageUnavailable)),
|
||||
"a refused COMMIT must be a safe unavailable outcome, got {outcome:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
tombstone_rows(&sandbox.pool).await,
|
||||
0,
|
||||
"a failed read commit must not be recorded as a revoke"
|
||||
);
|
||||
|
||||
// Positive control on a fresh registry: nothing was revoked by the failed commit.
|
||||
let reader = attributed_registry(&sandbox, "story38-reader").await;
|
||||
let fresh = reader
|
||||
.begin_authorized_resource_read("ws_default", &resource, 1)
|
||||
.await
|
||||
.map(|_| ());
|
||||
assert!(
|
||||
fresh.is_ok(),
|
||||
"an unrevoked Resource must still open a guard after the failed commit: {fresh:?}"
|
||||
);
|
||||
sandbox.cleanup().await;
|
||||
}
|
||||
+538
@@ -0,0 +1,538 @@
|
||||
//! Story 3.8 / AT-3.8-04: real mutation races against the revoke transition (owner decision A).
|
||||
//!
|
||||
//! The binding save, the Agent publication and the Resource publication each run on their own
|
||||
//! multi-connection registry over one schema, against a real revoke on a different connection.
|
||||
//! A test-only advisory gate parks one side after it took its production locks; the barrier names
|
||||
//! the actual blocker (`pg_blocking_pids`) instead of guessing with sleeps.
|
||||
//!
|
||||
//! Every scenario asserts the final rows: no partial binding, no publication or catalog revision
|
||||
//! after a refused mutation, and a successful mutation that legally precedes the revoke is kept.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use crank_core::WorkspaceId;
|
||||
use crank_core::ids::ResourceId;
|
||||
use crank_core::resource::ResourceError;
|
||||
use crank_registry::model::resource::PublishResourceVersionRequest;
|
||||
use crank_registry::{
|
||||
AgentResourceBinding, PublishAgentRequest, RegistryError, SaveAgentCatalogConfigRequest,
|
||||
};
|
||||
use sqlx::Row;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use super::revocation_race::{
|
||||
REVOCATION_GATE_KEY, attributed_registry, await_blocked_by, install_advisory_gate,
|
||||
install_revocation_gate, release_gate, revoke_request, take_gate, tombstone_rows,
|
||||
};
|
||||
use super::*;
|
||||
|
||||
const BINDING_GATE_KEY: i64 = 3822;
|
||||
const AGENT_GATE_KEY: i64 = 3823;
|
||||
const PUBLICATION_GATE_KEY: i64 = 3824;
|
||||
|
||||
fn binding(resource: &ResourceId) -> AgentResourceBinding {
|
||||
AgentResourceBinding {
|
||||
resource_id: resource.clone(),
|
||||
resource_version: 1,
|
||||
}
|
||||
}
|
||||
|
||||
async fn save_bindings(
|
||||
registry: &crank_registry::PostgresRegistry,
|
||||
workspace: &str,
|
||||
agent: &crank_core::AgentId,
|
||||
resource: &ResourceId,
|
||||
) -> Result<(), RegistryError> {
|
||||
registry
|
||||
.save_agent_catalog_config(SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &WorkspaceId::new(workspace),
|
||||
agent_id: agent,
|
||||
agent_version: 1,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &Default::default(),
|
||||
resource_bindings: &[binding(resource)],
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
async fn publish_request(
|
||||
sandbox: &Sandbox,
|
||||
workspace: &str,
|
||||
resource: &ResourceId,
|
||||
bytes: &[u8],
|
||||
) -> PublishResourceVersionRequest {
|
||||
let current = sandbox
|
||||
.registry
|
||||
.get_resource_draft(workspace, resource)
|
||||
.await
|
||||
.expect("the draft must be readable before publishing");
|
||||
PublishResourceVersionRequest {
|
||||
workspace_id: WorkspaceId::new(workspace),
|
||||
resource_id: resource.clone(),
|
||||
expected_updated_at: current.resource.updated_at,
|
||||
expected_version: current.version.version,
|
||||
expected_digest: current.version.digest.clone(),
|
||||
expected_size_bytes: current.version.size_bytes,
|
||||
artifact: registered(sandbox, bytes),
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn publication_rows(pool: &sqlx::PgPool, resource: &ResourceId) -> i64 {
|
||||
sqlx::query_scalar("select count(*) from resource_publications where resource_id = $1")
|
||||
.bind(resource.as_str())
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.expect("publications must be queryable")
|
||||
}
|
||||
|
||||
async fn catalog_revision(pool: &sqlx::PgPool, agent: &crank_core::AgentId) -> i64 {
|
||||
sqlx::query_scalar("select catalog_revision from agents where id = $1")
|
||||
.bind(agent.as_str())
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.expect("the Agent must be readable")
|
||||
}
|
||||
|
||||
async fn published_versions(pool: &sqlx::PgPool, agent: &crank_core::AgentId) -> i64 {
|
||||
sqlx::query_scalar("select count(*) from published_agents where agent_id = $1")
|
||||
.bind(agent.as_str())
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.expect("published Agents must be queryable")
|
||||
}
|
||||
|
||||
/// Revoke-first refuses a binding that starts behind the revoke lock: no rows, no revision bump.
|
||||
#[tokio::test]
|
||||
async fn story38_revoke_first_refuses_a_waiting_binding_without_partial_writes() {
|
||||
let sandbox = sandbox("revocation_write_revoke_bind").await;
|
||||
let resource = published_resource(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"res_write_revoke_bind",
|
||||
"crank://race/revoke-bind",
|
||||
b"revoke bind v1",
|
||||
)
|
||||
.await;
|
||||
let agent = create_draft_agent(&sandbox, "ws_default", "agent_write_revoke_bind", "rb").await;
|
||||
let revision_before = catalog_revision(&sandbox.pool, &agent).await;
|
||||
|
||||
install_revocation_gate(&sandbox).await;
|
||||
let gate = take_gate(&sandbox, REVOCATION_GATE_KEY).await;
|
||||
let revoker = attributed_registry(&sandbox, "story38-revoker").await;
|
||||
let revoke_resource = resource.clone();
|
||||
let revoke = tokio::spawn(async move {
|
||||
revoker
|
||||
.revoke_resource(revoke_request(&revoke_resource, "story38-revoke-bind"))
|
||||
.await
|
||||
});
|
||||
assert!(
|
||||
await_blocked_by(&sandbox.pool, "story38-revoker", "story38-gate").await,
|
||||
"the revoke must hold the Resource row before the binding starts"
|
||||
);
|
||||
|
||||
let binder = attributed_registry(&sandbox, "story38-binder").await;
|
||||
let bind_agent = agent.clone();
|
||||
let bind_resource = resource.clone();
|
||||
let binding_write = tokio::spawn(async move {
|
||||
save_bindings(&binder, "ws_default", &bind_agent, &bind_resource).await
|
||||
});
|
||||
assert!(
|
||||
await_blocked_by(&sandbox.pool, "story38-binder", "story38-revoker").await,
|
||||
"the binding write must wait for the in-flight revoke"
|
||||
);
|
||||
|
||||
release_gate(gate, REVOCATION_GATE_KEY).await;
|
||||
tokio::time::timeout(Duration::from_secs(15), revoke)
|
||||
.await
|
||||
.expect("the revoke must finish")
|
||||
.expect("the revoke must not panic")
|
||||
.expect("the revoke must commit");
|
||||
let outcome = tokio::time::timeout(Duration::from_secs(15), binding_write)
|
||||
.await
|
||||
.expect("the binding must finish")
|
||||
.expect("the binding must not panic");
|
||||
assert!(
|
||||
matches!(outcome, Err(RegistryError::ResourceRevoked { .. })),
|
||||
"a binding behind a committed revoke must be refused: {outcome:?}"
|
||||
);
|
||||
assert_eq!(binding_rows(&sandbox, agent.as_str()).await, 0);
|
||||
assert_eq!(
|
||||
catalog_revision(&sandbox.pool, &agent).await,
|
||||
revision_before,
|
||||
"a refused binding must not move catalog_revision"
|
||||
);
|
||||
assert_eq!(tombstone_rows(&sandbox.pool).await, 1);
|
||||
sandbox.cleanup().await;
|
||||
}
|
||||
|
||||
/// Binding-first commits legally; the later revoke still wins for every live read.
|
||||
#[tokio::test]
|
||||
async fn story38_binding_first_serializes_before_a_later_revoke() {
|
||||
let sandbox = sandbox("revocation_write_bind_first").await;
|
||||
let resource = published_resource(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"res_write_bind_first",
|
||||
"crank://race/bind-first",
|
||||
b"bind first v1",
|
||||
)
|
||||
.await;
|
||||
let agent = create_draft_agent(&sandbox, "ws_default", "agent_write_bind_first", "bf").await;
|
||||
install_advisory_gate(
|
||||
&sandbox,
|
||||
"crank_test_gate_binding_insert",
|
||||
"agent_resource_bindings",
|
||||
BINDING_GATE_KEY,
|
||||
)
|
||||
.await;
|
||||
let gate = take_gate(&sandbox, BINDING_GATE_KEY).await;
|
||||
|
||||
let binder = attributed_registry(&sandbox, "story38-binder").await;
|
||||
let bind_agent = agent.clone();
|
||||
let bind_resource = resource.clone();
|
||||
let binding_write = tokio::spawn(async move {
|
||||
save_bindings(&binder, "ws_default", &bind_agent, &bind_resource).await
|
||||
});
|
||||
assert!(
|
||||
await_blocked_by(&sandbox.pool, "story38-binder", "story38-gate").await,
|
||||
"the binding transaction must park after taking its Resource locks"
|
||||
);
|
||||
|
||||
let revoker = attributed_registry(&sandbox, "story38-revoker").await;
|
||||
let revoke_resource = resource.clone();
|
||||
let revoke = tokio::spawn(async move {
|
||||
revoker
|
||||
.revoke_resource(revoke_request(&revoke_resource, "story38-bind-first"))
|
||||
.await
|
||||
});
|
||||
assert!(
|
||||
await_blocked_by(&sandbox.pool, "story38-revoker", "story38-binder").await,
|
||||
"the revoke must wait for the binding transaction that holds the Resource row"
|
||||
);
|
||||
|
||||
release_gate(gate, BINDING_GATE_KEY).await;
|
||||
tokio::time::timeout(Duration::from_secs(15), binding_write)
|
||||
.await
|
||||
.expect("the binding must finish")
|
||||
.expect("the binding must not panic")
|
||||
.expect("a binding that commits before the revoke must be accepted");
|
||||
tokio::time::timeout(Duration::from_secs(15), revoke)
|
||||
.await
|
||||
.expect("the revoke must finish")
|
||||
.expect("the revoke must not panic")
|
||||
.expect("the revoke must follow the committed binding");
|
||||
|
||||
assert_eq!(binding_rows(&sandbox, agent.as_str()).await, 1);
|
||||
assert_eq!(tombstone_rows(&sandbox.pool).await, 1);
|
||||
let reader = attributed_registry(&sandbox, "story38-reader").await;
|
||||
let denied = reader
|
||||
.begin_authorized_resource_read("ws_default", &resource, 1)
|
||||
.await
|
||||
.map(|_| ());
|
||||
assert!(
|
||||
matches!(denied, Err(ResourceError::Revoked)),
|
||||
"after the revoke the existing binding must not grant live reads: {denied:?}"
|
||||
);
|
||||
sandbox.cleanup().await;
|
||||
}
|
||||
|
||||
/// Revoke-first refuses an Agent publication whose bindings are already revoked.
|
||||
#[tokio::test]
|
||||
async fn story38_revoke_first_refuses_a_waiting_agent_publish() {
|
||||
let sandbox = sandbox("revocation_write_revoke_agent").await;
|
||||
let resource = published_resource(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"res_write_revoke_agent",
|
||||
"crank://race/revoke-agent",
|
||||
b"revoke agent v1",
|
||||
)
|
||||
.await;
|
||||
let agent = create_draft_agent(&sandbox, "ws_default", "agent_write_revoke_agent", "ra").await;
|
||||
save_bindings(&sandbox.registry, "ws_default", &agent, &resource)
|
||||
.await
|
||||
.expect("the draft binding must save before the revoke");
|
||||
let revision_before = catalog_revision(&sandbox.pool, &agent).await;
|
||||
|
||||
install_revocation_gate(&sandbox).await;
|
||||
let gate = take_gate(&sandbox, REVOCATION_GATE_KEY).await;
|
||||
let revoker = attributed_registry(&sandbox, "story38-revoker").await;
|
||||
let revoke_resource = resource.clone();
|
||||
let revoke = tokio::spawn(async move {
|
||||
revoker
|
||||
.revoke_resource(revoke_request(&revoke_resource, "story38-revoke-agent"))
|
||||
.await
|
||||
});
|
||||
assert!(
|
||||
await_blocked_by(&sandbox.pool, "story38-revoker", "story38-gate").await,
|
||||
"the revoke must hold the Resource row before the Agent publish starts"
|
||||
);
|
||||
|
||||
let publisher = attributed_registry(&sandbox, "story38-agent-publish").await;
|
||||
let publish_agent = agent.clone();
|
||||
let published_at = OffsetDateTime::now_utc();
|
||||
let publish = tokio::spawn(async move {
|
||||
publisher
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &WorkspaceId::new("ws_default"),
|
||||
agent_id: &publish_agent,
|
||||
version: 1,
|
||||
published_at: &published_at,
|
||||
published_by: None,
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
});
|
||||
assert!(
|
||||
await_blocked_by(&sandbox.pool, "story38-agent-publish", "story38-revoker").await,
|
||||
"the Agent publication must wait for the in-flight revoke"
|
||||
);
|
||||
|
||||
release_gate(gate, REVOCATION_GATE_KEY).await;
|
||||
tokio::time::timeout(Duration::from_secs(15), revoke)
|
||||
.await
|
||||
.expect("the revoke must finish")
|
||||
.expect("the revoke must not panic")
|
||||
.expect("the revoke must commit");
|
||||
let outcome = tokio::time::timeout(Duration::from_secs(15), publish)
|
||||
.await
|
||||
.expect("the Agent publish must finish")
|
||||
.expect("the Agent publish must not panic");
|
||||
assert!(
|
||||
matches!(outcome, Err(RegistryError::ResourceRevoked { .. })),
|
||||
"publishing an Agent bound to a revoked Resource must be refused: {outcome:?}"
|
||||
);
|
||||
assert_eq!(published_versions(&sandbox.pool, &agent).await, 0);
|
||||
assert_eq!(
|
||||
catalog_revision(&sandbox.pool, &agent).await,
|
||||
revision_before,
|
||||
"a refused Agent publication must not bump catalog_revision"
|
||||
);
|
||||
sandbox.cleanup().await;
|
||||
}
|
||||
|
||||
/// Agent publish first: it holds the shared Resource lock, the revoke waits and follows; every
|
||||
/// read after the revoke is denied, and no deadlock appears in the Agent → Resource order.
|
||||
#[tokio::test]
|
||||
async fn story38_agent_publish_first_serializes_before_a_later_revoke() {
|
||||
let sandbox = sandbox("revocation_write_agent_first").await;
|
||||
let resource = published_resource(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"res_write_agent_first",
|
||||
"crank://race/agent-first",
|
||||
b"agent first v1",
|
||||
)
|
||||
.await;
|
||||
let agent = create_draft_agent(&sandbox, "ws_default", "agent_write_agent_first", "af").await;
|
||||
save_bindings(&sandbox.registry, "ws_default", &agent, &resource)
|
||||
.await
|
||||
.expect("the draft binding must save before publishing");
|
||||
install_advisory_gate(
|
||||
&sandbox,
|
||||
"crank_test_gate_agent_update",
|
||||
"agents",
|
||||
AGENT_GATE_KEY,
|
||||
)
|
||||
.await;
|
||||
let gate = take_gate(&sandbox, AGENT_GATE_KEY).await;
|
||||
|
||||
let publisher = attributed_registry(&sandbox, "story38-agent-publish").await;
|
||||
let publish_agent = agent.clone();
|
||||
let published_at = OffsetDateTime::now_utc();
|
||||
let publish = tokio::spawn(async move {
|
||||
publisher
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &WorkspaceId::new("ws_default"),
|
||||
agent_id: &publish_agent,
|
||||
version: 1,
|
||||
published_at: &published_at,
|
||||
published_by: None,
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
});
|
||||
assert!(
|
||||
await_blocked_by(&sandbox.pool, "story38-agent-publish", "story38-gate").await,
|
||||
"the Agent publish must park after taking the shared Resource lock"
|
||||
);
|
||||
|
||||
let revoker = attributed_registry(&sandbox, "story38-revoker").await;
|
||||
let revoke_resource = resource.clone();
|
||||
let revoke = tokio::spawn(async move {
|
||||
revoker
|
||||
.revoke_resource(revoke_request(&revoke_resource, "story38-agent-first"))
|
||||
.await
|
||||
});
|
||||
assert!(
|
||||
await_blocked_by(&sandbox.pool, "story38-revoker", "story38-agent-publish").await,
|
||||
"the revoke must wait for the Agent publication that holds the shared Resource lock"
|
||||
);
|
||||
|
||||
release_gate(gate, AGENT_GATE_KEY).await;
|
||||
tokio::time::timeout(Duration::from_secs(15), publish)
|
||||
.await
|
||||
.expect("the Agent publish must finish")
|
||||
.expect("the Agent publish must not panic")
|
||||
.expect("the Agent publication must commit before the revoke");
|
||||
tokio::time::timeout(Duration::from_secs(15), revoke)
|
||||
.await
|
||||
.expect("the revoke must finish")
|
||||
.expect("the revoke must not panic")
|
||||
.expect("the revoke must follow the Agent publication");
|
||||
|
||||
assert_eq!(published_versions(&sandbox.pool, &agent).await, 1);
|
||||
assert_eq!(catalog_revision(&sandbox.pool, &agent).await, 1);
|
||||
assert_eq!(tombstone_rows(&sandbox.pool).await, 1);
|
||||
let reader = attributed_registry(&sandbox, "story38-reader").await;
|
||||
let denied = reader
|
||||
.begin_authorized_resource_read("ws_default", &resource, 1)
|
||||
.await
|
||||
.map(|_| ());
|
||||
assert!(
|
||||
matches!(denied, Err(ResourceError::Revoked)),
|
||||
"the Agent snapshot published before the revoke must not stay readable: {denied:?}"
|
||||
);
|
||||
sandbox.cleanup().await;
|
||||
}
|
||||
|
||||
/// Revoke-first refuses a waiting Resource publication and leaves no publication row.
|
||||
#[tokio::test]
|
||||
async fn story38_revoke_first_refuses_a_waiting_resource_publish() {
|
||||
let sandbox = sandbox("revocation_write_revoke_publish").await;
|
||||
let resource = published_resource(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"res_write_revoke_publish",
|
||||
"crank://race/revoke-publish",
|
||||
b"revoke publish v1",
|
||||
)
|
||||
.await;
|
||||
draft_next_resource_version(&sandbox, "ws_default", &resource, b"revoke publish v2").await;
|
||||
let request = publish_request(&sandbox, "ws_default", &resource, b"revoke publish v2").await;
|
||||
|
||||
install_revocation_gate(&sandbox).await;
|
||||
let gate = take_gate(&sandbox, REVOCATION_GATE_KEY).await;
|
||||
let revoker = attributed_registry(&sandbox, "story38-revoker").await;
|
||||
let revoke_resource = resource.clone();
|
||||
let revoke = tokio::spawn(async move {
|
||||
revoker
|
||||
.revoke_resource(revoke_request(&revoke_resource, "story38-revoke-publish"))
|
||||
.await
|
||||
});
|
||||
assert!(
|
||||
await_blocked_by(&sandbox.pool, "story38-revoker", "story38-gate").await,
|
||||
"the revoke must hold the Resource row before the publication starts"
|
||||
);
|
||||
|
||||
let publisher = attributed_registry(&sandbox, "story38-resource-publish").await;
|
||||
let publish = tokio::spawn(async move { publisher.publish_resource_version(request).await });
|
||||
assert!(
|
||||
await_blocked_by(&sandbox.pool, "story38-resource-publish", "story38-revoker").await,
|
||||
"the Resource publication must wait for the in-flight revoke"
|
||||
);
|
||||
|
||||
release_gate(gate, REVOCATION_GATE_KEY).await;
|
||||
tokio::time::timeout(Duration::from_secs(15), revoke)
|
||||
.await
|
||||
.expect("the revoke must finish")
|
||||
.expect("the revoke must not panic")
|
||||
.expect("the revoke must commit");
|
||||
let outcome = tokio::time::timeout(Duration::from_secs(15), publish)
|
||||
.await
|
||||
.expect("the publication must finish")
|
||||
.expect("the publication must not panic");
|
||||
assert!(
|
||||
matches!(outcome, Err(ResourceError::Revoked)),
|
||||
"a publication behind a committed revoke must be refused: {outcome:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
publication_rows(&sandbox.pool, &resource).await,
|
||||
1,
|
||||
"a refused publication must not add an immutable version"
|
||||
);
|
||||
sandbox.cleanup().await;
|
||||
}
|
||||
|
||||
/// Resource publish first: the immutable version commits, the revoke follows and closes it.
|
||||
#[tokio::test]
|
||||
async fn story38_resource_publish_first_serializes_before_a_later_revoke() {
|
||||
let sandbox = sandbox("revocation_write_publish_first").await;
|
||||
let resource = published_resource(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"res_write_publish_first",
|
||||
"crank://race/publish-first",
|
||||
b"publish first v1",
|
||||
)
|
||||
.await;
|
||||
draft_next_resource_version(&sandbox, "ws_default", &resource, b"publish first v2").await;
|
||||
let request = publish_request(&sandbox, "ws_default", &resource, b"publish first v2").await;
|
||||
install_advisory_gate(
|
||||
&sandbox,
|
||||
"crank_test_gate_resource_publication",
|
||||
"resource_publications",
|
||||
PUBLICATION_GATE_KEY,
|
||||
)
|
||||
.await;
|
||||
let gate = take_gate(&sandbox, PUBLICATION_GATE_KEY).await;
|
||||
|
||||
let publisher = attributed_registry(&sandbox, "story38-resource-publish").await;
|
||||
let publish = tokio::spawn(async move { publisher.publish_resource_version(request).await });
|
||||
assert!(
|
||||
await_blocked_by(&sandbox.pool, "story38-resource-publish", "story38-gate").await,
|
||||
"the publication must park after locking the Resource row"
|
||||
);
|
||||
|
||||
let revoker = attributed_registry(&sandbox, "story38-revoker").await;
|
||||
let revoke_resource = resource.clone();
|
||||
let revoke = tokio::spawn(async move {
|
||||
revoker
|
||||
.revoke_resource(revoke_request(&revoke_resource, "story38-publish-first"))
|
||||
.await
|
||||
});
|
||||
assert!(
|
||||
await_blocked_by(&sandbox.pool, "story38-revoker", "story38-resource-publish").await,
|
||||
"the revoke must wait for the publication that holds the Resource row"
|
||||
);
|
||||
|
||||
release_gate(gate, PUBLICATION_GATE_KEY).await;
|
||||
tokio::time::timeout(Duration::from_secs(15), publish)
|
||||
.await
|
||||
.expect("the publication must finish")
|
||||
.expect("the publication must not panic")
|
||||
.expect("the publication must commit before the revoke");
|
||||
tokio::time::timeout(Duration::from_secs(15), revoke)
|
||||
.await
|
||||
.expect("the revoke must finish")
|
||||
.expect("the revoke must not panic")
|
||||
.expect("the revoke must follow the committed publication");
|
||||
|
||||
assert_eq!(publication_rows(&sandbox.pool, &resource).await, 2);
|
||||
assert_eq!(tombstone_rows(&sandbox.pool).await, 1);
|
||||
let reader = attributed_registry(&sandbox, "story38-reader").await;
|
||||
let denied = reader
|
||||
.begin_authorized_resource_read("ws_default", &resource, 2)
|
||||
.await
|
||||
.map(|_| ());
|
||||
assert!(
|
||||
matches!(denied, Err(ResourceError::Revoked)),
|
||||
"the version published before the revoke must not stay readable: {denied:?}"
|
||||
);
|
||||
// The immutable snapshot itself is untouched (only live access is closed).
|
||||
let snapshot = sandbox
|
||||
.registry
|
||||
.resolve_resource_publication("ws_default", &resource, 2)
|
||||
.await
|
||||
.expect("the immutable publication must stay resolvable for the raw Admin path");
|
||||
assert_eq!(snapshot.publication.version, 2);
|
||||
let row = sqlx::query("select count(*) from resource_publications where resource_id = $1")
|
||||
.bind(resource.as_str())
|
||||
.fetch_one(&sandbox.pool)
|
||||
.await
|
||||
.expect("publications must be queryable");
|
||||
assert_eq!(row.try_get::<i64, _>(0).unwrap(), 2);
|
||||
sandbox.cleanup().await;
|
||||
}
|
||||
@@ -0,0 +1,702 @@
|
||||
//! Story 3.7 / AC04 regression: fault-after-write rollback и concurrent
|
||||
//! published-catalog old-or-new (TL review F3).
|
||||
//!
|
||||
//! Проверяется на реальном PostgreSQL:
|
||||
//! - поздний сбой publication после уже выполненных в транзакции записей
|
||||
//! откатывает status/bindings/pointer/revision и не оставляет partial rows;
|
||||
//! - сбой editable fork после частичной работы не оставляет orphan version,
|
||||
//! bindings или сдвига pointer/revision;
|
||||
//! - bounded concurrent reader/republish видит целостный tuple
|
||||
//! (agent_version/resources/catalog_revision/tools) старого ИЛИ нового snapshot,
|
||||
//! никогда смешанный.
|
||||
//!
|
||||
//! Harness не создаётся: используются существующие sandbox/fixtures и test-only
|
||||
//! триггеры в приватной тестовой схеме.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use crank_core::{AgentOperationBinding, OperationStatus, WorkspaceId};
|
||||
use crank_registry::{
|
||||
CreateVersionRequest, PublishAgentRequest, PublishRequest, RegistryError,
|
||||
SaveAgentCatalogConfigRequest,
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Поздний сбой publication: триггер срабатывает на финальном `update agents`,
|
||||
/// когда `agent_versions.status` и `published_agents` в этой же транзакции уже
|
||||
/// изменены. Так проверяется именно rollback после частичной работы, а не
|
||||
/// precheck (stale expected_state отказывает до любых записей).
|
||||
async fn install_publication_fault(pool: &sqlx::PgPool) {
|
||||
sqlx::raw_sql(
|
||||
"create function crank_test_fail_publication_after_writes()
|
||||
returns trigger language plpgsql as $$
|
||||
begin
|
||||
if new.latest_published_version is not null then
|
||||
raise exception 'injected publication failure after earlier writes'
|
||||
using errcode = '23514';
|
||||
end if;
|
||||
return new;
|
||||
end;
|
||||
$$;
|
||||
create trigger crank_test_fail_publication_after_writes_guard
|
||||
before update on agents
|
||||
for each row execute function crank_test_fail_publication_after_writes();",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.expect("the test-only publication fault trigger must install");
|
||||
}
|
||||
|
||||
async fn remove_publication_fault(pool: &sqlx::PgPool) {
|
||||
sqlx::raw_sql(
|
||||
"drop trigger crank_test_fail_publication_after_writes_guard on agents;
|
||||
drop function crank_test_fail_publication_after_writes();",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.expect("the test-only publication fault trigger must be removable");
|
||||
}
|
||||
|
||||
/// Поздний сбой editable fork: версия, operation bindings и первая Resource
|
||||
/// binding уже вставлены; падает вставка второй Resource binding
|
||||
/// (`res_v18_fork_fault_b` этой fixture), поэтому проверяется откат уже
|
||||
/// записанных строк, а не пустой транзакции.
|
||||
async fn install_binding_write_fault(pool: &sqlx::PgPool) {
|
||||
sqlx::raw_sql(
|
||||
"create function crank_test_fail_binding_write()
|
||||
returns trigger language plpgsql as $$
|
||||
begin
|
||||
if new.resource_id = 'res_v18_fork_fault_b' then
|
||||
raise exception 'injected binding write failure after fork writes'
|
||||
using errcode = '23514';
|
||||
end if;
|
||||
return new;
|
||||
end;
|
||||
$$;
|
||||
create trigger crank_test_fail_binding_write_guard
|
||||
before insert on agent_resource_bindings
|
||||
for each row execute function crank_test_fail_binding_write();",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.expect("the test-only binding-write fault trigger must install");
|
||||
}
|
||||
|
||||
async fn remove_binding_write_fault(pool: &sqlx::PgPool) {
|
||||
sqlx::raw_sql(
|
||||
"drop trigger crank_test_fail_binding_write_guard on agent_resource_bindings;
|
||||
drop function crank_test_fail_binding_write();",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.expect("the test-only binding-write fault trigger must be removable");
|
||||
}
|
||||
|
||||
/// Второй опубликованный Resource того же workspace: имя draft-а уникально
|
||||
/// внутри workspace, поэтому fixture задаёт своё.
|
||||
async fn published_resource_named(
|
||||
sandbox: &Sandbox,
|
||||
resource_id: &str,
|
||||
uri: &str,
|
||||
name: &str,
|
||||
bytes: &[u8],
|
||||
) -> ResourceId {
|
||||
let id = ResourceId::new(resource_id);
|
||||
sandbox
|
||||
.registry
|
||||
.create_resource_draft(CreateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new("ws_default"),
|
||||
resource_id: id.clone(),
|
||||
uri: uri.to_owned(),
|
||||
name: name.to_owned(),
|
||||
description: String::new(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
artifact: registered(sandbox, bytes),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("named resource draft must be created");
|
||||
publish_current_resource(sandbox, "ws_default", &id, bytes).await;
|
||||
id
|
||||
}
|
||||
|
||||
async fn version_count(pool: &sqlx::PgPool, agent_id: &str) -> i64 {
|
||||
sqlx::query_scalar("select count(*) from agent_versions where agent_id = $1")
|
||||
.bind(agent_id)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.expect("agent versions must be queryable")
|
||||
}
|
||||
|
||||
async fn operation_binding_count(pool: &sqlx::PgPool, agent_id: &str, version: i32) -> i64 {
|
||||
sqlx::query_scalar(
|
||||
"select count(*) from agent_operation_bindings
|
||||
where agent_id = $1 and agent_version = $2",
|
||||
)
|
||||
.bind(agent_id)
|
||||
.bind(version)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.expect("operation bindings must be queryable")
|
||||
}
|
||||
|
||||
async fn resource_rows(pool: &sqlx::PgPool, agent_id: &str, version: i32) -> i64 {
|
||||
sqlx::query_scalar(
|
||||
"select count(*) from agent_resource_bindings
|
||||
where agent_id = $1 and agent_version = $2",
|
||||
)
|
||||
.bind(agent_id)
|
||||
.bind(version)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.expect("resource bindings must be queryable")
|
||||
}
|
||||
|
||||
async fn publish_agent_version(
|
||||
sandbox: &Sandbox,
|
||||
agent: &crank_core::AgentId,
|
||||
version: u32,
|
||||
) -> Result<(), RegistryError> {
|
||||
sandbox
|
||||
.registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &WorkspaceId::new("ws_default"),
|
||||
agent_id: agent,
|
||||
version,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: None,
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
async fn catalog_of(sandbox: &Sandbox, slug: &str) -> crank_registry::PublishedAgentCatalog {
|
||||
sandbox
|
||||
.registry
|
||||
.get_published_agent_catalog_by_slug("default", slug)
|
||||
.await
|
||||
.expect("published catalog must be readable")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story37_v18_publication_failure_after_writes_rolls_back_atomically() {
|
||||
let sandbox = sandbox("v18_publish_fault").await;
|
||||
let resource = published_resource(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"res_v18_publish_fault",
|
||||
"crank://v18/publish-fault",
|
||||
b"publish fault v1",
|
||||
)
|
||||
.await;
|
||||
let agent =
|
||||
create_draft_agent(&sandbox, "ws_default", "agent_v18_publish_fault", "v18-pf").await;
|
||||
save_resource_bindings(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
&agent,
|
||||
&[AgentResourceBinding {
|
||||
resource_id: resource.clone(),
|
||||
resource_version: 1,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
.expect("draft binding must be saved");
|
||||
let before = sandbox
|
||||
.registry
|
||||
.get_agent_summary(&WorkspaceId::new("ws_default"), &agent)
|
||||
.await
|
||||
.expect("summary must be readable")
|
||||
.expect("summary must exist");
|
||||
|
||||
install_publication_fault(&sandbox.pool).await;
|
||||
let failed = publish_agent_version(&sandbox, &agent, 1)
|
||||
.await
|
||||
.expect_err("the injected late failure must abort the publication");
|
||||
assert!(
|
||||
matches!(failed, RegistryError::Storage(_)),
|
||||
"a database failure after writes must surface as a storage error: {failed}"
|
||||
);
|
||||
remove_publication_fault(&sandbox.pool).await;
|
||||
|
||||
// Всё, что транзакция успела записать до сбоя, обязано откатиться.
|
||||
let version = sandbox
|
||||
.registry
|
||||
.get_agent_version(&WorkspaceId::new("ws_default"), &agent, 1)
|
||||
.await
|
||||
.expect("agent version must be readable")
|
||||
.expect("agent version must exist");
|
||||
assert_eq!(
|
||||
version.status,
|
||||
AgentStatus::Draft,
|
||||
"a rolled-back publication must not leave the version published"
|
||||
);
|
||||
assert_eq!(
|
||||
version.resource_bindings,
|
||||
vec![AgentResourceBinding {
|
||||
resource_id: resource.clone(),
|
||||
resource_version: 1
|
||||
}],
|
||||
"draft exact bindings must survive the rollback"
|
||||
);
|
||||
let after = sandbox
|
||||
.registry
|
||||
.get_agent_summary(&WorkspaceId::new("ws_default"), &agent)
|
||||
.await
|
||||
.expect("summary must be readable")
|
||||
.expect("summary must exist");
|
||||
assert_eq!(after.status, AgentStatus::Draft);
|
||||
assert_eq!(after.latest_published_version, None);
|
||||
assert_eq!(
|
||||
after.catalog_revision, before.catalog_revision,
|
||||
"a rolled-back publication must not bump catalog_revision"
|
||||
);
|
||||
let pointer_rows: i64 =
|
||||
sqlx::query_scalar("select count(*) from published_agents where agent_id = $1")
|
||||
.bind(agent.as_str())
|
||||
.fetch_one(&sandbox.pool)
|
||||
.await
|
||||
.expect("published pointer must be queryable");
|
||||
assert_eq!(pointer_rows, 0, "a failed publish must not write a pointer");
|
||||
assert_eq!(resource_rows(&sandbox.pool, agent.as_str(), 1).await, 1);
|
||||
assert_eq!(binding_rows(&sandbox, agent.as_str()).await, 1);
|
||||
|
||||
// Positive control: без fault та же публикация проходит и двигает pointer/revision.
|
||||
publish_agent_version(&sandbox, &agent, 1)
|
||||
.await
|
||||
.expect("publication must succeed once the fault is removed");
|
||||
let published = sandbox
|
||||
.registry
|
||||
.get_agent_summary(&WorkspaceId::new("ws_default"), &agent)
|
||||
.await
|
||||
.expect("summary must be readable")
|
||||
.expect("summary must exist");
|
||||
assert_eq!(published.status, AgentStatus::Published);
|
||||
assert_eq!(published.latest_published_version, Some(1));
|
||||
assert_eq!(
|
||||
published.catalog_revision,
|
||||
before.catalog_revision + 1,
|
||||
"publication must raise catalog_revision by exactly one"
|
||||
);
|
||||
let catalog = catalog_of(&sandbox, "v18-pf").await;
|
||||
assert_eq!(catalog.agent_version, 1);
|
||||
assert_eq!(
|
||||
catalog.resources,
|
||||
vec![AgentResourceBinding {
|
||||
resource_id: resource,
|
||||
resource_version: 1
|
||||
}]
|
||||
);
|
||||
sandbox.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story37_v18_editable_fork_failure_leaves_no_partial_version() {
|
||||
let sandbox = sandbox("v18_fork_fault").await;
|
||||
let resource = published_resource(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"res_v18_fork_fault",
|
||||
"crank://v18/fork-fault",
|
||||
b"fork fault v1",
|
||||
)
|
||||
.await;
|
||||
let second = published_resource_named(
|
||||
&sandbox,
|
||||
"res_v18_fork_fault_b",
|
||||
"crank://v18/fork-fault-b",
|
||||
"binding_doc_b",
|
||||
b"fork fault second v1",
|
||||
)
|
||||
.await;
|
||||
let agent = create_draft_agent(&sandbox, "ws_default", "agent_v18_fork_fault", "v18-ff").await;
|
||||
// Существующий опубликованный Tool binding: fork обязан успеть его записать.
|
||||
let operation_binding = published_operation_binding(&sandbox).await;
|
||||
let bindings = vec![operation_binding.clone()];
|
||||
sandbox
|
||||
.registry
|
||||
.save_agent_catalog_config(SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &WorkspaceId::new("ws_default"),
|
||||
agent_id: &agent,
|
||||
agent_version: 1,
|
||||
bindings: &bindings,
|
||||
tool_selection_policy: &Default::default(),
|
||||
resource_bindings: &[
|
||||
AgentResourceBinding {
|
||||
resource_id: resource.clone(),
|
||||
resource_version: 1,
|
||||
},
|
||||
AgentResourceBinding {
|
||||
resource_id: second.clone(),
|
||||
resource_version: 1,
|
||||
},
|
||||
],
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("v1 config with a published Tool and two exact Resources must save");
|
||||
publish_agent_version(&sandbox, &agent, 1)
|
||||
.await
|
||||
.expect("Agent v1 must publish");
|
||||
draft_next_resource_version(&sandbox, "ws_default", &resource, b"fork fault v2").await;
|
||||
assert_eq!(
|
||||
publish_current_resource(&sandbox, "ws_default", &resource, b"fork fault v2").await,
|
||||
2,
|
||||
"exact Resource v2 must be available for the fork"
|
||||
);
|
||||
let before = sandbox
|
||||
.registry
|
||||
.get_agent_summary(&WorkspaceId::new("ws_default"), &agent)
|
||||
.await
|
||||
.expect("summary must be readable")
|
||||
.expect("summary must exist");
|
||||
let catalog_before = catalog_of(&sandbox, "v18-ff").await;
|
||||
|
||||
install_binding_write_fault(&sandbox.pool).await;
|
||||
let failed = sandbox
|
||||
.registry
|
||||
.save_agent_catalog_config_editable(SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &WorkspaceId::new("ws_default"),
|
||||
agent_id: &agent,
|
||||
agent_version: 1,
|
||||
bindings: &bindings,
|
||||
tool_selection_policy: &Default::default(),
|
||||
resource_bindings: &[
|
||||
AgentResourceBinding {
|
||||
resource_id: resource.clone(),
|
||||
resource_version: 2,
|
||||
},
|
||||
AgentResourceBinding {
|
||||
resource_id: second.clone(),
|
||||
resource_version: 1,
|
||||
},
|
||||
],
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect_err("the injected fork failure must abort the editable save");
|
||||
assert!(
|
||||
matches!(failed, RegistryError::Storage(_)),
|
||||
"a database failure after fork writes must surface as a storage error: {failed}"
|
||||
);
|
||||
remove_binding_write_fault(&sandbox.pool).await;
|
||||
|
||||
// Partial work editable fork не должна пережить откат.
|
||||
assert_eq!(
|
||||
version_count(&sandbox.pool, agent.as_str()).await,
|
||||
1,
|
||||
"a failed fork must not leave an orphan Agent version"
|
||||
);
|
||||
assert_eq!(
|
||||
operation_binding_count(&sandbox.pool, agent.as_str(), 2).await,
|
||||
0,
|
||||
"a failed fork must not leave partial operation bindings"
|
||||
);
|
||||
assert_eq!(
|
||||
resource_rows(&sandbox.pool, agent.as_str(), 2).await,
|
||||
0,
|
||||
"a failed fork must not leave partial resource bindings"
|
||||
);
|
||||
// До сбоя транзакция успела записать Tool binding и первую Resource binding:
|
||||
// обе обязаны исчезнуть вместе с версией 2, а snapshot v1 — остаться целым.
|
||||
assert_eq!(
|
||||
operation_binding_count(&sandbox.pool, agent.as_str(), 1).await,
|
||||
1,
|
||||
"the published v1 Tool binding must survive the rollback"
|
||||
);
|
||||
assert_eq!(
|
||||
resource_rows(&sandbox.pool, agent.as_str(), 1).await,
|
||||
2,
|
||||
"the published v1 Resource bindings must survive the rollback"
|
||||
);
|
||||
let after = sandbox
|
||||
.registry
|
||||
.get_agent_summary(&WorkspaceId::new("ws_default"), &agent)
|
||||
.await
|
||||
.expect("summary must be readable")
|
||||
.expect("summary must exist");
|
||||
assert_eq!(after.current_draft_version, 1);
|
||||
assert_eq!(after.latest_published_version, Some(1));
|
||||
assert_eq!(after.catalog_revision, before.catalog_revision);
|
||||
assert_eq!(
|
||||
after.updated_at, before.updated_at,
|
||||
"a failed fork must not move the Agent updated_at"
|
||||
);
|
||||
assert_eq!(catalog_of(&sandbox, "v18-ff").await, catalog_before);
|
||||
|
||||
// Positive control: без fault тот же editable fork создаёт v2 и публикует новый snapshot.
|
||||
let forked = sandbox
|
||||
.registry
|
||||
.save_agent_catalog_config_editable(SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &WorkspaceId::new("ws_default"),
|
||||
agent_id: &agent,
|
||||
agent_version: 1,
|
||||
bindings: &bindings,
|
||||
tool_selection_policy: &Default::default(),
|
||||
resource_bindings: &[
|
||||
AgentResourceBinding {
|
||||
resource_id: resource.clone(),
|
||||
resource_version: 2,
|
||||
},
|
||||
AgentResourceBinding {
|
||||
resource_id: second.clone(),
|
||||
resource_version: 1,
|
||||
},
|
||||
],
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("the editable fork must succeed once the fault is removed");
|
||||
assert_eq!(forked, 2);
|
||||
assert_eq!(
|
||||
operation_binding_count(&sandbox.pool, agent.as_str(), 2).await,
|
||||
1,
|
||||
"the successful fork must persist the Tool binding that precedes the faulted Resource write"
|
||||
);
|
||||
assert_eq!(
|
||||
resource_rows(&sandbox.pool, agent.as_str(), 2).await,
|
||||
2,
|
||||
"the successful fork must persist both exact Resource bindings"
|
||||
);
|
||||
publish_agent_version(&sandbox, &agent, 2)
|
||||
.await
|
||||
.expect("Agent v2 must publish");
|
||||
let catalog = catalog_of(&sandbox, "v18-ff").await;
|
||||
assert_eq!(catalog.agent_version, 2);
|
||||
assert_eq!(
|
||||
catalog.resources,
|
||||
vec![
|
||||
AgentResourceBinding {
|
||||
resource_id: resource.clone(),
|
||||
resource_version: 2
|
||||
},
|
||||
AgentResourceBinding {
|
||||
resource_id: second.clone(),
|
||||
resource_version: 1
|
||||
}
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
catalog.tools.len(),
|
||||
1,
|
||||
"the republished snapshot must keep its Tool binding"
|
||||
);
|
||||
let still_v1 = sandbox
|
||||
.registry
|
||||
.get_agent_version(&WorkspaceId::new("ws_default"), &agent, 1)
|
||||
.await
|
||||
.expect("agent version must be readable")
|
||||
.expect("agent version must exist");
|
||||
assert_eq!(
|
||||
still_v1.resource_bindings,
|
||||
vec![
|
||||
AgentResourceBinding {
|
||||
resource_id: resource,
|
||||
resource_version: 1
|
||||
},
|
||||
AgentResourceBinding {
|
||||
resource_id: second,
|
||||
resource_version: 1
|
||||
}
|
||||
]
|
||||
);
|
||||
sandbox.cleanup().await;
|
||||
}
|
||||
|
||||
type CatalogTuple = (
|
||||
u32,
|
||||
String,
|
||||
Vec<AgentResourceBinding>,
|
||||
Vec<(String, String, u32)>,
|
||||
);
|
||||
|
||||
fn catalog_tuple(catalog: &crank_registry::PublishedAgentCatalog) -> CatalogTuple {
|
||||
(
|
||||
catalog.agent_version,
|
||||
catalog.catalog_revision.clone(),
|
||||
catalog.resources.clone(),
|
||||
catalog
|
||||
.tools
|
||||
.iter()
|
||||
.map(|tool| {
|
||||
(
|
||||
tool.tool_name.clone(),
|
||||
tool.operation.id.as_str().to_owned(),
|
||||
tool.operation.version,
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Публикует Operation v2 и возвращает binding, чтобы published catalog содержал
|
||||
/// непустой `tools` рядом с resources.
|
||||
async fn published_operation_binding(sandbox: &Sandbox) -> AgentOperationBinding {
|
||||
let operation = test_operation("op_v18_concurrent", 1, OperationStatus::Draft);
|
||||
sandbox
|
||||
.registry
|
||||
.create_operation(&WorkspaceId::new("ws_default"), &operation, None)
|
||||
.await
|
||||
.expect("operation draft must be created");
|
||||
let operation_v2 = test_operation("op_v18_concurrent", 2, OperationStatus::Draft);
|
||||
sandbox
|
||||
.registry
|
||||
.create_version(CreateVersionRequest {
|
||||
workspace_id: &WorkspaceId::new("ws_default"),
|
||||
snapshot: &operation_v2,
|
||||
change_note: Some("v18 concurrent fixture"),
|
||||
created_by: None,
|
||||
})
|
||||
.await
|
||||
.expect("operation version must be created");
|
||||
sandbox
|
||||
.registry
|
||||
.publish_operation(PublishRequest {
|
||||
workspace_id: &WorkspaceId::new("ws_default"),
|
||||
operation_id: &operation.id,
|
||||
version: 2,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: None,
|
||||
})
|
||||
.await
|
||||
.expect("operation v2 must publish");
|
||||
AgentOperationBinding {
|
||||
operation_id: operation.id,
|
||||
operation_version: 2,
|
||||
tool_name: "v18_concurrent_tool".to_owned(),
|
||||
tool_title: "V18 concurrent tool".to_owned(),
|
||||
tool_description_override: None,
|
||||
enabled: true,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story37_v18_concurrent_catalog_read_sees_old_or_new_tuple_never_mixed() {
|
||||
let sandbox = sandbox("v18_catalog_concurrent").await;
|
||||
let resource = published_resource(
|
||||
&sandbox,
|
||||
"ws_default",
|
||||
"res_v18_concurrent",
|
||||
"crank://v18/concurrent",
|
||||
b"concurrent v1",
|
||||
)
|
||||
.await;
|
||||
let agent = create_draft_agent(&sandbox, "ws_default", "agent_v18_concurrent", "v18-cc").await;
|
||||
let operation_binding = published_operation_binding(&sandbox).await;
|
||||
let bindings = vec![operation_binding.clone()];
|
||||
sandbox
|
||||
.registry
|
||||
.save_agent_catalog_config(SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &WorkspaceId::new("ws_default"),
|
||||
agent_id: &agent,
|
||||
agent_version: 1,
|
||||
bindings: &bindings,
|
||||
tool_selection_policy: &Default::default(),
|
||||
resource_bindings: &[AgentResourceBinding {
|
||||
resource_id: resource.clone(),
|
||||
resource_version: 1,
|
||||
}],
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("v1 config with exact resource and tool must save");
|
||||
publish_agent_version(&sandbox, &agent, 1)
|
||||
.await
|
||||
.expect("Agent v1 must publish");
|
||||
draft_next_resource_version(&sandbox, "ws_default", &resource, b"concurrent v2").await;
|
||||
assert_eq!(
|
||||
publish_current_resource(&sandbox, "ws_default", &resource, b"concurrent v2").await,
|
||||
2
|
||||
);
|
||||
let old_tuple = catalog_tuple(&catalog_of(&sandbox, "v18-cc").await);
|
||||
assert_eq!(old_tuple.0, 1);
|
||||
assert_eq!(
|
||||
old_tuple.3.len(),
|
||||
1,
|
||||
"the old snapshot must carry the published tool"
|
||||
);
|
||||
|
||||
// v2 меняет Tool binding, иначе смешанный tuple (старые version/resources +
|
||||
// новый tools) был бы неотличим от старого snapshot.
|
||||
let mut v2_bindings = bindings.clone();
|
||||
v2_bindings[0].tool_name = "v18_concurrent_tool_v2".to_owned();
|
||||
v2_bindings[0].tool_title = "V18 concurrent tool v2".to_owned();
|
||||
|
||||
let (started_tx, started_rx) = tokio::sync::oneshot::channel();
|
||||
let reader_registry = sandbox.registry.clone();
|
||||
let reader = tokio::spawn(async move {
|
||||
let mut observed = Vec::with_capacity(256);
|
||||
let mut started_tx = Some(started_tx);
|
||||
for _ in 0..256 {
|
||||
let catalog = reader_registry
|
||||
.get_published_agent_catalog_by_slug("default", "v18-cc")
|
||||
.await
|
||||
.expect("concurrent catalog read must succeed");
|
||||
observed.push(catalog_tuple(&catalog));
|
||||
if let Some(started) = started_tx.take() {
|
||||
let _ = started.send(());
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
tokio::time::sleep(Duration::from_millis(1)).await;
|
||||
}
|
||||
observed
|
||||
});
|
||||
// Reader уже прочитал старый snapshot до начала fork/publish: окно наблюдения
|
||||
// действительно перекрывает writer, а не идёт строго после него.
|
||||
started_rx
|
||||
.await
|
||||
.expect("the reader must observe the catalog before the publication starts");
|
||||
|
||||
let forked = sandbox
|
||||
.registry
|
||||
.save_agent_catalog_config_editable(SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &WorkspaceId::new("ws_default"),
|
||||
agent_id: &agent,
|
||||
agent_version: 1,
|
||||
bindings: &v2_bindings,
|
||||
tool_selection_policy: &Default::default(),
|
||||
resource_bindings: &[AgentResourceBinding {
|
||||
resource_id: resource.clone(),
|
||||
resource_version: 2,
|
||||
}],
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("editable fork to v2 must succeed");
|
||||
assert_eq!(forked, 2);
|
||||
publish_agent_version(&sandbox, &agent, 2)
|
||||
.await
|
||||
.expect("Agent v2 must publish");
|
||||
|
||||
let observed = reader.await.expect("reader task must finish");
|
||||
let new_tuple = catalog_tuple(&catalog_of(&sandbox, "v18-cc").await);
|
||||
assert_eq!(new_tuple.0, 2);
|
||||
assert_eq!(
|
||||
new_tuple.3.len(),
|
||||
1,
|
||||
"the new snapshot must carry the edited tool"
|
||||
);
|
||||
assert_ne!(
|
||||
new_tuple.3, old_tuple.3,
|
||||
"tools must differ between snapshots, otherwise a mixed tuple is undetectable"
|
||||
);
|
||||
assert_ne!(
|
||||
old_tuple, new_tuple,
|
||||
"the fixture must actually produce two different catalog snapshots"
|
||||
);
|
||||
assert_eq!(
|
||||
observed.first(),
|
||||
Some(&old_tuple),
|
||||
"the first read happened before the publication, so it must be the old tuple"
|
||||
);
|
||||
for (index, tuple) in observed.iter().enumerate() {
|
||||
assert!(
|
||||
*tuple == old_tuple || *tuple == new_tuple,
|
||||
"concurrent read #{index} observed a mixed catalog tuple: {tuple:?}"
|
||||
);
|
||||
}
|
||||
sandbox.cleanup().await;
|
||||
}
|
||||
@@ -236,6 +236,7 @@ async fn published_agent_snapshot_remains_immutable_after_draft_edit() {
|
||||
agent_version: version.version,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &Default::default(),
|
||||
resource_bindings: &[],
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
@@ -307,6 +308,7 @@ async fn stale_agent_revision_rejects_mutation() {
|
||||
agent_version: version.version,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &Default::default(),
|
||||
resource_bindings: &[],
|
||||
expected_state: None,
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#![allow(dead_code, unused_imports)]
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::str::FromStr;
|
||||
|
||||
use crank_core::{
|
||||
AgentId, AgentOperationBinding, AgentStatus, AgentVersion, ApiKeyHeaderAuthConfig, AuthConfig,
|
||||
@@ -295,6 +296,29 @@ impl TestDatabase {
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Registry over a multi-connection pool in this test schema: concurrency regressions need
|
||||
/// sessions that can genuinely block on each other's row locks.
|
||||
pub(super) async fn concurrent_registry(&self, max_connections: u32) -> PostgresRegistry {
|
||||
let database_url = format!(
|
||||
"{}?options=-csearch_path%3D{}",
|
||||
self.database_url, self.schema
|
||||
);
|
||||
let options = sqlx::postgres::PgConnectOptions::from_str(&database_url)
|
||||
.expect("the test database url must parse into connect options");
|
||||
PostgresRegistry::connect_with_options_and_pool_config(
|
||||
options,
|
||||
crank_registry::PostgresPoolConfig {
|
||||
max_connections,
|
||||
min_connections: 0,
|
||||
acquire_timeout_ms: 10_000,
|
||||
idle_timeout_ms: 600_000,
|
||||
max_lifetime_ms: 1_800_000,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("the concurrent test registry must connect")
|
||||
}
|
||||
|
||||
pub(super) async fn cleanup(&self) {
|
||||
self.admin_pool
|
||||
.execute(sqlx::query(sqlx::AssertSqlSafe(format!(
|
||||
|
||||
@@ -5,8 +5,13 @@ mod artifact_metadata;
|
||||
mod import_plan;
|
||||
mod legacy_adoption;
|
||||
mod preflight;
|
||||
mod resource_security_revocations;
|
||||
mod rollback;
|
||||
|
||||
mod schema_removal;
|
||||
|
||||
pub(crate) use schema_removal::*;
|
||||
|
||||
static EVENT_TRIGGER_TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
|
||||
|
||||
fn legacy_preservation_row_expr(table: &str) -> &'static str {
|
||||
@@ -57,6 +62,14 @@ async fn controlled_authority_is_versioned_and_safe_under_concurrent_apply() {
|
||||
(13, "artifact-cleanup-indexes-v13"),
|
||||
(14, "import-plan-v14"),
|
||||
(15, "onboarding-import-selection-v15"),
|
||||
(16, "resource-drafts-v16"),
|
||||
(17, "resource-publications-v17"),
|
||||
(18, "agent-resource-bindings-v18"),
|
||||
(19, "resource-security-revocations-v19"),
|
||||
(20, "resource-template-sources-v20"),
|
||||
(21, "prompts-v21"),
|
||||
(22, "prompt-publications-v22"),
|
||||
(23, "prompt-dependencies-v23"),
|
||||
];
|
||||
assert_eq!(rows.len(), expected.len());
|
||||
for (row, (version, name)) in rows.iter().zip(expected) {
|
||||
@@ -121,11 +134,105 @@ async fn controlled_authority_is_versioned_and_safe_under_concurrent_apply() {
|
||||
.await
|
||||
.expect("V14 import plan relations must be readable");
|
||||
assert_eq!(import_plan_relations.len(), 2);
|
||||
let publication_relations = sqlx::query(
|
||||
"select table_name
|
||||
from information_schema.tables
|
||||
where table_schema = current_schema()
|
||||
and table_name in ('resource_publications', 'resource_versions')
|
||||
order by table_name",
|
||||
)
|
||||
.fetch_all(first.pool())
|
||||
.await
|
||||
.expect("V17 publication relation must be readable");
|
||||
assert_eq!(
|
||||
publication_relations.len(),
|
||||
2,
|
||||
"V17 must add resource_publications beside resource_versions"
|
||||
);
|
||||
let binding_relations = sqlx::query(
|
||||
"select table_name
|
||||
from information_schema.tables
|
||||
where table_schema = current_schema()
|
||||
and table_name = 'agent_resource_bindings'",
|
||||
)
|
||||
.fetch_all(first.pool())
|
||||
.await
|
||||
.expect("V18 binding relation must be readable");
|
||||
assert_eq!(
|
||||
binding_relations.len(),
|
||||
1,
|
||||
"V18 must add the typed agent_resource_bindings table"
|
||||
);
|
||||
let binding_fks: i64 = sqlx::query_scalar(
|
||||
"select count(*)::bigint
|
||||
from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and t.relname = 'agent_resource_bindings' and c.contype = 'f'",
|
||||
)
|
||||
.fetch_one(first.pool())
|
||||
.await
|
||||
.expect("V18 binding constraints must be readable");
|
||||
assert_eq!(
|
||||
binding_fks, 3,
|
||||
"V18 must keep workspace equality on both ends plus the exact Agent version"
|
||||
);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(first.pool()).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 }
|
||||
MigrationPreflight::Current { version: 23 }
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn v18_guard_rejects_missing_agent_resource_binding_trigger() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_v18_guard_drift").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
sqlx::query("drop trigger agent_resource_bindings_immutable_guard on agent_resource_bindings")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("the V18 trigger must be droppable for the drift fixture");
|
||||
let error = MigrationAuthority::preflight(&pool).await.unwrap_err();
|
||||
assert_eq!(error.code(), "partial_sequence");
|
||||
assert_eq!(
|
||||
error.version(),
|
||||
Some(18),
|
||||
"a missing V18 immutability trigger must be attributed to V18: {error}"
|
||||
);
|
||||
assert_eq!(error.stage(), "v18.immutable_trigger");
|
||||
sqlx::raw_sql(
|
||||
"create trigger agent_resource_bindings_immutable_guard
|
||||
before insert or update or delete on agent_resource_bindings
|
||||
for each row
|
||||
execute function crank_reject_published_agent_binding_mutation();",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("the canonical trigger must be restorable");
|
||||
let function_drift = MigrationAuthority::preflight(&pool).await.unwrap_err();
|
||||
assert_eq!(
|
||||
function_drift.code(),
|
||||
"partial_sequence",
|
||||
"V18 guard must pin the V18-local OLD+NEW function, not the V9 function"
|
||||
);
|
||||
assert_eq!(function_drift.stage(), "v18.immutable_trigger");
|
||||
sqlx::raw_sql(
|
||||
"drop trigger agent_resource_bindings_immutable_guard on agent_resource_bindings;
|
||||
create trigger agent_resource_bindings_immutable_guard
|
||||
before insert or update or delete on agent_resource_bindings
|
||||
for each row
|
||||
execute function crank_reject_published_agent_resource_binding_mutation();",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("the V18-local guard must be restorable");
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 23 },
|
||||
"restoring the exact V18 contract must return the current verdict"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn service_connect_is_read_only_on_fresh_database() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_read_only_startup").await;
|
||||
@@ -247,7 +354,7 @@ async fn ledgerless_legacy_baseline_is_consolidated_without_data_loss() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: 15,
|
||||
target: 23,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
@@ -360,13 +467,13 @@ async fn healthy_v2_is_reported_as_migration_required_and_upgrades_to_v3() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 2,
|
||||
target: 15,
|
||||
target: 23,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 }
|
||||
MigrationPreflight::Current { version: 23 }
|
||||
);
|
||||
let trace_column: bool = sqlx::query_scalar(
|
||||
"select exists (
|
||||
@@ -409,7 +516,7 @@ async fn healthy_v3_upgrades_to_v4_with_honest_legacy_snapshot_provenance() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 3,
|
||||
target: 15,
|
||||
target: 23,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
@@ -469,7 +576,7 @@ async fn healthy_v4_upgrades_to_v5_without_fabricating_legacy_outcomes() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 4,
|
||||
target: 15,
|
||||
target: 23,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
@@ -723,207 +830,6 @@ async fn v3_upgrade_ignores_oversized_legacy_request_ids_in_partial_index() {
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 }
|
||||
MigrationPreflight::Current { version: 23 }
|
||||
);
|
||||
}
|
||||
async fn remove_v3_schema(pool: &sqlx::PgPool) {
|
||||
sqlx::raw_sql(
|
||||
"drop index if exists invocation_logs_workspace_request_id_idx;
|
||||
alter table invocation_logs drop column if exists trace_id;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
async fn remove_v4_schema(pool: &sqlx::PgPool) {
|
||||
remove_v5_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop trigger if exists operation_versions_immutable_guard on operation_versions;
|
||||
drop function if exists crank_guard_operation_version_immutable();
|
||||
drop trigger if exists published_operations_monotonic_guard on published_operations;
|
||||
drop function if exists crank_guard_published_operation_pointer();
|
||||
drop trigger if exists operations_latest_pointer_monotonic_guard on operations;
|
||||
drop function if exists crank_guard_operation_latest_pointer();
|
||||
alter table operation_versions
|
||||
drop constraint if exists operation_versions_snapshot_provenance_check,
|
||||
drop column if exists name,
|
||||
drop column if exists display_name,
|
||||
drop column if exists category,
|
||||
drop column if exists protocol,
|
||||
drop column if exists security_level,
|
||||
drop column if exists snapshot_provenance,
|
||||
drop column if exists snapshot_observed_at,
|
||||
drop column if exists published_at,
|
||||
drop column if exists published_by;
|
||||
delete from __crank_migrations where version = 4;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
async fn remove_v5_schema(pool: &sqlx::PgPool) {
|
||||
remove_v6_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop index if exists invocation_logs_workspace_operation_version_idx;
|
||||
alter table invocation_logs
|
||||
drop column if exists operation_version,
|
||||
drop column if exists execution_stage,
|
||||
drop column if exists execution_error_code,
|
||||
drop column if exists retryability,
|
||||
drop column if exists outcome_certainty;
|
||||
delete from __crank_migrations where version = 5;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
async fn remove_v6_schema(pool: &sqlx::PgPool) {
|
||||
remove_v7_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop index if exists platform_api_keys_workspace_name_active_idx;
|
||||
create unique index if not exists platform_api_keys_workspace_name_idx on platform_api_keys(workspace_id, name);
|
||||
delete from __crank_migrations where version = 6;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
async fn remove_v7_schema(pool: &sqlx::PgPool) {
|
||||
remove_v8_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"alter table secret_versions drop constraint if exists secret_versions_target_all_or_none_check,
|
||||
drop constraint if exists secret_versions_target_epoch_check,
|
||||
drop constraint if exists secret_versions_master_key_epoch_check,
|
||||
drop column if exists target_master_key_epoch, drop column if exists target_key_version,
|
||||
drop column if exists target_ciphertext, drop column if exists master_key_epoch;
|
||||
drop table if exists master_key_rotations;
|
||||
drop table if exists master_key_identities;
|
||||
delete from __crank_migrations where version = 7;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
async fn remove_v8_schema(pool: &sqlx::PgPool) {
|
||||
remove_v9_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists admin_security_audit_events;
|
||||
drop table if exists admin_login_backoff;
|
||||
drop table if exists admin_bootstrap_contracts;
|
||||
alter table user_sessions
|
||||
drop constraint if exists user_sessions_csrf_hash_check,
|
||||
drop column if exists csrf_hash,
|
||||
drop column if exists revoked_at;
|
||||
delete from __crank_migrations where version = 8;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
async fn remove_v9_schema(pool: &sqlx::PgPool) {
|
||||
remove_v10_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop trigger if exists published_agents_monotonic_guard on published_agents;
|
||||
drop function if exists crank_reject_published_agent_pointer_rewind();
|
||||
drop trigger if exists agent_operation_bindings_immutable_guard on agent_operation_bindings;
|
||||
drop function if exists crank_reject_published_agent_binding_mutation();
|
||||
drop trigger if exists agent_versions_immutable_guard on agent_versions;
|
||||
drop function if exists crank_reject_published_agent_version_mutation();
|
||||
alter table published_agents
|
||||
drop constraint if exists published_agents_catalog_revision_check,
|
||||
drop column if exists catalog_revision;
|
||||
alter table agents
|
||||
drop constraint if exists agents_catalog_revision_check,
|
||||
drop column if exists catalog_revision;
|
||||
delete from __crank_migrations where version = 9;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
async fn remove_v10_schema(pool: &sqlx::PgPool) {
|
||||
remove_v11_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop index if exists approval_requests_pending_scope_fingerprint_idx;
|
||||
drop index if exists approval_requests_workspace_request_trace_idx;
|
||||
alter table approval_requests drop constraint if exists approval_requests_request_id_check;
|
||||
alter table approval_requests drop constraint if exists approval_requests_trace_id_check;
|
||||
alter table approval_requests drop column if exists request_id;
|
||||
alter table approval_requests drop column if exists trace_id;
|
||||
create unique index if not exists approval_requests_pending_fingerprint_idx
|
||||
on approval_requests(agent_id, operation_id, operation_version, request_fingerprint)
|
||||
where status = 'pending' and request_fingerprint is not null;
|
||||
delete from __crank_migrations where version = 10;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
async fn remove_v11_schema(pool: &sqlx::PgPool) {
|
||||
remove_v12_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists onboarding_selections;
|
||||
drop trigger if exists product_events_append_only_guard on product_events;
|
||||
drop function if exists crank_reject_product_event_mutation();
|
||||
drop table if exists product_event_daily_rollups;
|
||||
drop table if exists product_events;
|
||||
drop index if exists invocation_logs_workspace_agent_key_success_idx;
|
||||
alter table invocation_logs drop constraint if exists invocation_logs_platform_key_scope_fk;
|
||||
alter table invocation_logs drop column if exists platform_api_key_id;
|
||||
alter table platform_api_keys drop constraint if exists platform_api_keys_workspace_agent_id_unique;
|
||||
delete from __crank_migrations where version = 11;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
async fn remove_v14_schema(pool: &sqlx::PgPool) {
|
||||
remove_v15_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists import_plan_applications;
|
||||
drop table if exists import_plans;
|
||||
drop function if exists crank_reject_import_plan_mutation();
|
||||
alter table import_jobs drop constraint if exists import_jobs_workspace_id_unique;
|
||||
delete from __crank_migrations where version = 14;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
async fn remove_v15_schema(pool: &sqlx::PgPool) {
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists onboarding_import_selections;
|
||||
alter table operations drop constraint if exists operations_workspace_id_unique;
|
||||
alter table product_events drop constraint if exists product_events_name_check;
|
||||
alter table product_events add constraint product_events_name_check check (event_name in (
|
||||
'onboarding_eligible', 'onboarding_started', 'onboarding_resumed',
|
||||
'onboarding_dismissed', 'onboarding_abandoned', 'onboarding_completed'
|
||||
));
|
||||
alter table product_event_daily_rollups drop constraint if exists product_event_daily_rollups_name_check;
|
||||
alter table product_event_daily_rollups add constraint product_event_daily_rollups_name_check check (event_name in (
|
||||
'onboarding_eligible', 'onboarding_started', 'onboarding_resumed',
|
||||
'onboarding_dismissed', 'onboarding_abandoned', 'onboarding_completed'
|
||||
));
|
||||
delete from __crank_migrations where version = 15;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
async fn remove_v12_schema(pool: &sqlx::PgPool) {
|
||||
remove_v14_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop index if exists import_jobs_openapi_source_idx;
|
||||
drop index if exists import_jobs_expires_at_idx;
|
||||
drop index if exists artifact_sources_openapi_dangling_idx;
|
||||
drop index if exists artifact_sources_blob_lifecycle_detached_idx;
|
||||
drop index if exists artifact_blobs_expired_claim_idx;
|
||||
delete from __crank_migrations where version = 13;
|
||||
drop table if exists artifact_sources;
|
||||
drop table if exists artifact_blobs;
|
||||
delete from __crank_migrations where version = 12;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
@@ -2,6 +2,7 @@ use super::*;
|
||||
use sqlx::Row;
|
||||
use std::collections::HashMap;
|
||||
|
||||
mod dependent_source_fks;
|
||||
mod exhaustive_v12;
|
||||
|
||||
#[tokio::test]
|
||||
@@ -31,7 +32,7 @@ async fn healthy_v11_upgrades_to_v13_without_rewriting_prior_ledger() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 11,
|
||||
target: 15,
|
||||
target: 23,
|
||||
}
|
||||
);
|
||||
|
||||
@@ -130,8 +131,22 @@ async fn v12_guard_still_rejects_column_constraint_index_and_relation_drift() {
|
||||
drop function unrelated_trigger_fn();",
|
||||
),
|
||||
(
|
||||
"alter table artifact_sources set unlogged;",
|
||||
"alter table artifact_sources set logged;",
|
||||
// V16 добавил `resource_versions_source_fkey`, а V17 —
|
||||
// `resource_publications_source_fkey`: обе logged-таблицы ссылаются на
|
||||
// `artifact_sources`, поэтому PostgreSQL больше не переводит её в unlogged
|
||||
// (`42P16`). Тот же класс дрейфа (persistence отношения, его проверяет
|
||||
// `schema_guard_v12`) снимает блокирующие ссылки на время дрейфа и
|
||||
// возвращает их при восстановлении.
|
||||
"alter table resource_versions drop constraint resource_versions_source_fkey;
|
||||
alter table resource_publications drop constraint resource_publications_source_fkey;
|
||||
alter table artifact_sources set unlogged;",
|
||||
"alter table artifact_sources set logged;
|
||||
alter table resource_versions add constraint resource_versions_source_fkey
|
||||
foreign key (workspace_id, artifact_source_id)
|
||||
references artifact_sources(workspace_id, source_id);
|
||||
alter table resource_publications add constraint resource_publications_source_fkey
|
||||
foreign key (workspace_id, artifact_source_id)
|
||||
references artifact_sources(workspace_id, source_id);",
|
||||
),
|
||||
(
|
||||
"alter table artifact_sources drop constraint artifact_sources_id_check;
|
||||
@@ -162,7 +177,7 @@ async fn v12_guard_still_rejects_column_constraint_index_and_relation_drift() {
|
||||
sqlx::raw_sql(restore).execute(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 },
|
||||
MigrationPreflight::Current { version: 23 },
|
||||
"restore: {restore}"
|
||||
);
|
||||
}
|
||||
@@ -215,7 +230,7 @@ async fn v13_guard_rejects_wrong_cleanup_index_order_and_predicate() {
|
||||
sqlx::raw_sql(restore).execute(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 },
|
||||
MigrationPreflight::Current { version: 23 },
|
||||
"restore: {restore}"
|
||||
);
|
||||
}
|
||||
@@ -451,6 +466,33 @@ async fn catalog_constraint_definitions(pool: &sqlx::PgPool) -> HashMap<String,
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Определение constraint **указанного отношения** текущей схемы; `None`, если его нет.
|
||||
///
|
||||
/// Отношение обязательно параметром: без него одноимённый объект другой таблицы
|
||||
/// (или другой схемы) мог бы молча подменить результат, а «однозначность» —
|
||||
/// это проверяемое свойство (R-C), а не предположение вызывающего.
|
||||
async fn constraint_definition(pool: &sqlx::PgPool, relation: &str, name: &str) -> Option<String> {
|
||||
let definitions = sqlx::query_scalar::<_, String>(
|
||||
"select pg_get_constraintdef(c.oid, true)
|
||||
from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema() and t.relname = $1 and c.conname = $2",
|
||||
)
|
||||
.bind(relation)
|
||||
.bind(name)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.expect("a constraint definition must be queryable");
|
||||
assert!(
|
||||
definitions.len() <= 1,
|
||||
"constraint `{name}` on `{relation}` must resolve to exactly one definition, \
|
||||
observed {}",
|
||||
definitions.len()
|
||||
);
|
||||
definitions.into_iter().next()
|
||||
}
|
||||
|
||||
async fn assert_v12_drift(pool: &sqlx::PgPool, drift: &str, restore: &str) {
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(drift.to_owned()))
|
||||
.execute(pool)
|
||||
@@ -465,7 +507,7 @@ async fn assert_v12_drift(pool: &sqlx::PgPool, drift: &str, restore: &str) {
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 },
|
||||
MigrationPreflight::Current { version: 23 },
|
||||
"restore: {restore}"
|
||||
);
|
||||
}
|
||||
@@ -656,6 +698,50 @@ async fn v12_guard_rejects_exhaustive_catalog_drift_for_both_tables() {
|
||||
alter table artifact_sources add constraint artifact_sources_blob_digest_fkey {fk};"
|
||||
);
|
||||
assert_v12_drift(&pool, drift, &restore).await;
|
||||
} else if constraint == "artifact_sources_pkey" {
|
||||
// V16/V17 добавили `resource_versions_source_fkey` и
|
||||
// `resource_publications_source_fkey`, которые физически опираются на
|
||||
// pkey-индекс `artifact_sources_pkey`. Чтобы дрейф «constraint отсутствует»
|
||||
// был исполнимым, блокирующие ссылки снимаются на время дрейфа и
|
||||
// возвращаются при восстановлении — тот же приём, что для `artifact_blobs_pkey`.
|
||||
let draft_dependent =
|
||||
constraint_definition(&pool, "resource_versions", "resource_versions_source_fkey")
|
||||
.await;
|
||||
let publication_dependent = constraint_definition(
|
||||
&pool,
|
||||
"resource_publications",
|
||||
"resource_publications_source_fkey",
|
||||
)
|
||||
.await;
|
||||
let mut drift = String::new();
|
||||
if draft_dependent.is_some() {
|
||||
drift.push_str(
|
||||
"alter table resource_versions drop constraint resource_versions_source_fkey;\n",
|
||||
);
|
||||
}
|
||||
if publication_dependent.is_some() {
|
||||
drift.push_str(
|
||||
"alter table resource_publications drop constraint \
|
||||
resource_publications_source_fkey;\n",
|
||||
);
|
||||
}
|
||||
drift.push_str("alter table artifact_sources drop constraint artifact_sources_pkey;");
|
||||
let mut restore = format!(
|
||||
"alter table artifact_sources add constraint artifact_sources_pkey {definition};\n"
|
||||
);
|
||||
if let Some(definition_of_fk) = draft_dependent {
|
||||
restore.push_str(&format!(
|
||||
"alter table resource_versions add constraint resource_versions_source_fkey \
|
||||
{definition_of_fk};\n"
|
||||
));
|
||||
}
|
||||
if let Some(definition_of_fk) = publication_dependent {
|
||||
restore.push_str(&format!(
|
||||
"alter table resource_publications add constraint \
|
||||
resource_publications_source_fkey {definition_of_fk};"
|
||||
));
|
||||
}
|
||||
assert_v12_drift(&pool, &drift, &restore).await;
|
||||
} else {
|
||||
let drift = format!("alter table {table} drop constraint {constraint};");
|
||||
let restore = format!("alter table {table} add constraint {constraint} {definition};");
|
||||
@@ -740,3 +826,61 @@ async fn v12_guard_rejects_exhaustive_catalog_drift_for_both_tables() {
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// P4 (V16 guard): шесть однофакторных мутаций определения и проверка выбора
|
||||
// зависимого FK/created index по текущей схеме перенесены в подмодуль
|
||||
// `artifact_metadata/exhaustive_v12.rs` — там же живёт разрешённый helper
|
||||
// `dependent_source_fk_definition`, и health-правило ограничивает файл 1000 строками.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// V17 guard (Story 3.7): минимальные однофакторные мутации схемы публикаций.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn v17_guard_rejects_publication_schema_drift() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_v17_guard_drift").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 23 }
|
||||
);
|
||||
|
||||
for (drift, restore) in [
|
||||
(
|
||||
"alter table resource_publications add column raw_upload_filename text;",
|
||||
"alter table resource_publications drop column raw_upload_filename;",
|
||||
),
|
||||
(
|
||||
"alter table resource_publications drop constraint resource_publications_sensitivity_check;\n\
|
||||
alter table resource_publications add constraint resource_publications_sensitivity_check \
|
||||
check (true);",
|
||||
"alter table resource_publications drop constraint resource_publications_sensitivity_check;\n\
|
||||
alter table resource_publications add constraint resource_publications_sensitivity_check \
|
||||
check (sensitivity in ('public', 'internal', 'secret'));",
|
||||
),
|
||||
(
|
||||
"alter table resource_publications drop constraint resource_publications_source_fkey;\n\
|
||||
alter table resource_publications add constraint resource_publications_source_fkey \
|
||||
foreign key (workspace_id, artifact_source_id) \
|
||||
references artifact_sources(workspace_id, source_id) on delete cascade;",
|
||||
"alter table resource_publications drop constraint resource_publications_source_fkey;\n\
|
||||
alter table resource_publications add constraint resource_publications_source_fkey \
|
||||
foreign key (workspace_id, artifact_source_id) \
|
||||
references artifact_sources(workspace_id, source_id);",
|
||||
),
|
||||
] {
|
||||
sqlx::raw_sql(drift).execute(&pool).await.unwrap();
|
||||
let error = MigrationAuthority::preflight(&pool).await.unwrap_err();
|
||||
assert_eq!(error.code(), "partial_sequence", "drift: {drift}");
|
||||
assert_eq!(error.version(), Some(17), "drift: {drift}");
|
||||
sqlx::raw_sql(restore).execute(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 23 },
|
||||
"restore: {restore}"
|
||||
);
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
//! Test-support: определения FK, зависящих от `artifact_sources_pkey`.
|
||||
//!
|
||||
//! Вынесено из `exhaustive_v12.rs`, чтобы legacy-файл не превышал health-лимит
|
||||
//! 1000 строк после добавления V17-ссылки.
|
||||
|
||||
/// Определение V16-ссылки `resource_versions_source_fkey`, которая зависит от
|
||||
/// `artifact_sources_pkey`. Снимок V12 её не содержит (helper фильтрует две
|
||||
/// artifact-таблицы), поэтому дрейф pkey снимает и возвращает её отдельно.
|
||||
///
|
||||
/// R-C: имя разрешается вместе с **текущей схемой и конкретным отношением** —
|
||||
/// одноимённый FK другой схемы не должен попадать в результат; однозначность
|
||||
/// результата проверяется явно, а не предполагается вызывающим.
|
||||
pub(super) async fn dependent_source_fk_definition(pool: &sqlx::PgPool) -> String {
|
||||
let definitions = sqlx::query_scalar::<_, String>(
|
||||
"select pg_get_constraintdef(c.oid, true)
|
||||
from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and t.relname = 'resource_versions'
|
||||
and c.conname = 'resource_versions_source_fkey'",
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.expect("the V16 foreign key that depends on artifact_sources_pkey must be captured");
|
||||
assert_eq!(
|
||||
definitions.len(),
|
||||
1,
|
||||
"the dependent V16 foreign key must resolve to exactly one definition in the current \
|
||||
schema, observed {}",
|
||||
definitions.len()
|
||||
);
|
||||
definitions
|
||||
.into_iter()
|
||||
.next()
|
||||
.expect("exactly one dependent definition was asserted above")
|
||||
}
|
||||
|
||||
/// Определение V17-ссылки `resource_publications_source_fkey`, которая также зависит от
|
||||
/// `artifact_sources_pkey`.
|
||||
pub(super) async fn dependent_publication_fk_definition(pool: &sqlx::PgPool) -> String {
|
||||
let definitions = sqlx::query_scalar::<_, String>(
|
||||
"select pg_get_constraintdef(c.oid, true)
|
||||
from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and t.relname = 'resource_publications'
|
||||
and c.conname = 'resource_publications_source_fkey'",
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.expect("the V17 foreign key that depends on artifact_sources_pkey must be captured");
|
||||
assert_eq!(
|
||||
definitions.len(),
|
||||
1,
|
||||
"the dependent V17 foreign key must resolve to exactly one definition in the current \
|
||||
schema, observed {}",
|
||||
definitions.len()
|
||||
);
|
||||
definitions
|
||||
.into_iter()
|
||||
.next()
|
||||
.expect("exactly one dependent definition was asserted above")
|
||||
}
|
||||
+548
-4
@@ -1,5 +1,18 @@
|
||||
//! Исчерпывающие проверки дрейфа схемы: V12 (типы/дефолты/nullability/определения
|
||||
//! constraints и индексов двух artifact-таблиц) и V16 (шесть однофакторных мутаций
|
||||
//! определения `resources`/`resource_versions` + выбор зависимого FK и created
|
||||
//! index по текущей схеме).
|
||||
//!
|
||||
//! Модуль держит проверки V16 по текущей схеме; определения зависимых
|
||||
//! FK-хелперов вынесены в `dependent_source_fks.rs`, чтобы оба файла оставались
|
||||
//! в пределах health-лимита 1000 строк.
|
||||
|
||||
use crank_registry::{MigrationAuthority, MigrationPreflight};
|
||||
|
||||
use super::dependent_source_fks::{
|
||||
dependent_publication_fk_definition, dependent_source_fk_definition,
|
||||
};
|
||||
|
||||
// V12 changed-type coverage. Every column gets a reachable `alter column ...
|
||||
// type` drift whose `information_schema.data_type` differs from the frozen
|
||||
// guard expectation, plus the exact expression that puts the original type
|
||||
@@ -276,7 +289,7 @@ async fn assert_primary_key_nullability(pool: &sqlx::PgPool, table: &str, column
|
||||
);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 },
|
||||
MigrationPreflight::Current { version: 23 },
|
||||
"a rejected primary-key nullability change must leave the schema current"
|
||||
);
|
||||
|
||||
@@ -303,20 +316,52 @@ async fn assert_primary_key_nullability(pool: &sqlx::PgPool, table: &str, column
|
||||
let pkey = definitions
|
||||
.get("artifact_sources_pkey")
|
||||
.expect("artifact_sources primary key definition must be captured");
|
||||
let fk = dependent_source_fk_definition(pool).await;
|
||||
let publication_fk = dependent_publication_fk_definition(pool).await;
|
||||
(
|
||||
format!(
|
||||
"alter table artifact_sources drop constraint artifact_sources_pkey;\n\
|
||||
"alter table resource_versions drop constraint resource_versions_source_fkey;\n\
|
||||
alter table resource_publications drop constraint resource_publications_source_fkey;\n\
|
||||
alter table artifact_sources drop constraint artifact_sources_pkey;\n\
|
||||
alter table artifact_sources alter column {column} drop not null;"
|
||||
),
|
||||
format!(
|
||||
"alter table artifact_sources alter column {column} set not null;\n\
|
||||
alter table artifact_sources add constraint artifact_sources_pkey {pkey};"
|
||||
alter table artifact_sources add constraint artifact_sources_pkey {pkey};\n\
|
||||
alter table resource_versions add constraint resource_versions_source_fkey {fk};\n\
|
||||
alter table resource_publications add constraint resource_publications_source_fkey {publication_fk};"
|
||||
),
|
||||
)
|
||||
};
|
||||
super::assert_v12_drift(pool, &drift, &restore).await;
|
||||
}
|
||||
|
||||
/// Определение одноимённого FK схемы-«тени» (`story36_guard_shadow`), если она создана.
|
||||
async fn shadow_source_fk_definition(pool: &sqlx::PgPool) -> String {
|
||||
let definitions = sqlx::query_scalar::<_, String>(
|
||||
"select pg_get_constraintdef(c.oid, true)
|
||||
from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = 'story36_guard_shadow'
|
||||
and t.relname = 'resource_versions'
|
||||
and c.conname = 'resource_versions_source_fkey'",
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.expect("the shadow constraint must be readable");
|
||||
assert_eq!(
|
||||
definitions.len(),
|
||||
1,
|
||||
"the shadow foreign key must resolve to exactly one definition, observed {}",
|
||||
definitions.len()
|
||||
);
|
||||
definitions
|
||||
.into_iter()
|
||||
.next()
|
||||
.expect("exactly one shadow definition was asserted above")
|
||||
}
|
||||
|
||||
pub(super) async fn assert_constraint_definition_drift(pool: &sqlx::PgPool) {
|
||||
assert_eq!(
|
||||
CONSTRAINT_DEFINITION_DRIFT.len(),
|
||||
@@ -345,6 +390,26 @@ pub(super) async fn assert_constraint_definition_drift(pool: &sqlx::PgPool) {
|
||||
alter table artifact_sources add constraint artifact_sources_blob_digest_fkey {fk};"
|
||||
);
|
||||
assert_definition_only_drift(pool, constraint, &drift, &restore).await;
|
||||
} else if *constraint == "artifact_sources_pkey" {
|
||||
let fk = dependent_source_fk_definition(pool).await;
|
||||
let publication_fk = dependent_publication_fk_definition(pool).await;
|
||||
let drift = format!(
|
||||
"alter table resource_versions drop constraint resource_versions_source_fkey;\n\
|
||||
alter table resource_publications drop constraint resource_publications_source_fkey;\n\
|
||||
alter table artifact_sources drop constraint artifact_sources_pkey;\n\
|
||||
alter table artifact_sources add constraint artifact_sources_pkey {drift_definition};\n\
|
||||
alter table resource_versions add constraint resource_versions_source_fkey {fk};\n\
|
||||
alter table resource_publications add constraint resource_publications_source_fkey {publication_fk};"
|
||||
);
|
||||
let restore = format!(
|
||||
"alter table resource_versions drop constraint resource_versions_source_fkey;\n\
|
||||
alter table resource_publications drop constraint resource_publications_source_fkey;\n\
|
||||
alter table artifact_sources drop constraint artifact_sources_pkey;\n\
|
||||
alter table artifact_sources add constraint artifact_sources_pkey {original};\n\
|
||||
alter table resource_versions add constraint resource_versions_source_fkey {fk};\n\
|
||||
alter table resource_publications add constraint resource_publications_source_fkey {publication_fk};"
|
||||
);
|
||||
assert_definition_only_drift(pool, constraint, &drift, &restore).await;
|
||||
} else {
|
||||
let drift = format!(
|
||||
"alter table {table} drop constraint {constraint};\n\
|
||||
@@ -408,7 +473,7 @@ async fn assert_definition_only_drift(
|
||||
assert_eq!(super::catalog_constraint_definitions(pool).await, before);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 }
|
||||
MigrationPreflight::Current { version: 23 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -424,3 +489,482 @@ async fn constraint_kinds(pool: &sqlx::PgPool) -> Vec<(String, String)> {
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// P4 (affected ATDD до исправления): V16 guard обязан сверять семантику
|
||||
// constraints и полную структуру created index, а не только имя и contype.
|
||||
// Источник: CORRECTION-PACKAGE P4 (TL F06, ARC «отдельный FK lookup»).
|
||||
// Блок перенесён из `artifact_metadata.rs` (health-правило ограничивает файл
|
||||
// 1000 строками) вместе с разрешённым helper-ом `dependent_source_fk_definition`.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Полный снимок определений, которыми оперирует V16 guard, снятый из `pg_catalog`.
|
||||
///
|
||||
/// Снимок **независим** от `MigrationAuthority::preflight`: он отвечает на вопрос
|
||||
/// «каталог действительно восстановлен», а не «guard считает его правильным». Именно
|
||||
/// поэтому он нужен для возврата V16-мутаций: тот же guard принимает все шесть
|
||||
/// неправильных определений, и `Current { version: 18 }` не доказывает точное
|
||||
/// восстановление (TL review run105 F4).
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct DefinitionSnapshot {
|
||||
/// Все constraints трёх отношений: `(имя, contype, pg_get_constraintdef)`.
|
||||
constraints: Vec<(String, String, String)>,
|
||||
/// Структура created index (колонки, предикат, определение); `None` — индекса нет.
|
||||
created_index: Option<String>,
|
||||
}
|
||||
|
||||
async fn catalog_definition_snapshot(pool: &sqlx::PgPool) -> DefinitionSnapshot {
|
||||
let constraints = sqlx::query_as::<_, (String, String, String)>(
|
||||
"select c.conname::text, c.contype::text, pg_get_constraintdef(c.oid, true)
|
||||
from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and t.relname in ('resources', 'resource_versions', 'artifact_sources')
|
||||
order by c.conname",
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.expect("the definition snapshot must be readable");
|
||||
let created_index = sqlx::query_scalar::<_, String>(
|
||||
"select pg_get_indexdef(i.indexrelid) || ' [valid=' || i.indisvalid::text
|
||||
|| ', ready=' || i.indisready::text || ']'
|
||||
from pg_catalog.pg_index i
|
||||
join pg_catalog.pg_class idx on idx.oid = i.indexrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = idx.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and idx.relname = 'resources_workspace_created_idx'",
|
||||
)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.expect("the created index definition must be observable");
|
||||
DefinitionSnapshot {
|
||||
constraints,
|
||||
created_index,
|
||||
}
|
||||
}
|
||||
|
||||
/// One-factor V16 drift: имя и contype сохраняются, меняется только определение.
|
||||
/// Ожидание — specific preflight refusal (partial_sequence, version 16); точное
|
||||
/// восстановление исходного определения обязано вернуть `Current { version: 18 }`.
|
||||
#[tokio::test]
|
||||
async fn story36_v16_guard_rejects_constraint_and_created_index_definition_drift() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_v16_definition_drift").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 23 },
|
||||
"the baseline before the drift matrix must be the current V16 schema"
|
||||
);
|
||||
let mut observations: Vec<String> = Vec::new();
|
||||
let mut unrejected: Vec<&str> = Vec::new();
|
||||
|
||||
for (label, drift, restore) in [
|
||||
(
|
||||
"weakened-check",
|
||||
"alter table resources drop constraint resources_description_len;
|
||||
alter table resources add constraint resources_description_len check (true);",
|
||||
"alter table resources drop constraint resources_description_len;
|
||||
alter table resources add constraint resources_description_len
|
||||
check (octet_length(description) <= 1024);",
|
||||
),
|
||||
(
|
||||
"wrong-fk-columns-and-target",
|
||||
"alter table resource_versions drop constraint resource_versions_resource_fkey;
|
||||
alter table resource_versions add constraint resource_versions_resource_fkey
|
||||
foreign key (workspace_id) references workspaces(id) on delete cascade;",
|
||||
"alter table resource_versions drop constraint resource_versions_resource_fkey;
|
||||
alter table resource_versions add constraint resource_versions_resource_fkey
|
||||
foreign key (workspace_id, resource_id)
|
||||
references resources(workspace_id, resource_id) on delete cascade;",
|
||||
),
|
||||
(
|
||||
"not-valid-fk",
|
||||
"alter table resource_versions drop constraint resource_versions_source_fkey;
|
||||
alter table resource_versions add constraint resource_versions_source_fkey
|
||||
foreign key (workspace_id, artifact_source_id)
|
||||
references artifact_sources(workspace_id, source_id) not valid;",
|
||||
"alter table resource_versions drop constraint resource_versions_source_fkey;
|
||||
alter table resource_versions add constraint resource_versions_source_fkey
|
||||
foreign key (workspace_id, artifact_source_id)
|
||||
references artifact_sources(workspace_id, source_id);",
|
||||
),
|
||||
(
|
||||
"fk-delete-action",
|
||||
"alter table resource_versions drop constraint resource_versions_resource_fkey;
|
||||
alter table resource_versions add constraint resource_versions_resource_fkey
|
||||
foreign key (workspace_id, resource_id)
|
||||
references resources(workspace_id, resource_id) on delete restrict;",
|
||||
"alter table resource_versions drop constraint resource_versions_resource_fkey;
|
||||
alter table resource_versions add constraint resource_versions_resource_fkey
|
||||
foreign key (workspace_id, resource_id)
|
||||
references resources(workspace_id, resource_id) on delete cascade;",
|
||||
),
|
||||
(
|
||||
"created-index-predicate",
|
||||
"drop index resources_workspace_created_idx;
|
||||
create index resources_workspace_created_idx
|
||||
on resources (workspace_id, created_at, resource_id) where status = 'draft';",
|
||||
"drop index resources_workspace_created_idx;
|
||||
create index resources_workspace_created_idx
|
||||
on resources (workspace_id, created_at, resource_id);",
|
||||
),
|
||||
(
|
||||
"created-index-extra-column",
|
||||
"drop index resources_workspace_created_idx;
|
||||
create index resources_workspace_created_idx
|
||||
on resources (workspace_id, created_at, resource_id, kind);",
|
||||
"drop index resources_workspace_created_idx;
|
||||
create index resources_workspace_created_idx
|
||||
on resources (workspace_id, created_at, resource_id);",
|
||||
),
|
||||
// F5 (TL run109 CODE-REVIEW): CHECK, который остаётся синтаксически
|
||||
// «похожим» (содержит ожидаемый фрагмент), но ослаблен до всегда-истинного,
|
||||
// обязан быть отвергнут: сверка подстрок вместо семантики его пропускает.
|
||||
(
|
||||
"weakened-check-with-original-snippet",
|
||||
"alter table resources drop constraint resources_description_len;
|
||||
alter table resources add constraint resources_description_len
|
||||
check (octet_length(description) <= 1024 or resource_id is not null);",
|
||||
"alter table resources drop constraint resources_description_len;
|
||||
alter table resources add constraint resources_description_len
|
||||
check (octet_length(description) <= 1024);",
|
||||
),
|
||||
// F5: `NOT VALID` CHECK сохраняет выражение, поэтому дрейф наблюдается только
|
||||
// через `convalidated`; guard обязан читать признак валидации, а не только текст.
|
||||
(
|
||||
"not-valid-check",
|
||||
"alter table resources drop constraint resources_description_len;
|
||||
alter table resources add constraint resources_description_len
|
||||
check (octet_length(description) <= 1024) not valid;",
|
||||
"alter table resources drop constraint resources_description_len;
|
||||
alter table resources add constraint resources_description_len
|
||||
check (octet_length(description) <= 1024);",
|
||||
),
|
||||
// F5: у FK сверяются точные target/columns/actions, а не только префикс
|
||||
// определения: `ON DELETE CASCADE` на source-FK — дрейф, а не вариант нормы.
|
||||
(
|
||||
"source-fk-delete-action",
|
||||
"alter table resource_versions drop constraint resource_versions_source_fkey;
|
||||
alter table resource_versions add constraint resource_versions_source_fkey
|
||||
foreign key (workspace_id, artifact_source_id)
|
||||
references artifact_sources(workspace_id, source_id) on delete cascade;",
|
||||
"alter table resource_versions drop constraint resource_versions_source_fkey;
|
||||
alter table resource_versions add constraint resource_versions_source_fkey
|
||||
foreign key (workspace_id, artifact_source_id)
|
||||
references artifact_sources(workspace_id, source_id);",
|
||||
),
|
||||
// F5: deferrability — часть определения FK и тоже обязана быть точной.
|
||||
(
|
||||
"source-fk-deferrable",
|
||||
"alter table resource_versions drop constraint resource_versions_source_fkey;
|
||||
alter table resource_versions add constraint resource_versions_source_fkey
|
||||
foreign key (workspace_id, artifact_source_id)
|
||||
references artifact_sources(workspace_id, source_id)
|
||||
deferrable initially deferred;",
|
||||
"alter table resource_versions drop constraint resource_versions_source_fkey;
|
||||
alter table resource_versions add constraint resource_versions_source_fkey
|
||||
foreign key (workspace_id, artifact_source_id)
|
||||
references artifact_sources(workspace_id, source_id);",
|
||||
),
|
||||
// R2 (TL run113 EH1/IA2): перечисляющий CHECK обязан отвергаться, если к нему
|
||||
// добавлен любой другой предикат. Множество строковых литералов при этом
|
||||
// остаётся ожидаемым, поэтому сверка «по набору значений» такой дрейф
|
||||
// пропускает, хотя ограничение ослаблено до всегда-истинного (колонка в
|
||||
// добавленном предикате объявлена `not null`). Обе таблицы и все четыре
|
||||
// перечисления V16 принадлежат одной границе F5.
|
||||
(
|
||||
"enum-check-with-or-predicate-resources-kind",
|
||||
"alter table resources drop constraint resources_kind_check;
|
||||
alter table resources add constraint resources_kind_check
|
||||
check (kind in ('text', 'json', 'binary') or resource_id is not null);",
|
||||
"alter table resources drop constraint resources_kind_check;
|
||||
alter table resources add constraint resources_kind_check
|
||||
check (kind in ('text', 'json', 'binary'));",
|
||||
),
|
||||
(
|
||||
"enum-check-with-or-predicate-resources-status",
|
||||
"alter table resources drop constraint resources_status_check;
|
||||
alter table resources add constraint resources_status_check
|
||||
check (status in ('draft', 'published', 'archived') or resource_id is not null);",
|
||||
"alter table resources drop constraint resources_status_check;
|
||||
alter table resources add constraint resources_status_check
|
||||
check (status in ('draft', 'published', 'archived'));",
|
||||
),
|
||||
(
|
||||
"enum-check-with-or-predicate-version-kind",
|
||||
"alter table resource_versions drop constraint resource_versions_kind_check;
|
||||
alter table resource_versions add constraint resource_versions_kind_check
|
||||
check (kind in ('text', 'json', 'binary') or workspace_id is not null);",
|
||||
"alter table resource_versions drop constraint resource_versions_kind_check;
|
||||
alter table resource_versions add constraint resource_versions_kind_check
|
||||
check (kind in ('text', 'json', 'binary'));",
|
||||
),
|
||||
(
|
||||
"enum-check-with-or-predicate-version-sensitivity",
|
||||
"alter table resource_versions drop constraint resource_versions_sensitivity_check;
|
||||
alter table resource_versions add constraint resource_versions_sensitivity_check
|
||||
check (sensitivity in ('public', 'internal', 'secret') or workspace_id is not null);",
|
||||
"alter table resource_versions drop constraint resource_versions_sensitivity_check;
|
||||
alter table resource_versions add constraint resource_versions_sensitivity_check
|
||||
check (sensitivity in ('public', 'internal', 'secret'));",
|
||||
),
|
||||
// R2 (TL run113 EH2): нормализация, удаляющая пробелы ВНУТРИ строкового
|
||||
// литерала, делает ослабленный regex неотличимым от канонического: класс
|
||||
// `[0-9a-f ]` допускает пробельные символы в 64-символьном digest.
|
||||
(
|
||||
"digest-literal-space-drift",
|
||||
"alter table resource_versions drop constraint resource_versions_digest_check;
|
||||
alter table resource_versions add constraint resource_versions_digest_check
|
||||
check (digest ~ '^[0-9a-f ]{64}$');",
|
||||
"alter table resource_versions drop constraint resource_versions_digest_check;
|
||||
alter table resource_versions add constraint resource_versions_digest_check
|
||||
check (digest ~ '^[0-9a-f]{64}$');",
|
||||
),
|
||||
// R2: смена регистра ВНУТРИ литерала — такое же ослабление (uppercase MIME
|
||||
// перестаёт приниматься), но после приведения к нижнему регистру строка
|
||||
// совпадает с канонической.
|
||||
(
|
||||
"mime-literal-case-drift",
|
||||
"alter table resource_versions drop constraint resource_versions_mime_type_check;
|
||||
alter table resource_versions add constraint resource_versions_mime_type_check
|
||||
check (octet_length(mime_type) between 3 and 255
|
||||
and mime_type ~ '^[a-za-z0-9!#$&^_.+-]+/[a-za-z0-9!#$&^_.+-]+$');",
|
||||
"alter table resource_versions drop constraint resource_versions_mime_type_check;
|
||||
alter table resource_versions add constraint resource_versions_mime_type_check
|
||||
check (octet_length(mime_type) between 3 and 255
|
||||
and mime_type ~ '^[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+$');",
|
||||
),
|
||||
] {
|
||||
// Снимок каталога берётся независимо от guard-а: он нужен и чтобы подтвердить,
|
||||
// что мутация реально изменила определения, и чтобы доказать точное
|
||||
// восстановление после неё (F4).
|
||||
let before = catalog_definition_snapshot(&pool).await;
|
||||
sqlx::raw_sql(drift).execute(&pool).await.unwrap();
|
||||
let drifted = catalog_definition_snapshot(&pool).await;
|
||||
let drift_observed = drifted != before;
|
||||
// Каждый вектор исполняется независимо: отказ фиксируется наблюдением, а не паникой,
|
||||
// поэтому следующие пять мутаций не пропускаются из-за первого расхождения (R-C).
|
||||
let refusal = match MigrationAuthority::preflight(&pool).await {
|
||||
Err(error) if error.code() == "partial_sequence" && error.version() == Some(16) => {
|
||||
format!(
|
||||
"refused code={} version={:?}",
|
||||
error.code(),
|
||||
error.version()
|
||||
)
|
||||
}
|
||||
Err(error) => {
|
||||
unrejected.push(label);
|
||||
format!(
|
||||
"unexpected refusal code={} version={:?}",
|
||||
error.code(),
|
||||
error.version()
|
||||
)
|
||||
}
|
||||
Ok(state) => {
|
||||
unrejected.push(label);
|
||||
format!("accepted {state:?}")
|
||||
}
|
||||
};
|
||||
// Восстановление выполняется всегда — и при подтверждённом отказе, и при расхождении.
|
||||
sqlx::raw_sql(restore)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("restoring the exact definition must apply");
|
||||
let restored = MigrationAuthority::preflight(&pool).await;
|
||||
let restored_current = matches!(restored, Ok(MigrationPreflight::Current { version: 23 }));
|
||||
// Точное восстановление доказывается сравнением снятого снимка с baseline, а не
|
||||
// мнением того же guard-а, который принимает неправильные определения (F4).
|
||||
let restored_exact = catalog_definition_snapshot(&pool).await == before;
|
||||
if !restored_current || !restored_exact || !drift_observed {
|
||||
unrejected.push(label);
|
||||
}
|
||||
observations.push(format!(
|
||||
"{label}: {refusal}; drift_observed={drift_observed}; \
|
||||
restored_current16={restored_current}; restored_exact={restored_exact}"
|
||||
));
|
||||
}
|
||||
assert!(
|
||||
unrejected.is_empty(),
|
||||
"every one-factor V16 definition drift must really change the captured catalog, be \
|
||||
refused with a specific preflight error and be restored to the exact captured baseline; \
|
||||
observations: {observations:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// R-C: зависимый V16 FK разрешается по **текущей схеме и своему отношению**, а не
|
||||
/// по одному имени. Одноимённый валидный FK другой схемы не должен ни подменять
|
||||
/// результат, ни маскировать настоящий дрейф, а восстановление обязано вернуть
|
||||
/// снятое ранее определение байт-в-байт (не «Current16 при слабом guard»).
|
||||
#[tokio::test]
|
||||
async fn story36_v16_guard_resolves_dependent_source_fk_in_the_current_schema() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_v16_schema_scope").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 23 },
|
||||
"baseline before inserting the shadow schema"
|
||||
);
|
||||
|
||||
// Снимок канонической ссылки текущей схемы (baseline восстановления).
|
||||
let canonical = dependent_source_fk_definition(&pool).await;
|
||||
assert!(
|
||||
canonical.contains("artifact_sources") && !canonical.contains("NOT VALID"),
|
||||
"the canonical dependent reference must be the validated V16 foreign key: {canonical}"
|
||||
);
|
||||
|
||||
// Схема-«тень»: то же имя FK, другое, но валидное определение; плюс одноимённый
|
||||
// created index, чтобы проверить и выбор индекса по текущей схеме.
|
||||
sqlx::raw_sql(
|
||||
"create schema story36_guard_shadow;
|
||||
create table story36_guard_shadow.artifact_sources (
|
||||
workspace_id text not null,
|
||||
source_id text not null,
|
||||
primary key (workspace_id, source_id)
|
||||
);
|
||||
create table story36_guard_shadow.resource_versions (
|
||||
workspace_id text not null,
|
||||
resource_id text not null,
|
||||
artifact_source_id text not null
|
||||
);
|
||||
alter table story36_guard_shadow.resource_versions
|
||||
add constraint resource_versions_source_fkey
|
||||
foreign key (workspace_id, artifact_source_id)
|
||||
references story36_guard_shadow.artifact_sources(workspace_id, source_id)
|
||||
on delete restrict;
|
||||
create table story36_guard_shadow.resources (
|
||||
workspace_id text not null,
|
||||
resource_id text not null,
|
||||
created_at timestamptz not null,
|
||||
kind text not null,
|
||||
status text not null,
|
||||
primary key (workspace_id, resource_id)
|
||||
);
|
||||
create index resources_workspace_created_idx
|
||||
on story36_guard_shadow.resources (workspace_id, created_at, resource_id)
|
||||
where status = 'draft';",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("the shadow schema with same-named objects must be creatable");
|
||||
|
||||
let shadow = shadow_source_fk_definition(&pool).await;
|
||||
assert_ne!(
|
||||
shadow, canonical,
|
||||
"the shadow constraint must really differ from the canonical definition"
|
||||
);
|
||||
assert!(
|
||||
shadow.contains("story36_guard_shadow") && shadow.contains("ON DELETE RESTRICT"),
|
||||
"the shadow constraint must point at its own schema and carry its own action: {shadow}"
|
||||
);
|
||||
|
||||
// Helper обязан вернуть определение текущей схемы — даже при существующей тени.
|
||||
let resolved = dependent_source_fk_definition(&pool).await;
|
||||
assert_eq!(
|
||||
resolved, canonical,
|
||||
"the dependent FK must be resolved from the current schema, not from a same-named \
|
||||
constraint of another schema"
|
||||
);
|
||||
assert!(
|
||||
!resolved.contains("story36_guard_shadow"),
|
||||
"the shadow constraint must never leak into the helper result: {resolved}"
|
||||
);
|
||||
|
||||
// Тень не меняет вердикт guard-а по текущей схеме.
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 23 },
|
||||
"a same-named object in another schema must not change the verdict for the current schema"
|
||||
);
|
||||
|
||||
// Настоящий дрейф текущей схемы: ссылка перестаёт быть валидной (NOT VALID).
|
||||
sqlx::raw_sql(
|
||||
"alter table resource_versions drop constraint resource_versions_source_fkey;
|
||||
alter table resource_versions add constraint resource_versions_source_fkey
|
||||
foreign key (workspace_id, artifact_source_id)
|
||||
references artifact_sources(workspace_id, source_id) not valid;",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("the one-factor NOT VALID drift must be applicable");
|
||||
|
||||
let drifted = dependent_source_fk_definition(&pool).await;
|
||||
assert!(
|
||||
drifted.contains("NOT VALID"),
|
||||
"the drift must be observable in the catalog: {drifted}"
|
||||
);
|
||||
let validation: bool = sqlx::query_scalar(
|
||||
"select c.convalidated
|
||||
from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and t.relname = 'resource_versions'
|
||||
and c.conname = 'resource_versions_source_fkey'",
|
||||
)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.expect("the drift must be observable through pg_constraint");
|
||||
assert!(
|
||||
!validation,
|
||||
"the drifted reference must be recorded as not validated"
|
||||
);
|
||||
|
||||
// Наблюдение вместо паники: следующий assertion не должен прерывать восстановление.
|
||||
let verdict = MigrationAuthority::preflight(&pool).await;
|
||||
let refused_with_specific_error = matches!(
|
||||
&verdict,
|
||||
Err(error) if error.code() == "partial_sequence" && error.version() == Some(16)
|
||||
);
|
||||
let observation = match &verdict {
|
||||
Err(error) => format!(
|
||||
"refused code={} version={:?}",
|
||||
error.code(),
|
||||
error.version()
|
||||
),
|
||||
Ok(state) => format!("accepted {state:?}"),
|
||||
};
|
||||
|
||||
// Точное восстановление снятого определения — не по вердикту guard-а, а по снимку.
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(format!(
|
||||
"alter table resource_versions drop constraint resource_versions_source_fkey;
|
||||
alter table resource_versions add constraint resource_versions_source_fkey {canonical};"
|
||||
)))
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("restoring the captured definition must apply");
|
||||
assert_eq!(
|
||||
dependent_source_fk_definition(&pool).await,
|
||||
canonical,
|
||||
"restoration must return the byte-exact definition captured before the drift"
|
||||
);
|
||||
assert_eq!(
|
||||
shadow_source_fk_definition(&pool).await,
|
||||
shadow,
|
||||
"the shadow definition must stay byte-identical through drift and restoration"
|
||||
);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 23 },
|
||||
"the exact restoration must return the current V16 schema"
|
||||
);
|
||||
|
||||
// Уборка: без схемы-тени текущая схема по-прежнему V16.
|
||||
sqlx::raw_sql("drop schema story36_guard_shadow cascade;")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 23 }
|
||||
);
|
||||
|
||||
assert!(
|
||||
refused_with_specific_error,
|
||||
"a real drift of the dependent source FK in the current schema must be refused with \
|
||||
partial_sequence/16 even while a same-named FK exists in another schema; observed \
|
||||
`{observation}` (source-id affected: R-C)"
|
||||
);
|
||||
}
|
||||
@@ -71,7 +71,7 @@ async fn fresh_install_exposes_import_plan_objects_with_cascading_job_fk() {
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 }
|
||||
MigrationPreflight::Current { version: 23 }
|
||||
);
|
||||
let tables = sqlx::query(
|
||||
"select table_name
|
||||
@@ -224,7 +224,7 @@ async fn healthy_v13_upgrades_to_v14_without_changing_prior_ledger() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 13,
|
||||
target: 15,
|
||||
target: 23,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
|
||||
@@ -88,7 +88,7 @@ async fn published_ledgerless_baseline_upgrades_without_data_loss() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: 15,
|
||||
target: 23,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
@@ -101,7 +101,7 @@ async fn published_ledgerless_baseline_upgrades_without_data_loss() {
|
||||
assert_eq!(operation_count, 1);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 }
|
||||
MigrationPreflight::Current { version: 23 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -194,7 +194,7 @@ async fn published_ledgerless_historical_column_layout_upgrades_without_data_los
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: 15,
|
||||
target: 23,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
@@ -230,7 +230,7 @@ async fn published_ledgerless_historical_column_layout_upgrades_without_data_los
|
||||
);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 }
|
||||
MigrationPreflight::Current { version: 23 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -262,7 +262,7 @@ async fn published_initial_mcp_layout_is_accepted() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: 15,
|
||||
target: 23,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
@@ -280,7 +280,7 @@ async fn published_initial_mcp_layout_is_accepted() {
|
||||
assert!(supports_elicitation);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 }
|
||||
MigrationPreflight::Current { version: 23 }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -314,13 +314,13 @@ async fn published_in_place_mcp_upgrade_layout_is_accepted() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 0,
|
||||
target: 15,
|
||||
target: 23,
|
||||
}
|
||||
);
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 }
|
||||
MigrationPreflight::Current { version: 23 }
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
//! Story 3.8: V19 immutable Resource security revocations — migration evidence.
|
||||
//!
|
||||
//! Fresh install, upgrade from V18 without rewriting the prior ledger, schema
|
||||
//! drift detection, failed-DDL rollback and the fail-closed future-version gate
|
||||
//! (the path an old binary takes when it meets a database newer than itself).
|
||||
|
||||
use super::*;
|
||||
use crank_registry::MigrationApplyResult;
|
||||
|
||||
#[tokio::test]
|
||||
async fn fresh_install_creates_the_empty_revocation_authority() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_v19_fresh_install").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 23 }
|
||||
);
|
||||
let rows: i64 = sqlx::query_scalar("select count(*) from resource_security_revocations")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.expect("V19 table must be queryable after a fresh install");
|
||||
assert_eq!(
|
||||
rows, 0,
|
||||
"an empty authoritative table must preserve the previous (unrevoked) behaviour; \
|
||||
no data backfill or mass migration is allowed"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn v18_upgrades_to_v19_without_rewriting_the_prior_ledger() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_v19_upgrade").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
let before: Vec<(i64, String, String)> =
|
||||
sqlx::query_as("select version, name, checksum from __crank_migrations where version < 19 order by version")
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
remove_v19_schema(&pool).await;
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 18,
|
||||
target: 23,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
MigrationAuthority::apply(&pool).await.unwrap(),
|
||||
MigrationApplyResult::Applied { from: 18, to: 23 }
|
||||
);
|
||||
let after: Vec<(i64, String, String)> =
|
||||
sqlx::query_as("select version, name, checksum from __crank_migrations where version < 19 order by version")
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(before, after, "V16–V18 ledger rows must not be rewritten");
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 23 }
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn v19_guard_rejects_a_missing_revocation_trigger() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_v19_trigger_drift").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
sqlx::query(
|
||||
"drop trigger resource_security_revocations_immutable_guard
|
||||
on resource_security_revocations",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("the V19 trigger must be droppable for the drift fixture");
|
||||
let error = MigrationAuthority::preflight(&pool).await.unwrap_err();
|
||||
assert_eq!(error.code(), "partial_sequence");
|
||||
assert_eq!(error.version(), Some(19));
|
||||
assert_eq!(error.stage(), "v19.immutable_trigger");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_database_newer_than_the_binary_fails_closed_at_startup() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_v19_future_version").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
// The same `version > CURRENT_VERSION` branch an old V23 binary takes when it
|
||||
// meets a V24 database; a synthetic V24 row exercises it without a second binary.
|
||||
sqlx::query(
|
||||
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
|
||||
values (24, 'future-v24', repeat('a', 64), 'expand', 'n-minus-one-readable')",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let error = MigrationAuthority::preflight(&pool).await.unwrap_err();
|
||||
assert_eq!(error.code(), "future_version");
|
||||
assert_eq!(error.version(), Some(24));
|
||||
assert_eq!(error.recovery(), "install_matching_application");
|
||||
assert!(
|
||||
MigrationAuthority::require_current(&pool).await.is_err(),
|
||||
"startup must refuse a newer database instead of serving with unknown schema"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_v19_migration_rolls_back_schema_and_ledger() {
|
||||
let _event_trigger_guard = EVENT_TRIGGER_TEST_LOCK.lock().await;
|
||||
let database_url = crank_test_support::postgres_schema_url("test_v19_rollback").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
remove_v19_schema(&pool).await;
|
||||
let schema: String = sqlx::query_scalar("select current_schema()")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let failure_trigger = format!(
|
||||
"create function reject_story38_v19() returns event_trigger language plpgsql as $$
|
||||
begin
|
||||
if current_schema() = '{schema}' and current_query() like '%resource_security_revocations%' then
|
||||
raise exception 'injected v19 ddl failure';
|
||||
end if;
|
||||
end $$;
|
||||
create event trigger reject_story38_v19 on ddl_command_start
|
||||
execute function reject_story38_v19();"
|
||||
);
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(failure_trigger))
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let error = MigrationAuthority::apply(&pool).await.unwrap_err();
|
||||
sqlx::raw_sql(
|
||||
"drop event trigger reject_story38_v19;
|
||||
drop function reject_story38_v19();",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(error.code(), "apply_failed");
|
||||
assert_eq!(error.version(), Some(19));
|
||||
let present: bool = sqlx::query_scalar(
|
||||
"select to_regclass(format('%I.%I', current_schema(), 'resource_security_revocations')) is not null",
|
||||
)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!present, "failed V19 DDL must roll the table back");
|
||||
let ledger_v19: i64 =
|
||||
sqlx::query_scalar("select count(*) from __crank_migrations where version = 19")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(ledger_v19, 0);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 18,
|
||||
target: 23,
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -63,7 +63,7 @@ async fn failed_artifact_metadata_migration_rolls_back_schema_and_ledger() {
|
||||
MigrationAuthority::preflight(&pool).await.unwrap(),
|
||||
MigrationPreflight::MigrationRequired {
|
||||
current: 11,
|
||||
target: 15,
|
||||
target: 23,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
//! Тестовые helpers, возвращающие приватную схему к состоянию до конкретной
|
||||
//! миграции (вынесены из `migrations.rs`, чтобы файл оставался в пределах
|
||||
//! rust-code-health); поведение не меняется.
|
||||
|
||||
pub(crate) async fn remove_v3_schema(pool: &sqlx::PgPool) {
|
||||
sqlx::raw_sql(
|
||||
"drop index if exists invocation_logs_workspace_request_id_idx;
|
||||
alter table invocation_logs drop column if exists trace_id;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v4_schema(pool: &sqlx::PgPool) {
|
||||
remove_v5_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop trigger if exists operation_versions_immutable_guard on operation_versions;
|
||||
drop function if exists crank_guard_operation_version_immutable();
|
||||
drop trigger if exists published_operations_monotonic_guard on published_operations;
|
||||
drop function if exists crank_guard_published_operation_pointer();
|
||||
drop trigger if exists operations_latest_pointer_monotonic_guard on operations;
|
||||
drop function if exists crank_guard_operation_latest_pointer();
|
||||
alter table operation_versions
|
||||
drop constraint if exists operation_versions_snapshot_provenance_check,
|
||||
drop column if exists name,
|
||||
drop column if exists display_name,
|
||||
drop column if exists category,
|
||||
drop column if exists protocol,
|
||||
drop column if exists security_level,
|
||||
drop column if exists snapshot_provenance,
|
||||
drop column if exists snapshot_observed_at,
|
||||
drop column if exists published_at,
|
||||
drop column if exists published_by;
|
||||
delete from __crank_migrations where version = 4;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v5_schema(pool: &sqlx::PgPool) {
|
||||
remove_v6_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop index if exists invocation_logs_workspace_operation_version_idx;
|
||||
alter table invocation_logs
|
||||
drop column if exists operation_version,
|
||||
drop column if exists execution_stage,
|
||||
drop column if exists execution_error_code,
|
||||
drop column if exists retryability,
|
||||
drop column if exists outcome_certainty;
|
||||
delete from __crank_migrations where version = 5;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v6_schema(pool: &sqlx::PgPool) {
|
||||
remove_v7_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop index if exists platform_api_keys_workspace_name_active_idx;
|
||||
create unique index if not exists platform_api_keys_workspace_name_idx on platform_api_keys(workspace_id, name);
|
||||
delete from __crank_migrations where version = 6;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v7_schema(pool: &sqlx::PgPool) {
|
||||
remove_v8_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"alter table secret_versions drop constraint if exists secret_versions_target_all_or_none_check,
|
||||
drop constraint if exists secret_versions_target_epoch_check,
|
||||
drop constraint if exists secret_versions_master_key_epoch_check,
|
||||
drop column if exists target_master_key_epoch, drop column if exists target_key_version,
|
||||
drop column if exists target_ciphertext, drop column if exists master_key_epoch;
|
||||
drop table if exists master_key_rotations;
|
||||
drop table if exists master_key_identities;
|
||||
delete from __crank_migrations where version = 7;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v8_schema(pool: &sqlx::PgPool) {
|
||||
remove_v9_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists admin_security_audit_events;
|
||||
drop table if exists admin_login_backoff;
|
||||
drop table if exists admin_bootstrap_contracts;
|
||||
alter table user_sessions
|
||||
drop constraint if exists user_sessions_csrf_hash_check,
|
||||
drop column if exists csrf_hash,
|
||||
drop column if exists revoked_at;
|
||||
delete from __crank_migrations where version = 8;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v9_schema(pool: &sqlx::PgPool) {
|
||||
remove_v10_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop trigger if exists published_agents_monotonic_guard on published_agents;
|
||||
drop function if exists crank_reject_published_agent_pointer_rewind();
|
||||
drop trigger if exists agent_operation_bindings_immutable_guard on agent_operation_bindings;
|
||||
drop function if exists crank_reject_published_agent_binding_mutation();
|
||||
drop trigger if exists agent_versions_immutable_guard on agent_versions;
|
||||
drop function if exists crank_reject_published_agent_version_mutation();
|
||||
alter table published_agents
|
||||
drop constraint if exists published_agents_catalog_revision_check,
|
||||
drop column if exists catalog_revision;
|
||||
alter table agents
|
||||
drop constraint if exists agents_catalog_revision_check,
|
||||
drop column if exists catalog_revision;
|
||||
delete from __crank_migrations where version = 9;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v10_schema(pool: &sqlx::PgPool) {
|
||||
remove_v11_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop index if exists approval_requests_pending_scope_fingerprint_idx;
|
||||
drop index if exists approval_requests_workspace_request_trace_idx;
|
||||
alter table approval_requests drop constraint if exists approval_requests_request_id_check;
|
||||
alter table approval_requests drop constraint if exists approval_requests_trace_id_check;
|
||||
alter table approval_requests drop column if exists request_id;
|
||||
alter table approval_requests drop column if exists trace_id;
|
||||
create unique index if not exists approval_requests_pending_fingerprint_idx
|
||||
on approval_requests(agent_id, operation_id, operation_version, request_fingerprint)
|
||||
where status = 'pending' and request_fingerprint is not null;
|
||||
delete from __crank_migrations where version = 10;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v11_schema(pool: &sqlx::PgPool) {
|
||||
remove_v12_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists onboarding_selections;
|
||||
drop trigger if exists product_events_append_only_guard on product_events;
|
||||
drop function if exists crank_reject_product_event_mutation();
|
||||
drop table if exists product_event_daily_rollups;
|
||||
drop table if exists product_events;
|
||||
drop index if exists invocation_logs_workspace_agent_key_success_idx;
|
||||
alter table invocation_logs drop constraint if exists invocation_logs_platform_key_scope_fk;
|
||||
alter table invocation_logs drop column if exists platform_api_key_id;
|
||||
alter table platform_api_keys drop constraint if exists platform_api_keys_workspace_agent_id_unique;
|
||||
delete from __crank_migrations where version = 11;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v14_schema(pool: &sqlx::PgPool) {
|
||||
remove_v15_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists import_plan_applications;
|
||||
drop table if exists import_plans;
|
||||
drop function if exists crank_reject_import_plan_mutation();
|
||||
alter table import_jobs drop constraint if exists import_jobs_workspace_id_unique;
|
||||
delete from __crank_migrations where version = 14;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v15_schema(pool: &sqlx::PgPool) {
|
||||
remove_v16_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists onboarding_import_selections;
|
||||
alter table operations drop constraint if exists operations_workspace_id_unique;
|
||||
alter table product_events drop constraint if exists product_events_name_check;
|
||||
alter table product_events add constraint product_events_name_check check (event_name in (
|
||||
'onboarding_eligible', 'onboarding_started', 'onboarding_resumed',
|
||||
'onboarding_dismissed', 'onboarding_abandoned', 'onboarding_completed'
|
||||
));
|
||||
alter table product_event_daily_rollups drop constraint if exists product_event_daily_rollups_name_check;
|
||||
alter table product_event_daily_rollups add constraint product_event_daily_rollups_name_check check (event_name in (
|
||||
'onboarding_eligible', 'onboarding_started', 'onboarding_resumed',
|
||||
'onboarding_dismissed', 'onboarding_abandoned', 'onboarding_completed'
|
||||
));
|
||||
delete from __crank_migrations where version = 15;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v16_schema(pool: &sqlx::PgPool) {
|
||||
remove_v17_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists resource_versions;
|
||||
drop index if exists resources_workspace_created_idx;
|
||||
drop table if exists resources;
|
||||
delete from __crank_migrations where version = 16;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v17_schema(pool: &sqlx::PgPool) {
|
||||
remove_v18_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists resource_publications;
|
||||
drop index if exists resource_publications_workspace_uri_idx;
|
||||
delete from __crank_migrations where version = 17;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v18_schema(pool: &sqlx::PgPool) {
|
||||
remove_v19_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists agent_resource_bindings;
|
||||
drop function if exists crank_reject_published_agent_resource_binding_mutation();
|
||||
drop index if exists agent_resource_bindings_resource_idx;
|
||||
drop index if exists agents_workspace_id_idx;
|
||||
delete from __crank_migrations where version = 18;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v19_schema(pool: &sqlx::PgPool) {
|
||||
remove_v20_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists resource_security_revocations;
|
||||
drop function if exists crank_reject_resource_security_revocation_mutation();
|
||||
delete from __crank_migrations where version = 19;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
/// Story 3.16: снять V23 (version-keyed пины зависимостей Prompt) перед возвратом к < 23.
|
||||
pub(crate) async fn remove_v23_schema(pool: &sqlx::PgPool) {
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists prompt_message_resource_refs;
|
||||
drop table if exists prompt_dependencies;
|
||||
delete from __crank_migrations where version = 23;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
/// Story 3.13: снять V22 (Published Prompt Versions и typed Prompt bindings)
|
||||
/// перед возвратом к состоянию < 22.
|
||||
pub(crate) async fn remove_v22_schema(pool: &sqlx::PgPool) {
|
||||
remove_v23_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists agent_prompt_bindings;
|
||||
drop table if exists prompt_publications;
|
||||
drop trigger if exists prompt_arguments_immutable_guard on prompt_arguments;
|
||||
drop trigger if exists prompt_messages_immutable_guard on prompt_messages;
|
||||
alter table prompts drop constraint if exists prompts_latest_published_version_check;
|
||||
alter table prompts drop column if exists latest_published_version;
|
||||
drop function if exists crank_reject_published_prompt_version_mutation();
|
||||
drop function if exists crank_reject_prompt_publication_mutation();
|
||||
drop function if exists crank_reject_published_agent_prompt_binding_mutation();
|
||||
delete from __crank_migrations where version = 22;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
/// Story 3.12: снять V21 (typed Prompt Drafts) перед возвратом к состоянию < 21.
|
||||
pub(crate) async fn remove_v21_schema(pool: &sqlx::PgPool) {
|
||||
remove_v22_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists prompt_messages;
|
||||
drop table if exists prompt_arguments;
|
||||
drop table if exists prompt_versions;
|
||||
drop table if exists prompts;
|
||||
delete from __crank_migrations where version = 21;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
/// Story 3.10: обратная совместимость fixture-ов — снять V20 и вернуть V16/V17
|
||||
/// ограничения artifact-строк, чтобы схема соответствовала версии < 20.
|
||||
pub(crate) async fn remove_v20_schema(pool: &sqlx::PgPool) {
|
||||
remove_v21_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop table if exists resource_template_sources;
|
||||
drop function if exists crank_guard_resource_template_source_immutable();
|
||||
alter table resource_versions drop constraint if exists resource_versions_source_kind_check;
|
||||
alter table resource_versions drop constraint if exists resource_versions_size_check;
|
||||
alter table resource_versions add constraint resource_versions_size_check check (size_bytes between 1 and 262144);
|
||||
alter table resource_versions drop constraint if exists resource_versions_source_id_check;
|
||||
alter table resource_versions add constraint resource_versions_source_id_check check (artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$');
|
||||
alter table resource_versions drop column if exists source_kind;
|
||||
alter table resource_versions alter column artifact_source_id set not null;
|
||||
alter table resource_publications drop constraint if exists resource_publications_source_kind_check;
|
||||
alter table resource_publications drop constraint if exists resource_publications_size_check;
|
||||
alter table resource_publications add constraint resource_publications_size_check check (size_bytes between 1 and 262144);
|
||||
alter table resource_publications drop constraint if exists resource_publications_source_id_check;
|
||||
alter table resource_publications add constraint resource_publications_source_id_check check (artifact_source_id ~ '^src_[A-Za-z0-9_-]{1,128}$');
|
||||
alter table resource_publications drop column if exists source_kind;
|
||||
alter table resource_publications alter column artifact_source_id set not null;
|
||||
delete from __crank_migrations where version = 20;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
pub(crate) async fn remove_v12_schema(pool: &sqlx::PgPool) {
|
||||
remove_v14_schema(pool).await;
|
||||
sqlx::raw_sql(
|
||||
"drop index if exists import_jobs_openapi_source_idx;
|
||||
drop index if exists import_jobs_expires_at_idx;
|
||||
drop index if exists artifact_sources_openapi_dangling_idx;
|
||||
drop index if exists artifact_sources_blob_lifecycle_detached_idx;
|
||||
drop index if exists artifact_blobs_expired_claim_idx;
|
||||
delete from __crank_migrations where version = 13;
|
||||
drop table if exists artifact_sources;
|
||||
drop table if exists artifact_blobs;
|
||||
delete from __crank_migrations where version = 12;",
|
||||
)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
@@ -0,0 +1,484 @@
|
||||
//! Story 3.16 / FR-18 на уровне реестра: version-keyed пины зависимостей Prompt.
|
||||
//!
|
||||
//! Проверяется на реальном PostgreSQL и реальном artifact store, что контракт держится схемой и
|
||||
//! транзакциями, а не только JSON-ответом admin-api:
|
||||
//! - публикация Prompt сохраняет точную опубликованную версию Resource (resource_id, version,
|
||||
//! digest, kind, source_class, sensitivity) и объявленные точки вставки;
|
||||
//! - новая версия Resource не переписывает пины уже опубликованного Prompt;
|
||||
//! - guard-триггер запрещает менять строки пинов опубликованной версии напрямую через SQL;
|
||||
//! - dependency другого workspace неотличима от отсутствующей (`prompt_dependency_unresolved`);
|
||||
//! - dependency, на которую не ссылается ни одно сообщение, отклоняется до любого чтения
|
||||
//! (`prompt_dependency_unused`);
|
||||
//! - публикация хранит строгую (effective) sensitivity.
|
||||
|
||||
use std::{
|
||||
fs,
|
||||
os::unix::fs::PermissionsExt,
|
||||
path::PathBuf,
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
};
|
||||
|
||||
use crank_artifacts::{ArtifactStore, RegisteredArtifact};
|
||||
use crank_core::{
|
||||
Workspace, WorkspaceId, WorkspaceStatus,
|
||||
ids::{PromptId, ResourceId},
|
||||
prompt::{PromptDefinition, PromptSensitivity, PromptStatus},
|
||||
};
|
||||
use crank_registry::{
|
||||
CreateWorkspaceRequest, MigrationAuthority, PostgresRegistry, RegistryError,
|
||||
model::{
|
||||
CreatePromptDraftRequest, PublishPromptRequest,
|
||||
resource::{CreateResourceDraftRequest, PublishResourceVersionRequest},
|
||||
},
|
||||
};
|
||||
use serde_json::json;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
const WORKSPACE_ID: &str = "ws_default";
|
||||
|
||||
static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct TestRoot(PathBuf);
|
||||
|
||||
impl TestRoot {
|
||||
fn new(name: &str) -> Self {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"crank-registry-prompt-composition-{name}-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT_ROOT.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
fs::create_dir(&path).expect("private artifact root must be creatable");
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o700))
|
||||
.expect("private artifact root must be 0700");
|
||||
Self(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestRoot {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
struct Sandbox {
|
||||
registry: PostgresRegistry,
|
||||
store: ArtifactStore,
|
||||
_root: TestRoot,
|
||||
}
|
||||
|
||||
async fn sandbox(name: &str) -> Sandbox {
|
||||
let database_url = crank_test_support::postgres_schema_url(&format!("story316_{name}")).await;
|
||||
let pool = sqlx::PgPool::connect(&database_url)
|
||||
.await
|
||||
.expect("test schema must accept connections");
|
||||
MigrationAuthority::apply(&pool)
|
||||
.await
|
||||
.expect("migration sequence applies");
|
||||
let registry = PostgresRegistry::connect(&database_url)
|
||||
.await
|
||||
.expect("registry must connect");
|
||||
let root = TestRoot::new(name);
|
||||
let store = ArtifactStore::open(root.0.clone()).expect("private artifact store must open");
|
||||
Sandbox {
|
||||
registry,
|
||||
store,
|
||||
_root: root,
|
||||
}
|
||||
}
|
||||
|
||||
/// Второй workspace того же реестра: dependency из него не адресуема.
|
||||
async fn create_foreign_workspace(registry: &PostgresRegistry) -> WorkspaceId {
|
||||
let workspace_id = WorkspaceId::new("ws_story316_foreign");
|
||||
let now = OffsetDateTime::now_utc();
|
||||
registry
|
||||
.create_workspace(CreateWorkspaceRequest {
|
||||
workspace: &Workspace {
|
||||
id: workspace_id.clone(),
|
||||
slug: "story316-foreign".to_owned(),
|
||||
display_name: "Story 3.16 foreign".to_owned(),
|
||||
status: WorkspaceStatus::Active,
|
||||
settings: json!({}),
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("foreign workspace must be created");
|
||||
workspace_id
|
||||
}
|
||||
|
||||
fn registered(sandbox: &Sandbox, bytes: &[u8]) -> RegisteredArtifact {
|
||||
sandbox
|
||||
.store
|
||||
.put_registered(bytes)
|
||||
.expect("fixture bytes must be registered durably")
|
||||
}
|
||||
|
||||
/// Публикует static Resource в заданном workspace и возвращает точную опубликованную версию.
|
||||
async fn published_resource(
|
||||
sandbox: &Sandbox,
|
||||
workspace: &WorkspaceId,
|
||||
resource_id: &str,
|
||||
sensitivity: &str,
|
||||
bytes: &[u8],
|
||||
) -> (ResourceId, u32, String) {
|
||||
let id = ResourceId::new(resource_id);
|
||||
let registry = &sandbox.registry;
|
||||
if registry
|
||||
.get_resource_draft(workspace.as_str(), &id)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
// Новая опубликованная версия существующего Resource (Story 3.7 path).
|
||||
let current = registry
|
||||
.get_resource_draft(workspace.as_str(), &id)
|
||||
.await
|
||||
.expect("current draft readable");
|
||||
registry
|
||||
.update_resource_draft(
|
||||
crank_registry::model::resource::UpdateResourceDraftRequest {
|
||||
workspace_id: workspace.clone(),
|
||||
resource_id: id.clone(),
|
||||
description: "second version".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: sensitivity.to_owned(),
|
||||
expected_updated_at: current.resource.updated_at,
|
||||
artifact: registered(sandbox, bytes),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("second draft version must be creatable");
|
||||
} else {
|
||||
registry
|
||||
.create_resource_draft(CreateResourceDraftRequest {
|
||||
workspace_id: workspace.clone(),
|
||||
resource_id: id.clone(),
|
||||
uri: format!("crank://resources/{resource_id}"),
|
||||
name: resource_id.to_owned(),
|
||||
description: String::new(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: sensitivity.to_owned(),
|
||||
artifact: registered(sandbox, bytes),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("resource draft must be created");
|
||||
}
|
||||
let current = registry
|
||||
.get_resource_draft(workspace.as_str(), &id)
|
||||
.await
|
||||
.expect("draft must be readable");
|
||||
let publication = registry
|
||||
.publish_resource_version(PublishResourceVersionRequest {
|
||||
workspace_id: workspace.clone(),
|
||||
resource_id: id.clone(),
|
||||
expected_updated_at: current.resource.updated_at,
|
||||
expected_version: current.version.version,
|
||||
expected_digest: current.version.digest.clone(),
|
||||
expected_size_bytes: current.version.size_bytes,
|
||||
artifact: registered(sandbox, bytes),
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("published Resource version");
|
||||
(id, publication.version, publication.digest)
|
||||
}
|
||||
|
||||
fn composed_definition(
|
||||
dependencies: serde_json::Value,
|
||||
refs: serde_json::Value,
|
||||
) -> PromptDefinition {
|
||||
PromptDefinition::parse(&json!({
|
||||
"name": "release-notes",
|
||||
"description": "Composed prompt",
|
||||
"arguments": [{"name": "channel", "schema": {"type": "string"}, "required": true}],
|
||||
"messages": [
|
||||
{"role": "system", "content": "Summarise only the attached document."},
|
||||
{"role": "user", "content": "Channel: {{channel}}", "resource_refs": refs}
|
||||
],
|
||||
"dependencies": dependencies
|
||||
}))
|
||||
.expect("composed definition parses")
|
||||
}
|
||||
|
||||
async fn create_draft(
|
||||
sandbox: &Sandbox,
|
||||
workspace: &WorkspaceId,
|
||||
prompt_id: &str,
|
||||
sensitivity: PromptSensitivity,
|
||||
definition: PromptDefinition,
|
||||
) -> crank_registry::model::PromptDraftRecord {
|
||||
sandbox
|
||||
.registry
|
||||
.create_prompt_draft(CreatePromptDraftRequest {
|
||||
workspace_id: workspace.clone(),
|
||||
prompt_id: PromptId::new(prompt_id),
|
||||
sensitivity,
|
||||
definition,
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("composed prompt draft creates")
|
||||
}
|
||||
|
||||
async fn publish_draft(
|
||||
sandbox: &Sandbox,
|
||||
workspace: &WorkspaceId,
|
||||
prompt_id: &str,
|
||||
expected_updated_at: time::OffsetDateTime,
|
||||
) -> crank_registry::model::PromptDraftRecord {
|
||||
sandbox
|
||||
.registry
|
||||
.publish_prompt_draft(PublishPromptRequest {
|
||||
workspace_id: workspace.clone(),
|
||||
prompt_id: PromptId::new(prompt_id),
|
||||
expected_updated_at,
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("composed prompt publishes")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story316_registry_stores_version_keyed_pins_and_insertion_points() {
|
||||
let sandbox = sandbox("pins").await;
|
||||
let workspace = WorkspaceId::new(WORKSPACE_ID);
|
||||
let (resource, version, digest) = published_resource(
|
||||
&sandbox,
|
||||
&workspace,
|
||||
"res_story316_pins",
|
||||
"internal",
|
||||
b"pinned body",
|
||||
)
|
||||
.await;
|
||||
|
||||
let definition = composed_definition(
|
||||
json!([{"resource_id": resource.as_str(), "version": version}]),
|
||||
json!([0]),
|
||||
);
|
||||
let created = create_draft(
|
||||
&sandbox,
|
||||
&workspace,
|
||||
"prm_story316_pins",
|
||||
PromptSensitivity::Public,
|
||||
definition,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(created.dependencies.len(), 1);
|
||||
assert_eq!(created.dependencies[0].resource_id, resource.as_str());
|
||||
assert_eq!(created.dependencies[0].version, version);
|
||||
assert_eq!(created.dependencies[0].digest, digest);
|
||||
assert_eq!(created.dependencies[0].kind.as_str(), "text");
|
||||
assert_eq!(created.dependencies[0].source_class.as_str(), "static");
|
||||
assert_eq!(
|
||||
created.dependencies[0].sensitivity,
|
||||
PromptSensitivity::Internal
|
||||
);
|
||||
|
||||
let stored_version: i32 =
|
||||
sqlx::query_scalar("select resource_version from prompt_dependencies where prompt_id = $1")
|
||||
.bind("prm_story316_pins")
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("pins are queryable");
|
||||
assert_eq!(stored_version, i32::try_from(version).unwrap());
|
||||
|
||||
let refs: i32 = sqlx::query_scalar(
|
||||
"select dependency_position from prompt_message_resource_refs where prompt_id = $1",
|
||||
)
|
||||
.bind("prm_story316_pins")
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("insertion points are queryable");
|
||||
assert_eq!(refs, 0);
|
||||
|
||||
// AC3: публикация хранит строгую политику, локальное значение остаётся в prompts.
|
||||
let published = publish_draft(
|
||||
&sandbox,
|
||||
&workspace,
|
||||
"prm_story316_pins",
|
||||
created.updated_at,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(published.prompt.status(), PromptStatus::Published);
|
||||
let publication_sensitivity: String = sqlx::query_scalar(
|
||||
"select sensitivity from prompt_publications where prompt_id = $1 and version = 1",
|
||||
)
|
||||
.bind("prm_story316_pins")
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("publication is queryable");
|
||||
assert_eq!(publication_sensitivity, "internal");
|
||||
let local_sensitivity: String =
|
||||
sqlx::query_scalar("select sensitivity from prompts where prompt_id = $1")
|
||||
.bind("prm_story316_pins")
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("local value is queryable");
|
||||
assert_eq!(
|
||||
local_sensitivity, "public",
|
||||
"the local value is not rewritten"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story316_registry_pins_stay_immutable_after_a_new_resource_version() {
|
||||
let sandbox = sandbox("immutable").await;
|
||||
let workspace = WorkspaceId::new(WORKSPACE_ID);
|
||||
let (resource, version, digest) = published_resource(
|
||||
&sandbox,
|
||||
&workspace,
|
||||
"res_story316_immutable",
|
||||
"internal",
|
||||
b"CHANGELOG v1",
|
||||
)
|
||||
.await;
|
||||
let definition = composed_definition(
|
||||
json!([{"resource_id": resource.as_str(), "version": version}]),
|
||||
json!([0]),
|
||||
);
|
||||
let created = create_draft(
|
||||
&sandbox,
|
||||
&workspace,
|
||||
"prm_story316_immutable",
|
||||
PromptSensitivity::Internal,
|
||||
definition,
|
||||
)
|
||||
.await;
|
||||
publish_draft(
|
||||
&sandbox,
|
||||
&workspace,
|
||||
"prm_story316_immutable",
|
||||
created.updated_at,
|
||||
)
|
||||
.await;
|
||||
|
||||
// Новая опубликованная версия того же Resource.
|
||||
let (_, second_version, second_digest) = published_resource(
|
||||
&sandbox,
|
||||
&workspace,
|
||||
"res_story316_immutable",
|
||||
"internal",
|
||||
b"CHANGELOG v2",
|
||||
)
|
||||
.await;
|
||||
assert_eq!(second_version, version + 1);
|
||||
assert_ne!(second_digest, digest);
|
||||
|
||||
let publication = sandbox
|
||||
.registry
|
||||
.get_published_prompt_version(
|
||||
&workspace,
|
||||
&PromptId::new("prm_story316_immutable"),
|
||||
version,
|
||||
)
|
||||
.await
|
||||
.expect("published prompt version is readable");
|
||||
assert_eq!(
|
||||
publication.dependencies[0].version, version,
|
||||
"the publication keeps the exact pinned version"
|
||||
);
|
||||
assert_eq!(publication.dependencies[0].digest, digest);
|
||||
|
||||
// Guard опубликованной версии: прямая правка пина через SQL отклоняется.
|
||||
let update = sqlx::query(
|
||||
"update prompt_dependencies set resource_version = resource_version + 1 where prompt_id = $1",
|
||||
)
|
||||
.bind("prm_story316_immutable")
|
||||
.execute(sandbox.registry.pool())
|
||||
.await;
|
||||
assert!(
|
||||
update.is_err(),
|
||||
"a published pin must be immutable through SQL as well"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story316_registry_cross_workspace_dependency_is_unresolved() {
|
||||
let sandbox = sandbox("foreign").await;
|
||||
let workspace = WorkspaceId::new(WORKSPACE_ID);
|
||||
let foreign = create_foreign_workspace(&sandbox.registry).await;
|
||||
let (resource, version, _digest) = published_resource(
|
||||
&sandbox,
|
||||
&foreign,
|
||||
"res_story316_foreign",
|
||||
"internal",
|
||||
b"foreign body",
|
||||
)
|
||||
.await;
|
||||
|
||||
let definition = composed_definition(
|
||||
json!([{"resource_id": resource.as_str(), "version": version}]),
|
||||
json!([0]),
|
||||
);
|
||||
let error = sandbox
|
||||
.registry
|
||||
.create_prompt_draft(CreatePromptDraftRequest {
|
||||
workspace_id: workspace.clone(),
|
||||
prompt_id: PromptId::new("prm_story316_foreign"),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition,
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect_err("a foreign dependency is not addressable");
|
||||
assert!(matches!(
|
||||
error,
|
||||
RegistryError::PromptDependencyUnresolved { position: 0, .. }
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story316_registry_unused_dependency_is_refused() {
|
||||
let sandbox = sandbox("unused").await;
|
||||
let workspace = WorkspaceId::new(WORKSPACE_ID);
|
||||
let (first, first_version, _) = published_resource(
|
||||
&sandbox,
|
||||
&workspace,
|
||||
"res_story316_unused_a",
|
||||
"internal",
|
||||
b"first",
|
||||
)
|
||||
.await;
|
||||
let (second, second_version, _) = published_resource(
|
||||
&sandbox,
|
||||
&workspace,
|
||||
"res_story316_unused_b",
|
||||
"internal",
|
||||
b"second",
|
||||
)
|
||||
.await;
|
||||
|
||||
let definition = composed_definition(
|
||||
json!([
|
||||
{"resource_id": first.as_str(), "version": first_version},
|
||||
{"resource_id": second.as_str(), "version": second_version}
|
||||
]),
|
||||
json!([0]),
|
||||
);
|
||||
let error = sandbox
|
||||
.registry
|
||||
.create_prompt_draft(CreatePromptDraftRequest {
|
||||
workspace_id: workspace.clone(),
|
||||
prompt_id: PromptId::new("prm_story316_unused"),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition,
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect_err("a dependency that no message references is refused");
|
||||
match error {
|
||||
RegistryError::PromptDependencyUnused {
|
||||
position,
|
||||
resource_id,
|
||||
version,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(position, 1);
|
||||
assert_eq!(resource_id, second.as_str());
|
||||
assert_eq!(version, second_version);
|
||||
}
|
||||
other => panic!("expected prompt_dependency_unused, got {other:?}"),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
use crank_core::{
|
||||
WorkspaceId,
|
||||
ids::PromptId,
|
||||
prompt::{PromptDefinition, PromptSensitivity, PromptStatus},
|
||||
};
|
||||
use crank_registry::{
|
||||
MigrationAuthority, PostgresRegistry,
|
||||
model::{CreatePromptDraftRequest, UpdatePromptDraftRequest},
|
||||
};
|
||||
use serde_json::json;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
const WS: &str = "ws_default";
|
||||
|
||||
fn prompt(content: &str) -> PromptDefinition {
|
||||
PromptDefinition::parse(&json!({
|
||||
"name":"welcome", "description":"Greeting",
|
||||
"arguments":[{"name":"name","schema":{"type":"string"},"required":true}],
|
||||
"messages":[{"role":"user","content":content}]
|
||||
}))
|
||||
.expect("valid typed definition")
|
||||
}
|
||||
|
||||
async fn registry_pool(label: &str) -> (PostgresRegistry, sqlx::PgPool) {
|
||||
let url = crank_test_support::postgres_schema_url(&format!("story312_{label}")).await;
|
||||
let pool = sqlx::PgPool::connect(&url)
|
||||
.await
|
||||
.expect("test postgres schema connects");
|
||||
MigrationAuthority::apply(&pool)
|
||||
.await
|
||||
.expect("migration sequence applies");
|
||||
let registry = PostgresRegistry::connect(&url)
|
||||
.await
|
||||
.expect("registry connects");
|
||||
(registry, pool)
|
||||
}
|
||||
|
||||
async fn registry(label: &str) -> PostgresRegistry {
|
||||
registry_pool(label).await.0
|
||||
}
|
||||
|
||||
fn defaulted_prompt(default: serde_json::Value) -> serde_json::Value {
|
||||
json!({
|
||||
"name":"welcome", "description":"Greeting",
|
||||
"arguments":[{"name":"text","schema":{"type":"string"},"required":false,"default":default}],
|
||||
"messages":[{"role":"user","content":"{{text}}"}]
|
||||
})
|
||||
}
|
||||
|
||||
async fn jsonb_text_bytes(pool: &sqlx::PgPool, text: &str) -> i32 {
|
||||
sqlx::query_scalar("select octet_length(to_jsonb($1::text)::text)")
|
||||
.bind(text)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.expect("PostgreSQL reports the stored jsonb size")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story312_prompt_draft_persists_typed_definition_and_is_previewable() {
|
||||
let registry = registry("draft_roundtrip").await;
|
||||
let workspace_id = WorkspaceId::new(WS);
|
||||
let prompt_id = PromptId::new("prm_story312_roundtrip");
|
||||
let record = registry
|
||||
.create_prompt_draft(CreatePromptDraftRequest {
|
||||
workspace_id: workspace_id.clone(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition: prompt("Hello {{name}}"),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("draft creates");
|
||||
assert_eq!(record.prompt.status(), PromptStatus::Draft);
|
||||
assert_eq!(record.prompt.version(), 1);
|
||||
let restored = registry
|
||||
.get_prompt_draft(&workspace_id, &prompt_id)
|
||||
.await
|
||||
.expect("typed draft reloads");
|
||||
assert_eq!(record, restored);
|
||||
let args = serde_json::Map::from_iter([("name".to_owned(), json!("Ada"))]);
|
||||
assert_eq!(
|
||||
restored.prompt.definition().preview(&args).unwrap()[0].content,
|
||||
"Hello Ada"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story312_prompt_multiline_defaults_roundtrip_through_real_postgres() {
|
||||
let (registry, pool) = registry_pool("multiline_roundtrip").await;
|
||||
let workspace_id = WorkspaceId::new(WS);
|
||||
let prompt_id = PromptId::new("prm_story312_multiline");
|
||||
let line_based = "\n".repeat(3_000);
|
||||
let tab_based = "\t".repeat(3_000);
|
||||
let definition = PromptDefinition::parse(&json!({
|
||||
"name": "multiline",
|
||||
"description": "Defaults with short JSON escapes",
|
||||
"arguments": [
|
||||
{"name":"lines","schema":{"type":"string"},"required":false,"default":line_based},
|
||||
{"name":"tabs","schema":{"type":"string"},"required":false,"default":tab_based}
|
||||
],
|
||||
"messages": [{"role":"user","content":"{{lines}}|{{tabs}}"}]
|
||||
}))
|
||||
.expect("multiline defaults stay inside the storage guard");
|
||||
registry
|
||||
.create_prompt_draft(CreatePromptDraftRequest {
|
||||
workspace_id: workspace_id.clone(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition: definition.clone(),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("draft with multiline defaults persists");
|
||||
let restored = registry
|
||||
.get_prompt_draft(&workspace_id, &prompt_id)
|
||||
.await
|
||||
.expect("multiline draft reloads");
|
||||
assert_eq!(restored.prompt.definition(), &definition);
|
||||
let stored_sizes: Vec<i32> = sqlx::query_scalar(
|
||||
"select octet_length(default_value::text) from prompt_arguments where prompt_id=$1 order by position",
|
||||
)
|
||||
.bind(prompt_id.as_str())
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.expect("stored default sizes are readable");
|
||||
assert!(stored_sizes.iter().all(|size| *size <= 16_384));
|
||||
let rendered = restored
|
||||
.prompt
|
||||
.definition()
|
||||
.preview(&serde_json::Map::new())
|
||||
.expect("multiline defaults preview");
|
||||
assert_eq!(rendered[0].content, format!("{line_based}|{tab_based}"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story312_default_size_matches_the_real_postgres_jsonb_text() {
|
||||
let (_registry, pool) = registry_pool("jsonb_text_size").await;
|
||||
let cases = [
|
||||
("plain", 'a', 16_382, 16_383),
|
||||
("lf", '\n', 8_191, 8_192),
|
||||
("tab", '\t', 8_191, 8_192),
|
||||
("cr", '\r', 8_191, 8_192),
|
||||
("backspace", '\u{8}', 8_191, 8_192),
|
||||
("formfeed", '\u{c}', 8_191, 8_192),
|
||||
("quote", '"', 8_191, 8_192),
|
||||
("backslash", '\\', 8_191, 8_192),
|
||||
("unicode", 'я', 8_191, 8_192),
|
||||
("control_0x01", '\u{1}', 2_730, 2_731),
|
||||
];
|
||||
for (label, unit, at_count, over_count) in cases {
|
||||
let at_limit = unit.to_string().repeat(at_count);
|
||||
let over_limit = unit.to_string().repeat(over_count);
|
||||
let at_size = jsonb_text_bytes(&pool, &at_limit).await;
|
||||
let over_size = jsonb_text_bytes(&pool, &over_limit).await;
|
||||
assert_eq!(
|
||||
PromptDefinition::parse(&defaulted_prompt(json!(at_limit))).is_ok(),
|
||||
at_size <= 16_384,
|
||||
"{label}: validator and PostgreSQL must agree at {at_size} bytes"
|
||||
);
|
||||
assert_eq!(
|
||||
PromptDefinition::parse(&defaulted_prompt(json!(over_limit))).is_ok(),
|
||||
over_size <= 16_384,
|
||||
"{label}: validator and PostgreSQL must agree at {over_size} bytes"
|
||||
);
|
||||
assert!(at_size <= 16_384 && over_size > 16_384);
|
||||
}
|
||||
// U+0000 is storage-incompatible in both columns this aggregate writes to.
|
||||
for (label, statement, value) in [
|
||||
("jsonb", "select ($1::jsonb)::text", "\"\\u0000\""),
|
||||
("text", "select $1::text", "a\u{0}b"),
|
||||
] {
|
||||
let stored: Result<String, _> = sqlx::query_scalar(statement)
|
||||
.bind(value)
|
||||
.fetch_one(&pool)
|
||||
.await;
|
||||
assert!(
|
||||
stored.is_err(),
|
||||
"PostgreSQL must reject U+0000 in {label}: {stored:?}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
PromptDefinition::parse(&defaulted_prompt(json!("\u{0}"))),
|
||||
Err(crank_core::prompt::PromptError::InvalidDefinition),
|
||||
"a storage-incompatible NUL default must fail before SQL"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story312_prompt_draft_roundtrips_enum_defaults_and_ordered_messages() {
|
||||
let registry = registry("typed_roundtrip").await;
|
||||
let workspace_id = WorkspaceId::new(WS);
|
||||
let prompt_id = PromptId::new("prm_story312_typed");
|
||||
let definition = PromptDefinition::parse(&json!({
|
||||
"name": "typed",
|
||||
"description": "Enum, defaults and several messages",
|
||||
"arguments": [
|
||||
{"name":"tone","schema":{"type":"string","enum":["warm","plain"]},"required":false,"default":"warm"},
|
||||
{"name":"count","schema":{"type":"integer"},"required":false,"default":3},
|
||||
{"name":"enabled","schema":{"type":"boolean"},"required":true}
|
||||
],
|
||||
"messages": [
|
||||
{"role":"system","content":"Tone {{tone}}."},
|
||||
{"role":"user","content":"Count {{count}}, enabled {{enabled}}."},
|
||||
{"role":"assistant","content":"Acknowledged."}
|
||||
]
|
||||
}))
|
||||
.expect("valid typed definition");
|
||||
registry
|
||||
.create_prompt_draft(CreatePromptDraftRequest {
|
||||
workspace_id: workspace_id.clone(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
sensitivity: PromptSensitivity::Secret,
|
||||
definition: definition.clone(),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("draft creates");
|
||||
let restored = registry
|
||||
.get_prompt_draft(&workspace_id, &prompt_id)
|
||||
.await
|
||||
.expect("typed draft reloads");
|
||||
assert_eq!(restored.prompt.definition(), &definition);
|
||||
assert_eq!(restored.prompt.sensitivity(), PromptSensitivity::Secret);
|
||||
assert_eq!(restored.prompt.definition().as_json(), definition.as_json());
|
||||
let args = serde_json::Map::from_iter([
|
||||
("enabled".to_owned(), json!(true)),
|
||||
("count".to_owned(), json!(7)),
|
||||
]);
|
||||
let rendered = restored
|
||||
.prompt
|
||||
.definition()
|
||||
.preview(&args)
|
||||
.expect("restored defaults and enum render");
|
||||
assert_eq!(rendered[0].content, "Tone warm.");
|
||||
assert_eq!(rendered[1].content, "Count 7, enabled true.");
|
||||
assert_eq!(rendered[2].content, "Acknowledged.");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story312_prompt_list_serves_records_beyond_the_first_hundred() {
|
||||
let registry = registry("list_all").await;
|
||||
let workspace_id = WorkspaceId::new(WS);
|
||||
let start = OffsetDateTime::now_utc();
|
||||
let mut ids = Vec::new();
|
||||
for index in 0..101 {
|
||||
let prompt_id = PromptId::new(format!("prm_story312_page_{index:03}"));
|
||||
registry
|
||||
.create_prompt_draft(CreatePromptDraftRequest {
|
||||
workspace_id: workspace_id.clone(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition: prompt("Hello {{name}}"),
|
||||
created_at: start + time::Duration::milliseconds(index),
|
||||
})
|
||||
.await
|
||||
.expect("draft creates");
|
||||
ids.push(prompt_id);
|
||||
}
|
||||
let listed = registry
|
||||
.list_prompt_drafts(&workspace_id)
|
||||
.await
|
||||
.expect("list reads every draft");
|
||||
let listed_ids: Vec<String> = listed
|
||||
.iter()
|
||||
.map(|record| record.prompt.prompt_id().to_string())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
listed_ids.len(),
|
||||
101,
|
||||
"no Draft may be truncated from the list"
|
||||
);
|
||||
assert_eq!(listed_ids.first(), Some(&ids[0].to_string()));
|
||||
assert_eq!(listed_ids.last(), Some(&ids[100].to_string()));
|
||||
for id in &ids {
|
||||
assert!(
|
||||
listed_ids.contains(&id.to_string()),
|
||||
"draft {id} must stay listed"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story312_prompt_update_uses_compare_and_swap_and_workspace_scope() {
|
||||
let registry = registry("draft_cas_scope").await;
|
||||
let workspace_id = WorkspaceId::new(WS);
|
||||
let prompt_id = PromptId::new("prm_story312_cas");
|
||||
let created = registry
|
||||
.create_prompt_draft(CreatePromptDraftRequest {
|
||||
workspace_id: workspace_id.clone(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
sensitivity: PromptSensitivity::Secret,
|
||||
definition: prompt("Old {{name}}"),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("draft creates");
|
||||
let changed = registry
|
||||
.update_prompt_draft(UpdatePromptDraftRequest {
|
||||
workspace_id: workspace_id.clone(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition: prompt("New {{name}}"),
|
||||
expected_updated_at: created.updated_at,
|
||||
updated_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("current revision updates");
|
||||
assert_eq!(changed.prompt.version(), 2);
|
||||
assert_eq!(changed.prompt.status(), PromptStatus::Draft);
|
||||
assert!(matches!(
|
||||
registry
|
||||
.update_prompt_draft(UpdatePromptDraftRequest {
|
||||
workspace_id: workspace_id.clone(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition: prompt("Stale {{name}}"),
|
||||
expected_updated_at: created.updated_at,
|
||||
updated_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await,
|
||||
Err(crank_registry::RegistryError::PromptStaleRevision { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
registry
|
||||
.get_prompt_draft(&WorkspaceId::new("ws_foreign"), &prompt_id)
|
||||
.await,
|
||||
Err(crank_registry::RegistryError::PromptNotFound { .. })
|
||||
));
|
||||
}
|
||||
@@ -0,0 +1,756 @@
|
||||
//! Story 3.13 / FR-17: immutable Published Prompt Versions и exact typed Prompt
|
||||
//! bindings Agent (V22).
|
||||
//!
|
||||
//! Проверяется на реальном PostgreSQL, что контракт держится схемой и
|
||||
//! транзакциями, а не только JSON-ответом API:
|
||||
//! - publish фиксирует точную версию, последующая правка открывает новый Draft,
|
||||
//! exact v1 не меняется после edit/publish/archive;
|
||||
//! - concurrent publish с одинаковым `expected_updated_at` даёт ровно одну
|
||||
//! публикацию, проигравший получает stale;
|
||||
//! - guard-триггеры запрещают менять definition опубликованной версии и строку
|
||||
//! публикации напрямую через SQL;
|
||||
//! - binding адресует exact published версию, archived/unpublished отклоняются,
|
||||
//! published Agent bindings иммутабельны, повтор Agent publish не даёт двойной
|
||||
//! bump, scope другого workspace не раскрывается.
|
||||
|
||||
use crank_core::{
|
||||
Agent, AgentId, AgentStatus, AgentVersion, Workspace, WorkspaceId, WorkspaceStatus,
|
||||
ids::PromptId,
|
||||
prompt::{PromptDefinition, PromptSensitivity, PromptStatus},
|
||||
};
|
||||
use crank_registry::{
|
||||
CreateAgentRequest, CreateWorkspaceRequest, MigrationAuthority, PostgresRegistry,
|
||||
PublishAgentRequest, RegistryError,
|
||||
model::{
|
||||
AgentPromptBinding, ArchivePromptRequest, CreatePromptDraftRequest, PublishPromptRequest,
|
||||
SaveAgentCatalogConfigRequest, UpdatePromptDraftRequest,
|
||||
},
|
||||
};
|
||||
use serde_json::json;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
const WS: &str = "ws_default";
|
||||
|
||||
fn prompt(content: &str) -> PromptDefinition {
|
||||
PromptDefinition::parse(&json!({
|
||||
"name":"welcome", "description":"Greeting",
|
||||
"arguments":[{"name":"name","schema":{"type":"string"},"required":true}],
|
||||
"messages":[{"role":"system","content":"Be brief."},{"role":"user","content":content}]
|
||||
}))
|
||||
.expect("valid typed definition")
|
||||
}
|
||||
|
||||
async fn registry_pool(label: &str) -> (PostgresRegistry, sqlx::PgPool) {
|
||||
let url = crank_test_support::postgres_schema_url(&format!("story313_{label}")).await;
|
||||
let pool = sqlx::PgPool::connect(&url)
|
||||
.await
|
||||
.expect("test postgres schema connects");
|
||||
MigrationAuthority::apply(&pool)
|
||||
.await
|
||||
.expect("migration sequence applies");
|
||||
let registry = PostgresRegistry::connect(&url)
|
||||
.await
|
||||
.expect("registry connects");
|
||||
(registry, pool)
|
||||
}
|
||||
|
||||
async fn registry(label: &str) -> PostgresRegistry {
|
||||
registry_pool(label).await.0
|
||||
}
|
||||
|
||||
async fn create_prompt(
|
||||
registry: &PostgresRegistry,
|
||||
workspace_id: &WorkspaceId,
|
||||
prompt_id: &PromptId,
|
||||
) -> crank_registry::model::PromptDraftRecord {
|
||||
registry
|
||||
.create_prompt_draft(CreatePromptDraftRequest {
|
||||
workspace_id: workspace_id.clone(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition: prompt("Hello {{name}}"),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("draft creates")
|
||||
}
|
||||
|
||||
async fn publish(
|
||||
registry: &PostgresRegistry,
|
||||
workspace_id: &WorkspaceId,
|
||||
prompt_id: &PromptId,
|
||||
expected_updated_at: OffsetDateTime,
|
||||
) -> Result<crank_registry::model::PromptDraftRecord, RegistryError> {
|
||||
registry
|
||||
.publish_prompt_draft(PublishPromptRequest {
|
||||
workspace_id: workspace_id.clone(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
expected_updated_at,
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// NEW-side проверки guard-триггеров обязаны падать именно на защите
|
||||
/// опубликованной версии, а не на случайном ограничении схемы.
|
||||
fn assert_immutable_guard_rejected(
|
||||
result: Result<sqlx::postgres::PgQueryResult, sqlx::Error>,
|
||||
expected_message: &str,
|
||||
) {
|
||||
let error = match result {
|
||||
Ok(_) => panic!("raw SQL must be rejected by `{expected_message}`"),
|
||||
Err(error) => error,
|
||||
};
|
||||
let message = match &error {
|
||||
sqlx::Error::Database(database) => database.message().to_owned(),
|
||||
other => panic!("expected the `{expected_message}` guard rejection, got: {other}"),
|
||||
};
|
||||
assert!(
|
||||
message.contains(expected_message),
|
||||
"the guard must reject the write with `{expected_message}`, got: {message}"
|
||||
);
|
||||
}
|
||||
|
||||
async fn create_draft_agent(
|
||||
registry: &PostgresRegistry,
|
||||
workspace_id: &WorkspaceId,
|
||||
agent_id: &str,
|
||||
slug: &str,
|
||||
) -> AgentId {
|
||||
let id = AgentId::new(agent_id);
|
||||
let now = OffsetDateTime::now_utc();
|
||||
registry
|
||||
.create_agent(CreateAgentRequest {
|
||||
agent: &Agent {
|
||||
id: id.clone(),
|
||||
workspace_id: workspace_id.clone(),
|
||||
slug: slug.to_owned(),
|
||||
display_name: slug.to_owned(),
|
||||
description: "Story 3.13 prompt binding fixture".to_owned(),
|
||||
status: AgentStatus::Draft,
|
||||
current_draft_version: 1,
|
||||
latest_published_version: None,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
published_at: None,
|
||||
},
|
||||
version: &AgentVersion {
|
||||
agent_id: id.clone(),
|
||||
version: 1,
|
||||
status: AgentStatus::Draft,
|
||||
instructions: json!({}),
|
||||
tool_selection_policy: Default::default(),
|
||||
created_at: now,
|
||||
},
|
||||
bindings: &[],
|
||||
})
|
||||
.await
|
||||
.expect("draft Agent is created");
|
||||
id
|
||||
}
|
||||
|
||||
async fn save_prompt_bindings(
|
||||
registry: &PostgresRegistry,
|
||||
workspace_id: &WorkspaceId,
|
||||
agent_id: &AgentId,
|
||||
agent_version: u32,
|
||||
prompt_id: &PromptId,
|
||||
prompt_version: u32,
|
||||
) -> Result<u32, RegistryError> {
|
||||
registry
|
||||
.save_agent_catalog_config_editable_with_prompts(
|
||||
SaveAgentCatalogConfigRequest {
|
||||
workspace_id,
|
||||
agent_id,
|
||||
agent_version,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &Default::default(),
|
||||
resource_bindings: &[],
|
||||
expected_state: None,
|
||||
},
|
||||
&[AgentPromptBinding {
|
||||
prompt_id: prompt_id.clone(),
|
||||
prompt_version,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story313_publish_pins_immutable_version_and_edit_opens_new_draft() {
|
||||
let registry = registry("publish_lifecycle").await;
|
||||
let workspace_id = WorkspaceId::new(WS);
|
||||
let prompt_id = PromptId::new("prm_story313_lifecycle");
|
||||
let created = create_prompt(®istry, &workspace_id, &prompt_id).await;
|
||||
let published = publish(®istry, &workspace_id, &prompt_id, created.updated_at)
|
||||
.await
|
||||
.expect("valid Draft publishes");
|
||||
assert_eq!(published.prompt.status(), PromptStatus::Published);
|
||||
assert_eq!(published.prompt.version(), 1);
|
||||
assert_eq!(published.latest_published_version, Some(1));
|
||||
assert_eq!(published.prompt.definition(), created.prompt.definition());
|
||||
|
||||
let exact = registry
|
||||
.get_published_prompt_version(&workspace_id, &prompt_id, 1)
|
||||
.await
|
||||
.expect("exact published version reads");
|
||||
assert_eq!(exact.name, "welcome");
|
||||
assert_eq!(&exact.definition, created.prompt.definition());
|
||||
|
||||
let edited_definition = prompt("Edited {{name}}");
|
||||
let edited = registry
|
||||
.update_prompt_draft(UpdatePromptDraftRequest {
|
||||
workspace_id: workspace_id.clone(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition: edited_definition.clone(),
|
||||
expected_updated_at: published.updated_at,
|
||||
updated_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("editing a published Prompt opens a new Draft");
|
||||
assert_eq!(edited.prompt.status(), PromptStatus::Draft);
|
||||
assert_eq!(edited.prompt.version(), 2);
|
||||
assert_eq!(edited.latest_published_version, Some(1));
|
||||
assert_eq!(edited.prompt.definition(), &edited_definition);
|
||||
|
||||
let preserved = registry
|
||||
.get_published_prompt_version(&workspace_id, &prompt_id, 1)
|
||||
.await
|
||||
.expect("the pinned publication survives a Draft edit");
|
||||
assert_eq!(&preserved.definition, created.prompt.definition());
|
||||
assert_eq!(preserved.name, "welcome");
|
||||
|
||||
// Вторая публикация: publish v2 создаёт отдельный immutable snapshot, при этом
|
||||
// exact v1 остаётся читаемой и latest_published_version поднимается до 2.
|
||||
let published_v2 = publish(®istry, &workspace_id, &prompt_id, edited.updated_at)
|
||||
.await
|
||||
.expect("the edited Draft publishes as v2");
|
||||
assert_eq!(published_v2.prompt.status(), PromptStatus::Published);
|
||||
assert_eq!(published_v2.prompt.version(), 2);
|
||||
assert_eq!(published_v2.latest_published_version, Some(2));
|
||||
assert_eq!(published_v2.prompt.definition(), &edited_definition);
|
||||
|
||||
let exact_v1_after_v2 = registry
|
||||
.get_published_prompt_version(&workspace_id, &prompt_id, 1)
|
||||
.await
|
||||
.expect("exact v1 stays readable after publishing v2");
|
||||
assert_eq!(&exact_v1_after_v2.definition, created.prompt.definition());
|
||||
assert_eq!(exact_v1_after_v2.version, 1);
|
||||
let exact_v2 = registry
|
||||
.get_published_prompt_version(&workspace_id, &prompt_id, 2)
|
||||
.await
|
||||
.expect("exact v2 is readable by its own number");
|
||||
assert_eq!(exact_v2.version, 2);
|
||||
assert_eq!(&exact_v2.definition, &edited_definition);
|
||||
|
||||
let archived = registry
|
||||
.archive_prompt_draft(ArchivePromptRequest {
|
||||
workspace_id: workspace_id.clone(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
expected_updated_at: published_v2.updated_at,
|
||||
archived_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("archive is a lifecycle action");
|
||||
assert_eq!(archived.prompt.status(), PromptStatus::Archived);
|
||||
|
||||
let refused = publish(®istry, &workspace_id, &prompt_id, archived.updated_at).await;
|
||||
assert!(matches!(refused, Err(RegistryError::PromptNotDraft { .. })));
|
||||
|
||||
let after_archive = registry
|
||||
.get_published_prompt_version(&workspace_id, &prompt_id, 1)
|
||||
.await
|
||||
.expect("archive is not a security revoke");
|
||||
assert_eq!(&after_archive.definition, created.prompt.definition());
|
||||
let v2_after_archive = registry
|
||||
.get_published_prompt_version(&workspace_id, &prompt_id, 2)
|
||||
.await
|
||||
.expect("the second publication survives archive");
|
||||
assert_eq!(&v2_after_archive.definition, &edited_definition);
|
||||
|
||||
// Повторная публикация той же версии не создаёт вторую строку публикации.
|
||||
let repeat = publish(®istry, &workspace_id, &prompt_id, archived.updated_at).await;
|
||||
assert!(matches!(repeat, Err(RegistryError::PromptNotDraft { .. })));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story313_repeated_publish_of_the_same_version_conflicts_without_mutation() {
|
||||
let (registry, pool) = registry_pool("repeated_publish").await;
|
||||
let workspace_id = WorkspaceId::new(WS);
|
||||
let prompt_id = PromptId::new("prm_story313_repeat");
|
||||
let created = create_prompt(®istry, &workspace_id, &prompt_id).await;
|
||||
let published = publish(®istry, &workspace_id, &prompt_id, created.updated_at)
|
||||
.await
|
||||
.expect("first publish succeeds");
|
||||
let repeat = publish(®istry, &workspace_id, &prompt_id, published.updated_at).await;
|
||||
assert!(matches!(
|
||||
repeat,
|
||||
Err(RegistryError::PromptPublicationConflict { .. })
|
||||
));
|
||||
let rows: i64 = sqlx::query_scalar(
|
||||
"select count(*) from prompt_publications where prompt_id = $1 and version = 1",
|
||||
)
|
||||
.bind(prompt_id.as_str())
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.expect("publication rows are readable");
|
||||
assert_eq!(rows, 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story313_concurrent_publish_with_same_precondition_yields_one_publication() {
|
||||
let (registry, pool) = registry_pool("concurrent_publish").await;
|
||||
let workspace_id = WorkspaceId::new(WS);
|
||||
let prompt_id = PromptId::new("prm_story313_concurrent");
|
||||
let created = create_prompt(®istry, &workspace_id, &prompt_id).await;
|
||||
let (first, second) = tokio::join!(
|
||||
publish(®istry, &workspace_id, &prompt_id, created.updated_at),
|
||||
publish(®istry, &workspace_id, &prompt_id, created.updated_at)
|
||||
);
|
||||
let successes = usize::from(first.is_ok()) + usize::from(second.is_ok());
|
||||
assert_eq!(successes, 1, "exactly one publish may win the CAS race");
|
||||
let loser = if first.is_err() { first } else { second };
|
||||
assert!(matches!(
|
||||
loser,
|
||||
Err(RegistryError::PromptStaleRevision { .. })
|
||||
));
|
||||
let rows: i64 = sqlx::query_scalar(
|
||||
"select count(*) from prompt_publications where prompt_id = $1 and version = 1",
|
||||
)
|
||||
.bind(prompt_id.as_str())
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.expect("publication rows are readable");
|
||||
assert_eq!(rows, 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story313_database_guard_protects_published_definition_and_publication() {
|
||||
let (registry, pool) = registry_pool("definition_guard").await;
|
||||
let workspace_id = WorkspaceId::new(WS);
|
||||
let prompt_id = PromptId::new("prm_story313_guard");
|
||||
let created = create_prompt(®istry, &workspace_id, &prompt_id).await;
|
||||
publish(®istry, &workspace_id, &prompt_id, created.updated_at)
|
||||
.await
|
||||
.expect("publish succeeds");
|
||||
|
||||
let mutated = sqlx::query(
|
||||
"update prompt_messages set content = 'tampered'
|
||||
where workspace_id = $1 and prompt_id = $2 and version = 1",
|
||||
)
|
||||
.bind(WS)
|
||||
.bind(prompt_id.as_str())
|
||||
.execute(&pool)
|
||||
.await;
|
||||
assert!(mutated.is_err(), "published messages must be immutable");
|
||||
let removed = sqlx::query(
|
||||
"delete from prompt_arguments where workspace_id = $1 and prompt_id = $2 and version = 1",
|
||||
)
|
||||
.bind(WS)
|
||||
.bind(prompt_id.as_str())
|
||||
.execute(&pool)
|
||||
.await;
|
||||
assert!(removed.is_err(), "published arguments must be immutable");
|
||||
let rewritten = sqlx::query(
|
||||
"update prompt_publications set name = 'tampered'
|
||||
where workspace_id = $1 and prompt_id = $2 and version = 1",
|
||||
)
|
||||
.bind(WS)
|
||||
.bind(prompt_id.as_str())
|
||||
.execute(&pool)
|
||||
.await;
|
||||
assert!(rewritten.is_err(), "publication rows must be immutable");
|
||||
|
||||
// NEW-сторона guard: в опубликованную версию нельзя добавить новую строку
|
||||
// definition напрямую через SQL.
|
||||
let inserted_argument = sqlx::query(
|
||||
"insert into prompt_arguments
|
||||
(workspace_id, prompt_id, version, argument_name, argument_type, required,
|
||||
default_value, enumeration, position)
|
||||
values ($1, $2, 1, 'injected', 'string', false, null, null, 3)",
|
||||
)
|
||||
.bind(WS)
|
||||
.bind(prompt_id.as_str())
|
||||
.execute(&pool)
|
||||
.await;
|
||||
assert_immutable_guard_rejected(inserted_argument, "published Prompt version is immutable");
|
||||
let inserted_message = sqlx::query(
|
||||
"insert into prompt_messages (workspace_id, prompt_id, version, position, role, content)
|
||||
values ($1, $2, 1, 2, 'assistant', 'injected')",
|
||||
)
|
||||
.bind(WS)
|
||||
.bind(prompt_id.as_str())
|
||||
.execute(&pool)
|
||||
.await;
|
||||
assert_immutable_guard_rejected(inserted_message, "published Prompt version is immutable");
|
||||
|
||||
let exact = registry
|
||||
.get_published_prompt_version(&workspace_id, &prompt_id, 1)
|
||||
.await
|
||||
.expect("exact read still works");
|
||||
assert_eq!(&exact.definition, created.prompt.definition());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story313_exact_read_and_publish_are_workspace_scoped() {
|
||||
let (registry, pool) = registry_pool("scope").await;
|
||||
let own = WorkspaceId::new(WS);
|
||||
let other = WorkspaceId::new("ws_story313_other");
|
||||
let now = OffsetDateTime::now_utc();
|
||||
registry
|
||||
.create_workspace(CreateWorkspaceRequest {
|
||||
workspace: &Workspace {
|
||||
id: other.clone(),
|
||||
slug: "story313-other".to_owned(),
|
||||
display_name: "Story 3.13 other".to_owned(),
|
||||
status: WorkspaceStatus::Active,
|
||||
settings: json!({}),
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("second workspace is created");
|
||||
let prompt_id = PromptId::new("prm_story313_scope");
|
||||
let created = create_prompt(®istry, &own, &prompt_id).await;
|
||||
publish(®istry, &own, &prompt_id, created.updated_at)
|
||||
.await
|
||||
.expect("publish succeeds");
|
||||
|
||||
let hidden = registry
|
||||
.get_published_prompt_version(&other, &prompt_id, 1)
|
||||
.await;
|
||||
assert!(matches!(
|
||||
hidden,
|
||||
Err(RegistryError::PromptPublicationNotFound { .. })
|
||||
));
|
||||
let foreign_publish = publish(®istry, &other, &prompt_id, created.updated_at).await;
|
||||
assert!(matches!(
|
||||
foreign_publish,
|
||||
Err(RegistryError::PromptNotFound { .. })
|
||||
));
|
||||
let publications: i64 =
|
||||
sqlx::query_scalar("select count(*) from prompt_publications where prompt_id = $1")
|
||||
.bind(prompt_id.as_str())
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.expect("publication rows are readable");
|
||||
assert_eq!(publications, 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story313_agent_binding_is_exact_typed_and_published_snapshot_is_stable() {
|
||||
let (registry, pool) = registry_pool("agent_binding").await;
|
||||
let workspace_id = WorkspaceId::new(WS);
|
||||
let prompt_id = PromptId::new("prm_story313_binding");
|
||||
let created = create_prompt(®istry, &workspace_id, &prompt_id).await;
|
||||
let published = publish(®istry, &workspace_id, &prompt_id, created.updated_at)
|
||||
.await
|
||||
.expect("publish succeeds");
|
||||
let agent_id = create_draft_agent(®istry, &workspace_id, "agent_story313", "agent313").await;
|
||||
|
||||
let saved = save_prompt_bindings(®istry, &workspace_id, &agent_id, 1, &prompt_id, 1)
|
||||
.await
|
||||
.expect("exact published Prompt binding is accepted");
|
||||
assert_eq!(saved, 1);
|
||||
let version = registry
|
||||
.get_agent_version(&workspace_id, &agent_id, 1)
|
||||
.await
|
||||
.expect("agent version reads")
|
||||
.expect("agent version exists");
|
||||
assert_eq!(
|
||||
version.prompt_bindings,
|
||||
vec![AgentPromptBinding {
|
||||
prompt_id: prompt_id.clone(),
|
||||
prompt_version: 1,
|
||||
}]
|
||||
);
|
||||
|
||||
// Draft edit после binding не меняет закреплённую версию.
|
||||
registry
|
||||
.update_prompt_draft(UpdatePromptDraftRequest {
|
||||
workspace_id: workspace_id.clone(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition: prompt("Changed {{name}}"),
|
||||
expected_updated_at: published.updated_at,
|
||||
updated_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("draft edit after binding succeeds");
|
||||
let exact = registry
|
||||
.get_published_prompt_version(&workspace_id, &prompt_id, 1)
|
||||
.await
|
||||
.expect("binding keeps the exact published definition");
|
||||
assert_eq!(&exact.definition, created.prompt.definition());
|
||||
|
||||
// Agent publication атомарно включает binding и bump catalog_revision; повтор
|
||||
// уже опубликованной версии идемпотентен.
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &workspace_id,
|
||||
agent_id: &agent_id,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: None,
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("agent publishes with the exact Prompt snapshot");
|
||||
let summary = registry
|
||||
.get_agent_summary(&workspace_id, &agent_id)
|
||||
.await
|
||||
.expect("agent summary reads")
|
||||
.expect("agent exists");
|
||||
assert_eq!(summary.latest_published_version, Some(1));
|
||||
assert_eq!(summary.catalog_revision, 1);
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &workspace_id,
|
||||
agent_id: &agent_id,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: None,
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("repeated publish is idempotent");
|
||||
let repeated = registry
|
||||
.get_agent_summary(&workspace_id, &agent_id)
|
||||
.await
|
||||
.expect("agent summary reads")
|
||||
.expect("agent exists");
|
||||
assert_eq!(repeated.catalog_revision, 1, "no double catalog bump");
|
||||
|
||||
// После unpublish та же версия публикуется обычным путём: Agent снова
|
||||
// Published, revision растёт один раз, exact Prompt binding сохраняется.
|
||||
registry
|
||||
.unpublish_agent(&workspace_id, &agent_id, &OffsetDateTime::now_utc(), None)
|
||||
.await
|
||||
.expect("agent unpublishes");
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &workspace_id,
|
||||
agent_id: &agent_id,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: None,
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("republishing the same version after unpublish succeeds");
|
||||
let republished = registry
|
||||
.get_agent_summary(&workspace_id, &agent_id)
|
||||
.await
|
||||
.expect("agent summary reads")
|
||||
.expect("agent exists");
|
||||
assert_eq!(republished.catalog_revision, 3);
|
||||
let still_bound = registry
|
||||
.get_agent_version(&workspace_id, &agent_id, 1)
|
||||
.await
|
||||
.expect("agent version reads")
|
||||
.expect("agent version exists");
|
||||
assert_eq!(still_bound.prompt_bindings.len(), 1);
|
||||
|
||||
// Published Agent bindings иммутабельны и через прямой SQL.
|
||||
let rewritten = sqlx::query(
|
||||
"update agent_prompt_bindings set prompt_version = 2
|
||||
where agent_id = $1 and agent_version = 1",
|
||||
)
|
||||
.bind(agent_id.as_str())
|
||||
.execute(&pool)
|
||||
.await;
|
||||
assert!(rewritten.is_err(), "published Agent bindings are immutable");
|
||||
|
||||
// NEW-сторона guard: в опубликованную версию Agent нельзя добавить новую
|
||||
// привязку к другой опубликованной версии Prompt.
|
||||
let second_prompt_id = PromptId::new("prm_story313_binding_second");
|
||||
let second = create_prompt(®istry, &workspace_id, &second_prompt_id).await;
|
||||
publish(
|
||||
®istry,
|
||||
&workspace_id,
|
||||
&second_prompt_id,
|
||||
second.updated_at,
|
||||
)
|
||||
.await
|
||||
.expect("the second Prompt fixture publishes");
|
||||
let inserted = sqlx::query(
|
||||
"insert into agent_prompt_bindings
|
||||
(workspace_id, agent_id, agent_version, prompt_id, prompt_version)
|
||||
values ($1, $2, 1, $3, 1)",
|
||||
)
|
||||
.bind(WS)
|
||||
.bind(agent_id.as_str())
|
||||
.bind(second_prompt_id.as_str())
|
||||
.execute(&pool)
|
||||
.await;
|
||||
assert_immutable_guard_rejected(inserted, "published Agent Prompt bindings are immutable");
|
||||
|
||||
let removed =
|
||||
sqlx::query("delete from agent_prompt_bindings where agent_id = $1 and agent_version = 1")
|
||||
.bind(agent_id.as_str())
|
||||
.execute(&pool)
|
||||
.await;
|
||||
assert_immutable_guard_rejected(removed, "published Agent Prompt bindings are immutable");
|
||||
|
||||
let still_bound = registry
|
||||
.get_agent_version(&workspace_id, &agent_id, 1)
|
||||
.await
|
||||
.expect("agent version reads")
|
||||
.expect("agent version exists");
|
||||
assert_eq!(
|
||||
still_bound.prompt_bindings,
|
||||
vec![AgentPromptBinding {
|
||||
prompt_id: prompt_id.clone(),
|
||||
prompt_version: 1,
|
||||
}],
|
||||
"raw SQL must not change the published Agent snapshot"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story313_binding_to_unpublished_or_archived_prompt_is_refused() {
|
||||
let registry = registry("binding_refusals").await;
|
||||
let workspace_id = WorkspaceId::new(WS);
|
||||
let prompt_id = PromptId::new("prm_story313_refusals");
|
||||
let created = create_prompt(®istry, &workspace_id, &prompt_id).await;
|
||||
|
||||
// Ещё не опубликованный Prompt: exact версии 1 нет в prompt_publications.
|
||||
let unpublished = save_prompt_bindings(
|
||||
®istry,
|
||||
&workspace_id,
|
||||
&create_draft_agent(®istry, &workspace_id, "agent_313_a", "agent313a").await,
|
||||
1,
|
||||
&prompt_id,
|
||||
1,
|
||||
)
|
||||
.await;
|
||||
assert!(unpublished.is_err(), "unpublished version cannot be bound");
|
||||
|
||||
let published = publish(®istry, &workspace_id, &prompt_id, created.updated_at)
|
||||
.await
|
||||
.expect("publish succeeds");
|
||||
let agent_id = create_draft_agent(®istry, &workspace_id, "agent_313_b", "agent313b").await;
|
||||
save_prompt_bindings(®istry, &workspace_id, &agent_id, 1, &prompt_id, 1)
|
||||
.await
|
||||
.expect("published version binds");
|
||||
|
||||
registry
|
||||
.archive_prompt_draft(ArchivePromptRequest {
|
||||
workspace_id: workspace_id.clone(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
expected_updated_at: published.updated_at,
|
||||
archived_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("archive succeeds");
|
||||
|
||||
let archived =
|
||||
save_prompt_bindings(®istry, &workspace_id, &agent_id, 1, &prompt_id, 1).await;
|
||||
assert!(
|
||||
matches!(archived, Err(RegistryError::PromptArchived { .. })),
|
||||
"archived Prompt must refuse new bindings: {archived:?}"
|
||||
);
|
||||
let version = registry
|
||||
.get_agent_version(&workspace_id, &agent_id, 1)
|
||||
.await
|
||||
.expect("agent version reads")
|
||||
.expect("agent version exists");
|
||||
assert_eq!(
|
||||
version.prompt_bindings.len(),
|
||||
1,
|
||||
"a refused binding must not clear existing bindings"
|
||||
);
|
||||
}
|
||||
|
||||
/// Гонка «bind в Draft-версию Agent» ↔ «publish этой версии»: обе операции
|
||||
/// сериализуются на строке Agent, и опубликованный снимок не мутирует ни в одном
|
||||
/// из порядков — bind либо успевает до publish, либо уезжает в новую Draft.
|
||||
#[tokio::test]
|
||||
async fn story313_concurrent_bind_and_agent_publish_keep_the_publication_stable() {
|
||||
let (registry, pool) = registry_pool("bind_publish_race").await;
|
||||
let workspace_id = WorkspaceId::new(WS);
|
||||
let prompt_id = PromptId::new("prm_story313_race");
|
||||
let created = create_prompt(®istry, &workspace_id, &prompt_id).await;
|
||||
publish(®istry, &workspace_id, &prompt_id, created.updated_at)
|
||||
.await
|
||||
.expect("the Prompt fixture publishes");
|
||||
let agent_id =
|
||||
create_draft_agent(®istry, &workspace_id, "agent_313_race", "agent313race").await;
|
||||
let binding = AgentPromptBinding {
|
||||
prompt_id: prompt_id.clone(),
|
||||
prompt_version: 1,
|
||||
};
|
||||
|
||||
let publish_at = OffsetDateTime::now_utc();
|
||||
let (bound, published) = tokio::join!(
|
||||
save_prompt_bindings(®istry, &workspace_id, &agent_id, 1, &prompt_id, 1),
|
||||
registry.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &workspace_id,
|
||||
agent_id: &agent_id,
|
||||
version: 1,
|
||||
published_at: &publish_at,
|
||||
published_by: None,
|
||||
expected_state: None,
|
||||
})
|
||||
);
|
||||
published.expect("Agent publish serializes against the concurrent binding save");
|
||||
|
||||
let summary = registry
|
||||
.get_agent_summary(&workspace_id, &agent_id)
|
||||
.await
|
||||
.expect("agent summary reads")
|
||||
.expect("agent exists");
|
||||
assert_eq!(summary.latest_published_version, Some(1));
|
||||
|
||||
let published_v1 = registry
|
||||
.get_agent_version(&workspace_id, &agent_id, 1)
|
||||
.await
|
||||
.expect("agent version reads")
|
||||
.expect("version 1 exists");
|
||||
assert_eq!(published_v1.status, AgentStatus::Published);
|
||||
|
||||
match bound {
|
||||
// Bind ушёл первым: опубликованный снимок содержит эту привязку.
|
||||
Ok(1) => {
|
||||
assert_eq!(published_v1.prompt_bindings, vec![binding.clone()]);
|
||||
assert_eq!(summary.current_draft_version, 1);
|
||||
}
|
||||
// Publish ушёл первым: bind форкнут в новую Draft, published v1 не изменился.
|
||||
Ok(2) => {
|
||||
assert!(
|
||||
published_v1.prompt_bindings.is_empty(),
|
||||
"publish won the race, so the published v1 must stay empty: {published_v1:?}"
|
||||
);
|
||||
let draft_v2 = registry
|
||||
.get_agent_version(&workspace_id, &agent_id, 2)
|
||||
.await
|
||||
.expect("agent version reads")
|
||||
.expect("the forked Draft version exists");
|
||||
assert_eq!(draft_v2.status, AgentStatus::Draft);
|
||||
assert_eq!(draft_v2.prompt_bindings, vec![binding.clone()]);
|
||||
}
|
||||
other => panic!("unexpected concurrent binding outcome: {other:?}"),
|
||||
}
|
||||
|
||||
// Повторное чтение: опубликованный снимок не изменился после гонки.
|
||||
let replayed = registry
|
||||
.get_agent_version(&workspace_id, &agent_id, 1)
|
||||
.await
|
||||
.expect("agent version reads")
|
||||
.expect("version 1 exists");
|
||||
assert_eq!(replayed.prompt_bindings, published_v1.prompt_bindings);
|
||||
let rows: i64 = sqlx::query_scalar(
|
||||
"select count(*) from agent_prompt_bindings where agent_id = $1 and agent_version = 1",
|
||||
)
|
||||
.bind(agent_id.as_str())
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.expect("binding rows are readable");
|
||||
assert_eq!(
|
||||
rows,
|
||||
published_v1.prompt_bindings.len() as i64,
|
||||
"the published Agent snapshot must not gain or lose binding rows"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,886 @@
|
||||
//! BUILD-ONLY: проверки реестра Story 3.6 (AT-3.6-01/03, таргет P).
|
||||
//!
|
||||
//! Статус файла на стадии Dev ATDD: **не зарегистрирован** в `tests/integration.rs`
|
||||
//! (`mod integration { mod resource_drafts; }` добавляет BUILD), поэтому он не компилируется и
|
||||
//! не исполняется: `PostgresRegistry::create_resource_draft`/`update_resource_draft`/
|
||||
//! `resolve_resource_version` и миграция V16 ещё не существуют. Нулевая коллекция этого файла
|
||||
//! не является PASS.
|
||||
//!
|
||||
//! Минимальный будущий интерфейс (SPEC v4 §5, D-15):
|
||||
//! - `crank_registry::postgres::resource::{create_resource_draft, update_resource_draft,
|
||||
//! get_resource_draft, list_resource_drafts, resolve_resource_version}`;
|
||||
//! - `crank_registry::model::resource::{CreateResourceDraftRequest, UpdateResourceDraftRequest,
|
||||
//! ResourceDraftRecord, ResolvedResourceVersion}`, где оба мутирующих запроса получают
|
||||
//! `artifact: RegisteredArtifact` — доказательство уже зарегистрированных durable bytes
|
||||
//! (`ArtifactStore::put_registered` в сервисе), а не сырые bytes и не digest строкой:
|
||||
//! реестр получает durable metadata/owning ref и **не** становится владельцем записи файла
|
||||
//! (D-15 шаг 3 `ensure_blob`, D-19 «put» — точка сервиса);
|
||||
//! - `resource_versions` не имеет `updated_at`; CAS-precondition берётся из `artifact_sources`
|
||||
//! через существующий `get_source_in_transaction` (D-15 шаг 2);
|
||||
//! - таблицы V16 — по наброску SPEC §5.
|
||||
//!
|
||||
//! Фиксированные имена тестов (SPEC §2) должны появиться при регистрации без переименования.
|
||||
//! Каждый тест получает собственные PG-схему и приватный artifact root, поэтому положительные
|
||||
//! seed-ы не смешиваются между тестами и digest в них всегда соответствует реально
|
||||
//! зарегистрированным bytes (независимый оракул — `sha256_hex`).
|
||||
|
||||
use std::{
|
||||
fs,
|
||||
os::unix::fs::PermissionsExt,
|
||||
path::PathBuf,
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
};
|
||||
|
||||
use crank_artifacts::{ArtifactStore, RegisteredArtifact};
|
||||
use crank_core::ids::ResourceId;
|
||||
use crank_core::{Workspace, WorkspaceId, WorkspaceStatus};
|
||||
use crank_registry::model::resource::{
|
||||
CreateResourceDraftRequest, ResolvedResourceVersion, ResourceDraftRecord,
|
||||
UpdateResourceDraftRequest,
|
||||
};
|
||||
use crank_registry::{CreateWorkspaceRequest, PostgresRegistry};
|
||||
use serde_json::json;
|
||||
use sqlx::Row as _;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
const WORKSPACE_ID: &str = "ws_default";
|
||||
|
||||
mod resource_publications;
|
||||
mod resource_template;
|
||||
|
||||
static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct TestRoot(PathBuf);
|
||||
|
||||
impl TestRoot {
|
||||
fn new(name: &str) -> Self {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"crank-registry-resource-drafts-{name}-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT_ROOT.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
fs::create_dir(&path).expect("private artifact root must be creatable");
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o700))
|
||||
.expect("private artifact root must be 0700");
|
||||
Self(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestRoot {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::set_permissions(&self.0, fs::Permissions::from_mode(0o700));
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
struct Sandbox {
|
||||
registry: PostgresRegistry,
|
||||
store: ArtifactStore,
|
||||
_root: TestRoot,
|
||||
}
|
||||
|
||||
/// Изолированный стенд: своя PG-схема V16, свой приватный store, свой workspace.
|
||||
async fn sandbox(name: &str) -> Sandbox {
|
||||
let database_url = crank_test_support::postgres_schema_url(&format!("story36_{name}")).await;
|
||||
let pool = sqlx::PgPool::connect(&database_url)
|
||||
.await
|
||||
.expect("test schema must accept connections");
|
||||
crank_registry::MigrationAuthority::apply(&pool)
|
||||
.await
|
||||
.expect("V16 must be applicable");
|
||||
let registry = PostgresRegistry::connect(&database_url)
|
||||
.await
|
||||
.expect("registry must connect");
|
||||
let root = TestRoot::new(name);
|
||||
let store = ArtifactStore::open(root.0.clone()).expect("private artifact store must open");
|
||||
create_workspace(®istry).await;
|
||||
Sandbox {
|
||||
registry,
|
||||
store,
|
||||
_root: root,
|
||||
}
|
||||
}
|
||||
|
||||
async fn create_workspace(registry: &PostgresRegistry) {
|
||||
// V1 baseline уже сеет `ws_default`, поэтому фикстура не создаёт его повторно:
|
||||
// тесту нужен именно доступный workspace, а не вторая его копия.
|
||||
let workspace_id = WorkspaceId::new(WORKSPACE_ID);
|
||||
if registry
|
||||
.get_workspace(&workspace_id)
|
||||
.await
|
||||
.expect("workspace lookup must succeed")
|
||||
.is_some()
|
||||
{
|
||||
return;
|
||||
}
|
||||
let now = OffsetDateTime::now_utc();
|
||||
registry
|
||||
.create_workspace(CreateWorkspaceRequest {
|
||||
workspace: &Workspace {
|
||||
id: workspace_id,
|
||||
slug: "story36-registry".to_owned(),
|
||||
display_name: "Story 3.6 Registry".to_owned(),
|
||||
status: WorkspaceStatus::Active,
|
||||
settings: json!({}),
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("synthetic workspace must be created");
|
||||
}
|
||||
|
||||
/// Регистрирует bytes в приватном store и создаёт Draft, передавая реестру именно
|
||||
/// `RegisteredArtifact` (durable metadata/owning ref), а не сырые bytes.
|
||||
async fn seeded_draft(sandbox: &Sandbox) -> ResourceId {
|
||||
let bytes = b"registry payload";
|
||||
let artifact = sandbox
|
||||
.store
|
||||
.put_registered(bytes)
|
||||
.expect("fixture bytes must be registered durably");
|
||||
let request = CreateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: ResourceId::new("res_story36_registry"),
|
||||
uri: "crank://registry/draft".to_owned(),
|
||||
name: "registry_draft".to_owned(),
|
||||
description: String::new(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
artifact,
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
};
|
||||
sandbox
|
||||
.registry
|
||||
.create_resource_draft(request)
|
||||
.await
|
||||
.expect("draft must be created");
|
||||
ResourceId::new("res_story36_registry")
|
||||
}
|
||||
|
||||
fn registered(sandbox: &Sandbox, bytes: &[u8]) -> RegisteredArtifact {
|
||||
sandbox
|
||||
.store
|
||||
.put_registered(bytes)
|
||||
.expect("fixture bytes must be registered durably")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story36_at01_resource_and_version_roundtrip_through_postgres() {
|
||||
let sandbox = sandbox("at01_roundtrip").await;
|
||||
let resource_id = seeded_draft(&sandbox).await;
|
||||
|
||||
let record: ResourceDraftRecord = sandbox
|
||||
.registry
|
||||
.get_resource_draft(WORKSPACE_ID, &resource_id)
|
||||
.await
|
||||
.expect("draft must be readable");
|
||||
assert_eq!(record.resource.uri, "crank://registry/draft");
|
||||
assert_eq!(record.resource.kind, "text");
|
||||
assert_eq!(record.version.version, 1);
|
||||
assert_eq!(record.version.sensitivity, "internal");
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>("select count(*) from resources")
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("resources must be queryable"),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>("select count(*) from resource_versions")
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("resource_versions must be queryable"),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story36_at03_exact_digest_and_metadata_roundtrip() {
|
||||
let sandbox = sandbox("at03_digest").await;
|
||||
let resource_id = seeded_draft(&sandbox).await;
|
||||
|
||||
let resolved = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, 1)
|
||||
.await
|
||||
.expect("version must resolve");
|
||||
// Независимый оракул: digest считается тестом из тех же bytes, а не берётся у реестра.
|
||||
let digest = sha256_hex(b"registry payload");
|
||||
assert_eq!(
|
||||
resolved.snapshot.version.digest, digest,
|
||||
"digest must match independently computed SHA-256"
|
||||
);
|
||||
assert_eq!(resolved.snapshot.version.size_bytes, 16);
|
||||
assert_eq!(resolved.snapshot.version.mime_type, "text/plain");
|
||||
|
||||
// Повторная регистрация тех же bytes переиспользует blob, но создаёт новую version-строку.
|
||||
let updated = sandbox
|
||||
.registry
|
||||
.update_resource_draft(UpdateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: resource_id.clone(),
|
||||
description: String::new(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
expected_updated_at: resolved.snapshot.resource.updated_at,
|
||||
artifact: registered(&sandbox, b"registry payload"),
|
||||
})
|
||||
.await
|
||||
.expect("update must succeed");
|
||||
assert_eq!(updated.version, 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story36_at03_corrupt_missing_and_mismatched_artifact_fail_closed() {
|
||||
let sandbox = sandbox("at03_integrity").await;
|
||||
let resource_id = seeded_draft(&sandbox).await;
|
||||
|
||||
// рассинхронизация metadata/digest/size обязана давать фиксированную ошибку без bytes
|
||||
sqlx::query("update artifact_blobs set size_bytes = size_bytes + 1")
|
||||
.execute(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("fixture mutation must apply");
|
||||
let error = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, 1)
|
||||
.await
|
||||
.expect_err("mismatched artifact metadata must fail closed");
|
||||
assert_eq!(error.code(), "resource_artifact_integrity");
|
||||
}
|
||||
|
||||
/// F7 (TL run109 CODE-REVIEW): полное наблюдаемое состояние отката duplicate-create.
|
||||
///
|
||||
/// Считаются **все четыре** отношения (`resources`, `resource_versions`,
|
||||
/// `artifact_sources`, `artifact_blobs`), фиксируются строки принятого Draft и
|
||||
/// owning-ссылки, а не только «сколько ресурсов стало». Допускаемые AD-10 orphan
|
||||
/// bytes лежат в файловом store вне БД, поэтому строк отказ добавлять не должен.
|
||||
async fn accepted_snapshot(pool: &sqlx::PgPool) -> Vec<String> {
|
||||
let mut snapshot = Vec::new();
|
||||
let counts = sqlx::query_as::<_, (i64, i64, i64, i64, i64)>(
|
||||
"select (select count(*) from resources),
|
||||
(select count(*) from resource_versions),
|
||||
(select count(*) from artifact_sources),
|
||||
(select count(*) from artifact_blobs),
|
||||
(select count(*) from artifact_sources where lifecycle = 'active')",
|
||||
)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.expect("the four V16 relations must stay countable");
|
||||
snapshot.push(format!("counts={counts:?}"));
|
||||
|
||||
let resources = sqlx::query_as::<
|
||||
_,
|
||||
(
|
||||
String,
|
||||
String,
|
||||
String,
|
||||
String,
|
||||
String,
|
||||
String,
|
||||
String,
|
||||
String,
|
||||
),
|
||||
>(
|
||||
"select resource_id, uri, name, status, kind, description,
|
||||
current_draft_version::text,
|
||||
created_at::text || '|' || updated_at::text
|
||||
from resources order by resource_id",
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.expect("the accepted resource rows must be readable");
|
||||
for row in resources {
|
||||
snapshot.push(format!("resource={row:?}"));
|
||||
}
|
||||
|
||||
let versions = sqlx::query_as::<
|
||||
_,
|
||||
(
|
||||
String,
|
||||
i32,
|
||||
String,
|
||||
String,
|
||||
i64,
|
||||
String,
|
||||
String,
|
||||
String,
|
||||
String,
|
||||
),
|
||||
>(
|
||||
"select resource_id, version, kind, mime_type, size_bytes, digest, sensitivity,
|
||||
artifact_source_id,
|
||||
created_at::text || '|' || coalesce(superseded_at::text, '<current>')
|
||||
from resource_versions order by resource_id, version",
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.expect("the accepted version rows must be readable");
|
||||
for row in versions {
|
||||
snapshot.push(format!("version={row:?}"));
|
||||
}
|
||||
|
||||
let refs = sqlx::query_as::<_, (String, String, String, String, String, String, String)>(
|
||||
"select source_id, workspace_id, lifecycle, blob_digest, mime_type, sensitivity,
|
||||
created_at::text || '|' || coalesce(detached_at::text, '<attached>')
|
||||
from artifact_sources order by source_id",
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.expect("owning references must be readable");
|
||||
for row in refs {
|
||||
snapshot.push(format!("ref={row:?}"));
|
||||
}
|
||||
snapshot
|
||||
}
|
||||
|
||||
/// R3/F7: принятая версия и её bytes обязаны читаться **теми же** данными сразу
|
||||
/// после каждого отказа, а не только после всей пары отказов: сравнивается полный
|
||||
/// resolved-снимок версии и фактически прочитанные bytes по его же ссылке.
|
||||
async fn assert_accepted_version_intact(
|
||||
sandbox: &Sandbox,
|
||||
resource_id: &ResourceId,
|
||||
before: &ResolvedResourceVersion,
|
||||
) {
|
||||
let after = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, resource_id, before.snapshot.version.version)
|
||||
.await
|
||||
.expect("the accepted version must resolve right after the refusal");
|
||||
assert_eq!(
|
||||
after.snapshot, before.snapshot,
|
||||
"the accepted Draft card metadata (identifiers, pointer, version, description, \
|
||||
timestamps, digest/size/MIME/sensitivity and source binding) must be unchanged right \
|
||||
after the refusal (F7)"
|
||||
);
|
||||
assert_eq!(
|
||||
sandbox
|
||||
.store
|
||||
.read(&after.artifact_ref)
|
||||
.expect("the previously accepted bytes must stay readable right after the refusal"),
|
||||
b"registry payload".to_vec(),
|
||||
"the previously accepted bytes must stay readable and exact right after the refusal (F7)"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story36_at03_rollback_leaves_no_accepted_resource_or_owning_ref() {
|
||||
let sandbox = sandbox("at03_rollback").await;
|
||||
let resource_id = seeded_draft(&sandbox).await;
|
||||
|
||||
// «До»: полное состояние принятого Draft, включая все четыре отношения.
|
||||
let before = accepted_snapshot(sandbox.registry.pool()).await;
|
||||
let resolved_before = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, 1)
|
||||
.await
|
||||
.expect("the accepted version must resolve before the duplicates");
|
||||
assert_eq!(
|
||||
resolved_before.snapshot.version.digest,
|
||||
sha256_hex(b"registry payload")
|
||||
);
|
||||
|
||||
// duplicate uri с **другими** bytes (put содержимого мог состояться, orphan bytes
|
||||
// допустимы, AD-10); принятых строк быть не должно.
|
||||
let duplicate_uri = CreateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: ResourceId::new("res_story36_registry_dup"),
|
||||
uri: "crank://registry/draft".to_owned(),
|
||||
name: "registry_other".to_owned(),
|
||||
description: String::new(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
artifact: registered(&sandbox, b"other payload"),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
};
|
||||
let error = sandbox
|
||||
.registry
|
||||
.create_resource_draft(duplicate_uri)
|
||||
.await
|
||||
.expect_err("duplicate uri must be rejected");
|
||||
assert_eq!(error.code(), "resource_uri_duplicate");
|
||||
// Наблюдение неизменности **сразу** после отказа по uri (TL run111): не только
|
||||
// после пары отказов, иначе «второй отказ откатился» маскировал бы первый.
|
||||
let after_uri = accepted_snapshot(sandbox.registry.pool()).await;
|
||||
assert_eq!(
|
||||
after_uri, before,
|
||||
"a duplicate uri must leave all four relations and the accepted Draft exactly as they \
|
||||
were, observed right after that refusal (F7)"
|
||||
);
|
||||
assert_accepted_version_intact(&sandbox, &resource_id, &resolved_before).await;
|
||||
|
||||
// duplicate name: тот же единственный нарушенный фактор, но по другой колонке.
|
||||
let duplicate_name = CreateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: ResourceId::new("res_story36_registry_dup_name"),
|
||||
uri: "crank://registry/other".to_owned(),
|
||||
name: "registry_draft".to_owned(),
|
||||
description: String::new(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
artifact: registered(&sandbox, b"third payload"),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
};
|
||||
let error = sandbox
|
||||
.registry
|
||||
.create_resource_draft(duplicate_name)
|
||||
.await
|
||||
.expect_err("duplicate name must be rejected");
|
||||
assert_eq!(error.code(), "resource_name_duplicate");
|
||||
// Такое же отдельное наблюдение после отказа по name.
|
||||
let after_name = accepted_snapshot(sandbox.registry.pool()).await;
|
||||
assert_eq!(
|
||||
after_name, before,
|
||||
"a duplicate name must leave all four relations and the accepted Draft exactly as they \
|
||||
were, observed right after that refusal (F7)"
|
||||
);
|
||||
assert_accepted_version_intact(&sandbox, &resource_id, &resolved_before).await;
|
||||
|
||||
// «После»: ни одно из четырёх отношений, ни текущий указатель/версия/metadata/
|
||||
// timestamps/owning-ссылка не изменились.
|
||||
let after = accepted_snapshot(sandbox.registry.pool()).await;
|
||||
assert_eq!(
|
||||
after, before,
|
||||
"each duplicate create must leave all four relations and the accepted Draft exactly \
|
||||
as they were (F7)"
|
||||
);
|
||||
|
||||
// И старые bytes по-прежнему читаются теми же (не новыми) bytes.
|
||||
assert_accepted_version_intact(&sandbox, &resource_id, &resolved_before).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story36_at03_update_supersedes_before_insert_and_switches_pointer() {
|
||||
let sandbox = sandbox("at03_supersede").await;
|
||||
let resource_id = seeded_draft(&sandbox).await;
|
||||
let resolved = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, 1)
|
||||
.await
|
||||
.expect("version must resolve");
|
||||
|
||||
sandbox
|
||||
.registry
|
||||
.update_resource_draft(UpdateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: resource_id.clone(),
|
||||
description: "second".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "public".to_owned(),
|
||||
expected_updated_at: resolved.snapshot.resource.updated_at,
|
||||
artifact: registered(&sandbox, b"second payload"),
|
||||
})
|
||||
.await
|
||||
.expect("update must succeed");
|
||||
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>(
|
||||
"select count(*) from resource_versions where superseded_at is null",
|
||||
)
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("resource_versions must be queryable"),
|
||||
1,
|
||||
"exactly one current draft version after update"
|
||||
);
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i32>(
|
||||
"select current_draft_version from resources where resource_id = $1",
|
||||
)
|
||||
.bind(resource_id.as_str())
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("resources must be queryable"),
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story36_at03_update_rollback_after_supersede_restores_previous_current_version() {
|
||||
let sandbox = sandbox("at03_update_rollback").await;
|
||||
let resource_id = seeded_draft(&sandbox).await;
|
||||
let resolved = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, 1)
|
||||
.await
|
||||
.expect("version must resolve");
|
||||
|
||||
// repository вызывается напрямую, ниже доменной валидации: отказ наступает уже ПОСЛЕ шага
|
||||
// пометки прежней версии (CHECK `resources_description_len` отвергает 1025 байт).
|
||||
let error = sandbox
|
||||
.registry
|
||||
.update_resource_draft(UpdateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: resource_id.clone(),
|
||||
description: "d".repeat(1025),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
expected_updated_at: resolved.snapshot.resource.updated_at,
|
||||
artifact: registered(&sandbox, b"third payload"),
|
||||
})
|
||||
.await
|
||||
.expect_err("DB CHECK must reject the oversized description");
|
||||
assert_eq!(error.code(), "resource_storage_unavailable");
|
||||
|
||||
// Откат обязан вернуть прежнюю версию в состояние «единственная текущая».
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>(
|
||||
"select count(*) from resource_versions where superseded_at is null",
|
||||
)
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("resource_versions must be queryable"),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>(
|
||||
"select count(*) from artifact_sources where lifecycle = 'active' and detached_at is null",
|
||||
)
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("artifact_sources must be queryable"),
|
||||
1,
|
||||
"the previous owning reference must stay active"
|
||||
);
|
||||
}
|
||||
|
||||
/// Независимо посчитанный digest (оракул не берётся из реализации).
|
||||
fn sha256_hex(bytes: &[u8]) -> String {
|
||||
use std::fmt::Write as _;
|
||||
let digest = sha256(bytes);
|
||||
let mut hex = String::with_capacity(64);
|
||||
for byte in digest {
|
||||
write!(&mut hex, "{byte:02x}").expect("hex formatting");
|
||||
}
|
||||
hex
|
||||
}
|
||||
|
||||
fn sha256(bytes: &[u8]) -> [u8; 32] {
|
||||
// Независимое вычисление: используется уже объявленная зависимость крейты (`sha2.workspace`),
|
||||
// новая зависимость не вводится.
|
||||
use sha2::{Digest as _, Sha256};
|
||||
Sha256::digest(bytes).into()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// P5 (affected ATDD до исправления): полные итоги строк и прежние bytes после
|
||||
// отката позднего UPDATE, плюс положительный контроль следующего update.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async fn count(sandbox: &Sandbox, sql: &'static str) -> i64 {
|
||||
sqlx::query_scalar::<_, i64>(sql)
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("row totals must be queryable")
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct RowTotals {
|
||||
resources: i64,
|
||||
versions: i64,
|
||||
owning_refs: i64,
|
||||
blobs: i64,
|
||||
}
|
||||
|
||||
impl RowTotals {
|
||||
async fn observe(sandbox: &Sandbox) -> Self {
|
||||
Self {
|
||||
resources: count(sandbox, "select count(*) from resources").await,
|
||||
versions: count(sandbox, "select count(*) from resource_versions").await,
|
||||
owning_refs: count(sandbox, "select count(*) from artifact_sources").await,
|
||||
blobs: count(sandbox, "select count(*) from artifact_blobs").await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Точное состояние текущей версии Draft и её owning-ссылки.
|
||||
///
|
||||
/// Наблюдается повторным чтением (не из закешированных значений) и сравнивается целиком:
|
||||
/// указатель, ссылка, digest/size/MIME/sensitivity, timestamps и metadata (R-D).
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct DraftSnapshot {
|
||||
version: i32,
|
||||
digest: String,
|
||||
size_bytes: i64,
|
||||
mime_type: String,
|
||||
sensitivity: String,
|
||||
artifact_source_id: String,
|
||||
version_created_at: String,
|
||||
superseded_is_null: bool,
|
||||
current_draft_version: i32,
|
||||
resource_updated_at: String,
|
||||
description: String,
|
||||
status: String,
|
||||
source_lifecycle: String,
|
||||
source_digest: String,
|
||||
source_detached: bool,
|
||||
}
|
||||
|
||||
impl DraftSnapshot {
|
||||
async fn observe(sandbox: &Sandbox, resource_id: &ResourceId) -> Self {
|
||||
let row = sqlx::query(
|
||||
"select v.version, v.digest, v.size_bytes, v.mime_type, v.sensitivity,
|
||||
v.artifact_source_id, v.created_at::text as version_created_at,
|
||||
(v.superseded_at is null) as superseded_is_null,
|
||||
r.current_draft_version, r.updated_at::text as resource_updated_at,
|
||||
r.description, r.status,
|
||||
s.lifecycle as source_lifecycle, s.blob_digest as source_digest,
|
||||
(s.detached_at is not null) as source_detached
|
||||
from resource_versions v
|
||||
join resources r
|
||||
on r.workspace_id = v.workspace_id and r.resource_id = v.resource_id
|
||||
join artifact_sources s
|
||||
on s.workspace_id = v.workspace_id and s.source_id = v.artifact_source_id
|
||||
where v.workspace_id = $1
|
||||
and v.resource_id = $2
|
||||
and v.version = r.current_draft_version",
|
||||
)
|
||||
.bind(WORKSPACE_ID)
|
||||
.bind(resource_id.as_str())
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("the current Draft version and its owning reference must be observable");
|
||||
Self {
|
||||
version: row.get("version"),
|
||||
digest: row.get("digest"),
|
||||
size_bytes: row.get("size_bytes"),
|
||||
mime_type: row.get("mime_type"),
|
||||
sensitivity: row.get("sensitivity"),
|
||||
artifact_source_id: row.get("artifact_source_id"),
|
||||
version_created_at: row.get("version_created_at"),
|
||||
superseded_is_null: row.get("superseded_is_null"),
|
||||
current_draft_version: row.get("current_draft_version"),
|
||||
resource_updated_at: row.get("resource_updated_at"),
|
||||
description: row.get("description"),
|
||||
status: row.get("status"),
|
||||
source_lifecycle: row.get("source_lifecycle"),
|
||||
source_digest: row.get("source_digest"),
|
||||
source_detached: row.get("source_detached"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Состояние конкретной owning-ссылки по её `source_id`.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct SourceState {
|
||||
lifecycle: String,
|
||||
digest: String,
|
||||
detached: bool,
|
||||
}
|
||||
|
||||
async fn source_state(sandbox: &Sandbox, source_id: &str) -> SourceState {
|
||||
let row = sqlx::query(
|
||||
"select lifecycle, blob_digest, (detached_at is not null) as detached
|
||||
from artifact_sources
|
||||
where workspace_id = $1 and source_id = $2",
|
||||
)
|
||||
.bind(WORKSPACE_ID)
|
||||
.bind(source_id)
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("the owning reference must be observable by its source_id");
|
||||
SourceState {
|
||||
lifecycle: row.get("lifecycle"),
|
||||
digest: row.get("blob_digest"),
|
||||
detached: row.get("detached"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story36_at03_update_rollback_preserves_totals_and_old_bytes() {
|
||||
let sandbox = sandbox("at03_rollback_totals").await;
|
||||
let resource_id = seeded_draft(&sandbox).await;
|
||||
let resolved = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, 1)
|
||||
.await
|
||||
.expect("version must resolve");
|
||||
|
||||
let before = RowTotals::observe(&sandbox).await;
|
||||
let before_snapshot = DraftSnapshot::observe(&sandbox, &resource_id).await;
|
||||
let old_ref = resolved.artifact_ref.clone();
|
||||
let bytes_before_refusal = sandbox
|
||||
.store
|
||||
.read(&old_ref)
|
||||
.expect("old bytes must be readable before the rejected update");
|
||||
|
||||
// repository вызывается напрямую, ниже доменной валидации: отказ наступает уже ПОСЛЕ шага
|
||||
// пометки прежней версии (CHECK `resources_description_len` отвергает 1025 байт).
|
||||
let error = sandbox
|
||||
.registry
|
||||
.update_resource_draft(UpdateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: resource_id.clone(),
|
||||
description: "d".repeat(1025),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
expected_updated_at: resolved.snapshot.resource.updated_at,
|
||||
artifact: registered(&sandbox, b"second payload"),
|
||||
})
|
||||
.await
|
||||
.expect_err("the late UPDATE must be refused by the DB CHECK");
|
||||
assert_eq!(error.code(), "resource_storage_unavailable");
|
||||
|
||||
// (1) Полные итоги ВСЕХ участвующих классов строк не изменились (не только «активных»).
|
||||
let after = RowTotals::observe(&sandbox).await;
|
||||
assert_eq!(
|
||||
after, before,
|
||||
"a rolled back update must not change resource/version/owning/blob row totals"
|
||||
);
|
||||
|
||||
// (2) Прежняя версия снова единственная текущая; её ссылка активна; указатель и timestamp не двигались.
|
||||
let current = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, 1)
|
||||
.await
|
||||
.expect("the previous version must remain resolvable");
|
||||
assert_eq!(current.snapshot.version.version, 1);
|
||||
assert_eq!(
|
||||
current.snapshot.version.digest,
|
||||
resolved.snapshot.version.digest
|
||||
);
|
||||
assert_eq!(
|
||||
current.snapshot.resource.updated_at, resolved.snapshot.resource.updated_at,
|
||||
"the optimistic-precondition timestamp must not move on rollback"
|
||||
);
|
||||
// Повторное чтение ПОСЛЕ отказа через тот же exact ref: oracle не доверяет
|
||||
// закешированному до отказа Vec (R-D).
|
||||
let bytes_after_refusal = sandbox
|
||||
.store
|
||||
.read(&old_ref)
|
||||
.expect("the previous bytes must stay readable through the same artifact reference");
|
||||
assert_eq!(
|
||||
bytes_after_refusal, bytes_before_refusal,
|
||||
"a rejected update must not touch the content of the previous version"
|
||||
);
|
||||
assert_eq!(bytes_after_refusal, b"registry payload");
|
||||
assert_eq!(
|
||||
sha256_hex(&bytes_after_refusal),
|
||||
current.snapshot.version.digest,
|
||||
"the re-read bytes must still match the recorded digest of the previous version"
|
||||
);
|
||||
// Полное состояние (ссылка, указатель, timestamps, metadata) не изменилось.
|
||||
let after_snapshot = DraftSnapshot::observe(&sandbox, &resource_id).await;
|
||||
assert_eq!(
|
||||
after_snapshot, before_snapshot,
|
||||
"a rolled back update must not change the current version, its reference, timestamps or metadata"
|
||||
);
|
||||
assert_eq!(
|
||||
count(
|
||||
&sandbox,
|
||||
"select count(*) from resource_versions where superseded_at is null"
|
||||
)
|
||||
.await,
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
count(
|
||||
&sandbox,
|
||||
"select count(*) from artifact_sources where lifecycle = 'active' and detached_at is null"
|
||||
)
|
||||
.await,
|
||||
1,
|
||||
"the previous owning reference must stay active and undetached"
|
||||
);
|
||||
assert_eq!(
|
||||
count(
|
||||
&sandbox,
|
||||
"select count(*) from resources where current_draft_version = 1"
|
||||
)
|
||||
.await,
|
||||
1,
|
||||
"the current pointer must still point at version 1"
|
||||
);
|
||||
|
||||
// (3) Положительный контроль: следующий корректный update отсоединяет старую ссылку и активирует новую.
|
||||
sandbox
|
||||
.registry
|
||||
.update_resource_draft(UpdateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: resource_id.clone(),
|
||||
description: "second".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "public".to_owned(),
|
||||
expected_updated_at: resolved.snapshot.resource.updated_at,
|
||||
artifact: registered(&sandbox, b"second payload"),
|
||||
})
|
||||
.await
|
||||
.expect("a fresh valid update after the rollback must succeed");
|
||||
|
||||
assert_eq!(RowTotals::observe(&sandbox).await.versions, 2);
|
||||
assert_eq!(RowTotals::observe(&sandbox).await.owning_refs, 2);
|
||||
// Точные роли ссылок: прежняя стала detached и сохранила свой digest, новая — active (R-D).
|
||||
let superseded_source = source_state(&sandbox, &before_snapshot.artifact_source_id).await;
|
||||
assert_eq!(
|
||||
superseded_source.lifecycle, "detached",
|
||||
"the superseded version's reference must be detached"
|
||||
);
|
||||
assert!(superseded_source.detached);
|
||||
assert_eq!(
|
||||
superseded_source.digest, before_snapshot.source_digest,
|
||||
"the detached reference must keep the exact digest of the previous version"
|
||||
);
|
||||
let new_snapshot = DraftSnapshot::observe(&sandbox, &resource_id).await;
|
||||
assert_eq!(new_snapshot.version, 2);
|
||||
assert_eq!(new_snapshot.current_draft_version, 2);
|
||||
assert_ne!(
|
||||
new_snapshot.artifact_source_id, before_snapshot.artifact_source_id,
|
||||
"an accepted update must switch the current version to a new owning reference"
|
||||
);
|
||||
assert_eq!(new_snapshot.source_lifecycle, "active");
|
||||
assert!(!new_snapshot.source_detached);
|
||||
assert_eq!(new_snapshot.digest, sha256_hex(b"second payload"));
|
||||
assert_eq!(new_snapshot.source_digest, new_snapshot.digest);
|
||||
assert_eq!(new_snapshot.description, "second");
|
||||
assert_eq!(new_snapshot.sensitivity, "public");
|
||||
assert!(new_snapshot.superseded_is_null);
|
||||
assert_eq!(
|
||||
count(
|
||||
&sandbox,
|
||||
"select count(*) from resource_versions where superseded_at is null"
|
||||
)
|
||||
.await,
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
count(
|
||||
&sandbox,
|
||||
"select count(*) from artifact_sources where lifecycle = 'active' and detached_at is null"
|
||||
)
|
||||
.await,
|
||||
1,
|
||||
"exactly one live owning reference after a successful update"
|
||||
);
|
||||
assert_eq!(
|
||||
count(
|
||||
&sandbox,
|
||||
"select count(*) from artifact_sources where lifecycle = 'detached' and detached_at is not null"
|
||||
)
|
||||
.await,
|
||||
1,
|
||||
"the superseded version's reference must be detached with a timestamp"
|
||||
);
|
||||
assert_eq!(
|
||||
count(
|
||||
&sandbox,
|
||||
"select count(*) from resources where current_draft_version = 2"
|
||||
)
|
||||
.await,
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
// Остаток R-D (P5) вынесен в подмодуль: health-правило ограничивает файл 1000 строками,
|
||||
// а прежние фикстуры (`sandbox`/`seeded_draft`/`RowTotals`/`DraftSnapshot`) переиспользуются.
|
||||
#[path = "resource_drafts/p5_remnant.rs"]
|
||||
mod p5_remnant;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// BUILD obligations, которые этот файл НЕ подтверждает (не считать покрытием по именам тестов)
|
||||
// ---------------------------------------------------------------------------
|
||||
// - `MembershipRole`/workspace access здесь не проверяется: это уровень HTTP-сервиса (таргет A).
|
||||
// - `resource_versions.digest == artifact_sources.blob_digest` и прочие metadata-сверки чтения
|
||||
// проверяются только частично (см. `story36_at03_corrupt_missing_and_mismatched_artifact_fail_closed`);
|
||||
// полная матрица рассинхронизаций digest/size/MIME/sensitivity/lifecycle — обязательство BUILD.
|
||||
@@ -0,0 +1,598 @@
|
||||
//! Остаток пакета P5 (R-D) для таргета P: ранее разрешённый объём, который не был
|
||||
//! выполнен в run100/run102 и прямо возвращён TL run103:35 (Published-снимок после
|
||||
//! реального редактирования черновика, однофакторная integrity-матрица на durable
|
||||
//! seed-ах, целочисленные границы версии и детерминированного `source_id`).
|
||||
//!
|
||||
//! Модуль подключается из `tests/integration/resource_drafts.rs` и использует те же
|
||||
//! приватные фикстуры (`sandbox`, `seeded_draft`, `registered`): рабочая копия
|
||||
//! разбита на подмодуль, потому что health-правило ограничивает файл 1000 строками.
|
||||
//! Физическое чтение байт здесь идёт через `ArtifactStore::read` по точному
|
||||
//! `artifact_ref`, поэтому digest/bytes сверяются независимым оракулом.
|
||||
|
||||
use super::{
|
||||
DraftSnapshot, RowTotals, Sandbox, WORKSPACE_ID, count, registered, sandbox, seeded_draft,
|
||||
sha256_hex, source_state,
|
||||
};
|
||||
use crank_core::WorkspaceId;
|
||||
use crank_core::ids::ResourceId;
|
||||
use crank_registry::model::resource::{
|
||||
CreateResourceDraftRequest, ResolvedResourceVersion, UpdateResourceDraftRequest,
|
||||
};
|
||||
use sqlx::Row as _;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
const ORIGINAL_BYTES: &[u8] = b"registry payload";
|
||||
const EDITED_BYTES: &[u8] = b"registry payload v2";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// R-D (1): реальное редактирование черновика обязано сохранить ранее полученный
|
||||
// Published-снимок версии байт-в-байт (metadata/digest/version) и её bytes.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Metadata-снимок конкретной версии и её owning-ссылки (без времени замены:
|
||||
/// `superseded_at` — ожидаемый эффект редактирования, а не часть снимка).
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct PublishedRow {
|
||||
version: i32,
|
||||
kind: String,
|
||||
mime_type: String,
|
||||
size_bytes: i64,
|
||||
digest: String,
|
||||
sensitivity: String,
|
||||
created_at: String,
|
||||
artifact_source_id: String,
|
||||
source_digest: String,
|
||||
source_mime_type: String,
|
||||
source_sensitivity: String,
|
||||
}
|
||||
|
||||
impl PublishedRow {
|
||||
async fn observe(sandbox: &Sandbox, resource_id: &ResourceId, version: i32) -> Self {
|
||||
let row = sqlx::query(
|
||||
"select v.version, v.kind, v.mime_type, v.size_bytes, v.digest, v.sensitivity,
|
||||
v.created_at::text as created_at, v.artifact_source_id,
|
||||
s.blob_digest as source_digest, s.mime_type as source_mime_type,
|
||||
s.sensitivity as source_sensitivity
|
||||
from resource_versions v
|
||||
join artifact_sources s
|
||||
on s.workspace_id = v.workspace_id and s.source_id = v.artifact_source_id
|
||||
where v.workspace_id = $1 and v.resource_id = $2 and v.version = $3",
|
||||
)
|
||||
.bind(WORKSPACE_ID)
|
||||
.bind(resource_id.as_str())
|
||||
.bind(version)
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("the published version row and its owning reference must be observable");
|
||||
Self {
|
||||
version: row.get("version"),
|
||||
kind: row.get("kind"),
|
||||
mime_type: row.get("mime_type"),
|
||||
size_bytes: row.get("size_bytes"),
|
||||
digest: row.get("digest"),
|
||||
sensitivity: row.get("sensitivity"),
|
||||
created_at: row.get("created_at"),
|
||||
artifact_source_id: row.get("artifact_source_id"),
|
||||
source_digest: row.get("source_digest"),
|
||||
source_mime_type: row.get("source_mime_type"),
|
||||
source_sensitivity: row.get("source_sensitivity"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Стала ли версия заменённой (поле вне снимка, но часть контракта обновления).
|
||||
async fn superseded(sandbox: &Sandbox, resource_id: &ResourceId, version: i32) -> bool {
|
||||
sqlx::query_scalar::<_, bool>(
|
||||
"select superseded_at is not null from resource_versions
|
||||
where workspace_id = $1 and resource_id = $2 and version = $3",
|
||||
)
|
||||
.bind(WORKSPACE_ID)
|
||||
.bind(resource_id.as_str())
|
||||
.bind(version)
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("the superseding state of the version must be observable")
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story36_at01_real_draft_edit_preserves_the_previously_resolved_published_snapshot() {
|
||||
let sandbox = sandbox("at01_published_snapshot").await;
|
||||
let resource_id = seeded_draft(&sandbox).await;
|
||||
|
||||
// Published-снимок берётся до редактирования — это и есть «ранее полученное»
|
||||
// представление опубликованной версии (модель версии без path/filename/source-id).
|
||||
let published: ResolvedResourceVersion = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, 1)
|
||||
.await
|
||||
.expect("version 1 must resolve before the edit");
|
||||
assert_eq!(published.snapshot.version.version, 1);
|
||||
assert_eq!(
|
||||
published.snapshot.version.digest,
|
||||
sha256_hex(ORIGINAL_BYTES)
|
||||
);
|
||||
let published_bytes = sandbox
|
||||
.store
|
||||
.read(&published.artifact_ref)
|
||||
.expect("the resolved artifact_ref must read the exact bytes");
|
||||
assert_eq!(published_bytes, ORIGINAL_BYTES);
|
||||
let published_row = PublishedRow::observe(&sandbox, &resource_id, 1).await;
|
||||
assert_eq!(
|
||||
published_row.digest,
|
||||
sha256_hex(ORIGINAL_BYTES),
|
||||
"the published row must carry the digest of the real bytes"
|
||||
);
|
||||
assert!(
|
||||
!PublishedRow::superseded(&sandbox, &resource_id, 1).await,
|
||||
"version 1 must be current before the edit"
|
||||
);
|
||||
|
||||
let edited = sandbox
|
||||
.registry
|
||||
.update_resource_draft(UpdateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: resource_id.clone(),
|
||||
description: "edited after publication snapshot".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
expected_updated_at: published.snapshot.resource.updated_at,
|
||||
artifact: registered(&sandbox, EDITED_BYTES),
|
||||
})
|
||||
.await
|
||||
.expect("a valid edit of the draft must succeed");
|
||||
assert_eq!(edited.version, 2);
|
||||
assert_ne!(edited.digest, published.snapshot.version.digest);
|
||||
|
||||
// (1) Ранее полученный Published-снимок остаётся точным: строка версии 1 и её
|
||||
// owning-ссылка не изменились ни в одном поле (metadata/digest/version).
|
||||
let replayed_row = PublishedRow::observe(&sandbox, &resource_id, 1).await;
|
||||
assert_eq!(
|
||||
replayed_row, published_row,
|
||||
"a real draft edit must not change the previously published row (version, kind, MIME, \
|
||||
size, digest, sensitivity, created_at, superseding time)"
|
||||
);
|
||||
let source = source_state(&sandbox, &replayed_row.artifact_source_id).await;
|
||||
assert_eq!(
|
||||
source.digest, published_row.digest,
|
||||
"the published version keeps its own owning reference digest"
|
||||
);
|
||||
assert!(
|
||||
PublishedRow::superseded(&sandbox, &resource_id, 1).await,
|
||||
"the accepted edit must mark the previous version as superseded"
|
||||
);
|
||||
|
||||
// (2) Байты прежнего снимка читаются по его собственному `artifact_ref` точными bytes —
|
||||
// это тот же ref, который был получен ДО редактирования.
|
||||
let old_bytes = sandbox
|
||||
.store
|
||||
.read(&published.artifact_ref)
|
||||
.expect("the previously obtained artifact_ref must keep reading the exact bytes");
|
||||
assert_eq!(old_bytes, ORIGINAL_BYTES);
|
||||
assert_eq!(sha256_hex(&old_bytes), published.snapshot.version.digest);
|
||||
|
||||
// (3) Разрешённое через API чтение заменённой версии — отказ (ссылка отсоединена
|
||||
// штатным обновлением), а не выдача «почти того же» содержимого. Наблюдаемый код
|
||||
// записывается, чтобы контракт не подменялся конкретным текстом ошибки.
|
||||
let superseded = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, 1)
|
||||
.await;
|
||||
let superseded_observation = match &superseded {
|
||||
Ok(value) => format!(
|
||||
"accepted version={} digest={}",
|
||||
value.snapshot.version.version, value.snapshot.version.digest
|
||||
),
|
||||
Err(error) => format!("refused code={}", error.code()),
|
||||
};
|
||||
|
||||
// (4) Текущая версия переключилась на новые bytes.
|
||||
let current = sandbox
|
||||
.registry
|
||||
.resolve_current_resource_version(WORKSPACE_ID, &resource_id)
|
||||
.await
|
||||
.expect("the current version must resolve");
|
||||
assert_eq!(current.snapshot.version.version, 2);
|
||||
assert_eq!(current.snapshot.version.digest, sha256_hex(EDITED_BYTES));
|
||||
assert_eq!(
|
||||
sandbox
|
||||
.store
|
||||
.read(¤t.artifact_ref)
|
||||
.expect("the new version must read its own bytes"),
|
||||
EDITED_BYTES
|
||||
);
|
||||
assert_ne!(current.artifact_ref, published.artifact_ref);
|
||||
assert!(
|
||||
superseded.is_err(),
|
||||
"a superseded version must not stay served after the edit; observed \
|
||||
{superseded_observation}"
|
||||
);
|
||||
|
||||
let card = sandbox
|
||||
.registry
|
||||
.get_resource_draft(WORKSPACE_ID, &resource_id)
|
||||
.await
|
||||
.expect("the card must stay readable");
|
||||
assert_eq!(card.resource.current_draft_version, 2);
|
||||
assert_eq!(card.resource.uri, "crank://registry/draft");
|
||||
assert_eq!(card.resource.name, "registry_draft");
|
||||
assert_eq!(card.resource.kind, "text");
|
||||
assert_eq!(card.version.version, 2);
|
||||
|
||||
// (4) Итоги строк: две версии, одна живая ссылка, одна отсоединённая.
|
||||
let totals = RowTotals::observe(&sandbox).await;
|
||||
assert_eq!(totals.versions, 2);
|
||||
assert_eq!(totals.owning_refs, 2);
|
||||
assert_eq!(totals.resources, 1);
|
||||
assert_eq!(
|
||||
count(
|
||||
&sandbox,
|
||||
"select count(*) from artifact_sources where lifecycle = 'active' and detached_at is null",
|
||||
)
|
||||
.await,
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
count(
|
||||
&sandbox,
|
||||
"select count(*) from artifact_sources where lifecycle = 'detached' and detached_at is not null",
|
||||
)
|
||||
.await,
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// R-D (2): однофакторная integrity-матрица на durable seed-ах.
|
||||
// Каждый вектор исполняется независимо, с точным отказом и точным восстановлением,
|
||||
// поэтому первое расхождение не скрывает остальные пять (TL run103:35).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Clone)]
|
||||
struct ArtifactIdentity {
|
||||
blob_digest: String,
|
||||
blob_size_bytes: i64,
|
||||
blob_artifact_ref: String,
|
||||
blob_lifecycle: String,
|
||||
version_digest: String,
|
||||
version_size_bytes: i64,
|
||||
version_mime_type: String,
|
||||
version_sensitivity: String,
|
||||
source_mime_type: String,
|
||||
source_sensitivity: String,
|
||||
source_lifecycle: String,
|
||||
source_detached_at: Option<OffsetDateTime>,
|
||||
}
|
||||
|
||||
impl ArtifactIdentity {
|
||||
async fn observe(sandbox: &Sandbox) -> Self {
|
||||
let row = sqlx::query(
|
||||
"select b.digest as blob_digest, b.size_bytes as blob_size_bytes,
|
||||
b.artifact_ref as blob_artifact_ref, b.storage_lifecycle as blob_lifecycle,
|
||||
v.digest as version_digest, v.size_bytes as version_size_bytes,
|
||||
v.mime_type as version_mime_type, v.sensitivity as version_sensitivity,
|
||||
s.mime_type as source_mime_type, s.sensitivity as source_sensitivity,
|
||||
s.lifecycle as source_lifecycle, s.detached_at as source_detached_at
|
||||
from artifact_blobs b
|
||||
join artifact_sources s on s.blob_digest = b.digest
|
||||
join resource_versions v
|
||||
on v.workspace_id = s.workspace_id and v.artifact_source_id = s.source_id
|
||||
where v.superseded_at is null
|
||||
order by s.source_id
|
||||
limit 1",
|
||||
)
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("the durable artifact identity must be observable");
|
||||
Self {
|
||||
blob_digest: row.get("blob_digest"),
|
||||
blob_size_bytes: row.get("blob_size_bytes"),
|
||||
blob_artifact_ref: row.get("blob_artifact_ref"),
|
||||
blob_lifecycle: row.get("blob_lifecycle"),
|
||||
version_digest: row.get("version_digest"),
|
||||
version_size_bytes: row.get("version_size_bytes"),
|
||||
version_mime_type: row.get("version_mime_type"),
|
||||
version_sensitivity: row.get("version_sensitivity"),
|
||||
source_mime_type: row.get("source_mime_type"),
|
||||
source_sensitivity: row.get("source_sensitivity"),
|
||||
source_lifecycle: row.get("source_lifecycle"),
|
||||
source_detached_at: row.get("source_detached_at"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Восстановление ровно зафиксированного значения (не «похожего»): сравнение
|
||||
/// `before == after` требует байт-в-байт того же состояния.
|
||||
async fn restore(&self, sandbox: &Sandbox) {
|
||||
sqlx::query(
|
||||
"update artifact_blobs
|
||||
set digest = $1, size_bytes = $2, artifact_ref = $3, storage_lifecycle = $4",
|
||||
)
|
||||
.bind(&self.blob_digest)
|
||||
.bind(self.blob_size_bytes)
|
||||
.bind(&self.blob_artifact_ref)
|
||||
.bind(&self.blob_lifecycle)
|
||||
.execute(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("the blob identity must be restorable");
|
||||
sqlx::query(
|
||||
"update resource_versions
|
||||
set digest = $1, size_bytes = $2, mime_type = $3, sensitivity = $4",
|
||||
)
|
||||
.bind(&self.version_digest)
|
||||
.bind(self.version_size_bytes)
|
||||
.bind(&self.version_mime_type)
|
||||
.bind(&self.version_sensitivity)
|
||||
.execute(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("the version metadata must be restorable");
|
||||
sqlx::query(
|
||||
"update artifact_sources
|
||||
set mime_type = $1, sensitivity = $2, lifecycle = $3, detached_at = $4",
|
||||
)
|
||||
.bind(&self.source_mime_type)
|
||||
.bind(&self.source_sensitivity)
|
||||
.bind(&self.source_lifecycle)
|
||||
.bind(self.source_detached_at)
|
||||
.execute(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("the owning reference identity must be restorable");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story36_at03_integrity_mismatch_matrix_fails_closed_without_content() {
|
||||
let sandbox = sandbox("at03_integrity_matrix").await;
|
||||
let resource_id = seeded_draft(&sandbox).await;
|
||||
|
||||
// Позитивный контроля до матрицы: durable seed реально читается точными bytes.
|
||||
let baseline = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, 1)
|
||||
.await
|
||||
.expect("the durable seed must resolve before any mutation");
|
||||
assert_eq!(
|
||||
sandbox
|
||||
.store
|
||||
.read(&baseline.artifact_ref)
|
||||
.expect("the durable seed must read its bytes"),
|
||||
ORIGINAL_BYTES
|
||||
);
|
||||
let identity = ArtifactIdentity::observe(&sandbox).await;
|
||||
|
||||
// Однофакторные мутации: меняется ровно один элемент metadata, от которого зависит
|
||||
// сверка чтения (§6). Расхождение `artifact_blobs.artifact_ref` с digest недостижимо:
|
||||
// его связывает CHECK `artifact_blobs_ref_check (artifact_ref = 'sha256:' || digest)`,
|
||||
// поэтому вектор не выдумывается, а заменён проверкой самой связи через version-digest.
|
||||
let mutations: [(&str, &str); 8] = [
|
||||
(
|
||||
"blob-size",
|
||||
"update artifact_blobs set size_bytes = size_bytes + 1",
|
||||
),
|
||||
(
|
||||
"blob-storage-lifecycle",
|
||||
"update artifact_blobs set storage_lifecycle = 'unavailable'",
|
||||
),
|
||||
(
|
||||
"version-digest",
|
||||
"update resource_versions set digest = repeat('0', 64)",
|
||||
),
|
||||
(
|
||||
"version-size",
|
||||
"update resource_versions set size_bytes = size_bytes + 1",
|
||||
),
|
||||
(
|
||||
"version-mime-type",
|
||||
"update resource_versions set mime_type = 'text/html'",
|
||||
),
|
||||
(
|
||||
"version-sensitivity",
|
||||
"update resource_versions set sensitivity = 'public'",
|
||||
),
|
||||
(
|
||||
"source-mime-type",
|
||||
"update artifact_sources set mime_type = 'text/html'",
|
||||
),
|
||||
(
|
||||
"source-lifecycle",
|
||||
"update artifact_sources set lifecycle = 'detached', detached_at = updated_at",
|
||||
),
|
||||
];
|
||||
|
||||
let mut observations: Vec<String> = Vec::new();
|
||||
let mut unexpected: Vec<&str> = Vec::new();
|
||||
for (label, mutation) in mutations {
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(mutation.to_owned()))
|
||||
.execute(sandbox.registry.pool())
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("mutation `{label}` must apply: {error}"));
|
||||
assert_ne!(
|
||||
ArtifactIdentity::observe(&sandbox).await,
|
||||
identity,
|
||||
"mutation `{label}` must really change the observed identity"
|
||||
);
|
||||
|
||||
let resolved = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, 1)
|
||||
.await;
|
||||
match resolved {
|
||||
Err(error) if error.code() == "resource_artifact_integrity" => {
|
||||
observations.push(format!("{label}: refused {code}", code = error.code()));
|
||||
}
|
||||
Err(error) => {
|
||||
unexpected.push(label);
|
||||
observations.push(format!(
|
||||
"{label}: unexpected refusal {code}",
|
||||
code = error.code()
|
||||
));
|
||||
}
|
||||
Ok(value) => {
|
||||
unexpected.push(label);
|
||||
observations.push(format!(
|
||||
"{label}: accepted with digest={} size={}",
|
||||
value.snapshot.version.digest, value.snapshot.version.size_bytes
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Точное восстановление и повторный положительный контроль — даже если выше
|
||||
// зафиксировано расхождение.
|
||||
identity.restore(&sandbox).await;
|
||||
assert_eq!(
|
||||
ArtifactIdentity::observe(&sandbox).await,
|
||||
identity,
|
||||
"mutation `{label}` must be restored byte-exactly"
|
||||
);
|
||||
let restored = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, 1)
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("restore after `{label}` must resolve: {error:?}"));
|
||||
assert_eq!(
|
||||
restored, baseline,
|
||||
"restoration after `{label}` must return the exact published snapshot"
|
||||
);
|
||||
assert_eq!(
|
||||
sandbox
|
||||
.store
|
||||
.read(&restored.artifact_ref)
|
||||
.expect("the restored artifact must read its bytes"),
|
||||
ORIGINAL_BYTES
|
||||
);
|
||||
}
|
||||
|
||||
assert!(
|
||||
unexpected.is_empty(),
|
||||
"every one-factor integrity mismatch must fail closed with `resource_artifact_integrity` \
|
||||
and return no content; observations: {observations:?}"
|
||||
);
|
||||
assert_eq!(observations.len(), 8);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// R-D (3): целочисленные границы версии и детерминированного `source_id`.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn story36_at03_version_and_source_id_boundaries_are_exact() {
|
||||
let sandbox = sandbox("at03_boundaries").await;
|
||||
let resource_id = seeded_draft(&sandbox).await;
|
||||
|
||||
// Версия 0 не должна «случайно» совпасть с текущей версией.
|
||||
let error = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, 0)
|
||||
.await
|
||||
.expect_err("version 0 must not resolve to the current version");
|
||||
assert_eq!(error.code(), "resource_not_found");
|
||||
|
||||
let error = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, i32::MAX as u32)
|
||||
.await
|
||||
.expect_err("an unused version must be not found");
|
||||
assert_eq!(error.code(), "resource_not_found");
|
||||
|
||||
// Значения вне диапазона `integer` не могут быть связаны с колонкой `version`.
|
||||
for version in [i32::MAX as u32 + 1, u32::MAX] {
|
||||
let error = sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &resource_id, version)
|
||||
.await
|
||||
.expect_err("a version outside the integer range cannot be bound");
|
||||
assert_eq!(error.code(), "resource_storage_unavailable");
|
||||
}
|
||||
|
||||
// Детерминированный `source_id` при максимально допустимом хвосте ResourceId (96).
|
||||
let tail_96 = "a".repeat(96);
|
||||
let boundary_id = ResourceId::new(format!("res_{tail_96}"));
|
||||
let boundary_bytes = b"boundary payload";
|
||||
sandbox
|
||||
.registry
|
||||
.create_resource_draft(CreateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: boundary_id.clone(),
|
||||
uri: "crank://registry/boundary".to_owned(),
|
||||
name: "registry_boundary".to_owned(),
|
||||
description: String::new(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
artifact: registered(&sandbox, boundary_bytes),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("a ResourceId with the maximal 96-character tail must be accepted");
|
||||
|
||||
let source_id: String = sqlx::query_scalar(
|
||||
"select artifact_source_id from resource_versions
|
||||
where workspace_id = $1 and resource_id = $2 and version = 1",
|
||||
)
|
||||
.bind(WORKSPACE_ID)
|
||||
.bind(boundary_id.as_str())
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("the deterministic owning reference must be observable");
|
||||
assert_eq!(
|
||||
source_id,
|
||||
format!("src_{tail_96}_v1"),
|
||||
"the owning reference is derived from the ResourceId tail and the version"
|
||||
);
|
||||
assert!(
|
||||
source_id.len() <= 128 && source_id.len() >= 5,
|
||||
"the derived source id must stay inside the stored grammar: {source_id}"
|
||||
);
|
||||
assert_eq!(
|
||||
source_id.len(),
|
||||
4 + 96 + 2 + 1,
|
||||
"a maximal tail still produces a storable source id"
|
||||
);
|
||||
assert_eq!(
|
||||
sandbox
|
||||
.registry
|
||||
.resolve_resource_version(WORKSPACE_ID, &boundary_id, 1)
|
||||
.await
|
||||
.expect("the boundary draft must resolve")
|
||||
.snapshot
|
||||
.version
|
||||
.digest,
|
||||
sha256_hex(boundary_bytes)
|
||||
);
|
||||
|
||||
// Хвост на один символ длиннее отвергается целиком: ни строки Resource, ни версии,
|
||||
// ни owning-ссылки не появляется.
|
||||
let before = RowTotals::observe(&sandbox).await;
|
||||
let tail_97 = "b".repeat(97);
|
||||
let error = sandbox
|
||||
.registry
|
||||
.create_resource_draft(CreateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: ResourceId::new(format!("res_{tail_97}")),
|
||||
uri: "crank://registry/boundary-over".to_owned(),
|
||||
name: "registry_boundary_over".to_owned(),
|
||||
description: String::new(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
artifact: registered(&sandbox, b"over boundary payload"),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect_err("a source id longer than the stored grammar must be refused");
|
||||
assert_eq!(error.code(), "resource_storage_unavailable");
|
||||
assert_eq!(
|
||||
RowTotals::observe(&sandbox).await,
|
||||
before,
|
||||
"a refused over-long identifier must leave no accepted Resource, version or owning ref"
|
||||
);
|
||||
|
||||
// Прежний черновик и его связь не тронуты.
|
||||
let snapshot = DraftSnapshot::observe(&sandbox, &resource_id).await;
|
||||
assert_eq!(snapshot.version, 1);
|
||||
assert_eq!(snapshot.source_lifecycle, "active");
|
||||
assert_eq!(
|
||||
source_state(&sandbox, &snapshot.artifact_source_id)
|
||||
.await
|
||||
.lifecycle,
|
||||
"active"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
//! Story 3.7 / AC03 registry-level: immutable publication ownership, CAS и отказ
|
||||
//! без partial writes.
|
||||
//!
|
||||
//! Проверяется на реальном PostgreSQL:
|
||||
//! - публикация создаёт отдельную owning-ссылку на тот же immutable blob;
|
||||
//! - Draft edit после публикации не отсоединяет publication source и не меняет snapshot;
|
||||
//! - повторный/stale publish и отказ по несовпавшему snapshot не пишут строк и не
|
||||
//! сдвигают ревизию карточки.
|
||||
|
||||
use super::*;
|
||||
|
||||
use crank_core::resource::ResourceError;
|
||||
use crank_registry::model::resource::{PublishResourceVersionRequest, ResourcePublicationRecord};
|
||||
|
||||
async fn publish_current(sandbox: &Sandbox, resource_id: &ResourceId) -> ResourcePublicationRecord {
|
||||
let current = sandbox
|
||||
.registry
|
||||
.get_resource_draft(WORKSPACE_ID, resource_id)
|
||||
.await
|
||||
.expect("draft must be readable");
|
||||
sandbox
|
||||
.registry
|
||||
.publish_resource_version(PublishResourceVersionRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: resource_id.clone(),
|
||||
expected_updated_at: current.resource.updated_at,
|
||||
expected_version: current.version.version,
|
||||
expected_digest: current.version.digest.clone(),
|
||||
expected_size_bytes: current.version.size_bytes,
|
||||
artifact: registered(sandbox, b"registry payload"),
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("a valid current draft must publish")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story37_at03_publication_owns_blob_independently_of_draft_edit() {
|
||||
let sandbox = sandbox("at37_publication_owning").await;
|
||||
let resource_id = seeded_draft(&sandbox).await;
|
||||
let publication = publish_current(&sandbox, &resource_id).await;
|
||||
|
||||
assert_eq!(publication.version, 1);
|
||||
assert_eq!(publication.uri, "crank://registry/draft");
|
||||
assert_eq!(publication.kind, "text");
|
||||
assert_eq!(publication.mime_type, "text/plain");
|
||||
assert_eq!(publication.sensitivity, "internal");
|
||||
assert_eq!(publication.size_bytes, 16);
|
||||
assert_eq!(publication.digest, sha256_hex(b"registry payload"));
|
||||
|
||||
let status: String = sqlx::query_scalar("select status from resources where resource_id = $1")
|
||||
.bind(resource_id.as_str())
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("resources must be queryable");
|
||||
assert_eq!(
|
||||
status, "published",
|
||||
"publish must switch the card to published"
|
||||
);
|
||||
|
||||
let draft_source: String = sqlx::query_scalar(
|
||||
"select artifact_source_id from resource_versions where resource_id = $1 and superseded_at is null",
|
||||
)
|
||||
.bind(resource_id.as_str())
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("draft source must be queryable");
|
||||
let publication_source: String = sqlx::query_scalar(
|
||||
"select artifact_source_id from resource_publications where resource_id = $1 and version = 1",
|
||||
)
|
||||
.bind(resource_id.as_str())
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("publication source must be queryable");
|
||||
assert_ne!(
|
||||
draft_source, publication_source,
|
||||
"publication must own a dedicated source, not the mutable draft owning ref"
|
||||
);
|
||||
|
||||
// Draft edit: новая версия, новая draft-ссылка, карточка снова Draft.
|
||||
let current = sandbox
|
||||
.registry
|
||||
.get_resource_draft(WORKSPACE_ID, &resource_id)
|
||||
.await
|
||||
.expect("draft must be readable");
|
||||
sandbox
|
||||
.registry
|
||||
.update_resource_draft(UpdateResourceDraftRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: resource_id.clone(),
|
||||
description: "edited after publication".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "public".to_owned(),
|
||||
expected_updated_at: current.resource.updated_at,
|
||||
artifact: registered(&sandbox, b"edited payload"),
|
||||
})
|
||||
.await
|
||||
.expect("draft edit after publication must succeed");
|
||||
|
||||
let status: String = sqlx::query_scalar("select status from resources where resource_id = $1")
|
||||
.bind(resource_id.as_str())
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("resources must be queryable");
|
||||
assert_eq!(
|
||||
status, "draft",
|
||||
"a Draft edit must return the card to draft"
|
||||
);
|
||||
|
||||
let publication_lifecycle: String = sqlx::query_scalar(
|
||||
"select lifecycle from artifact_sources where workspace_id = $1 and source_id = $2",
|
||||
)
|
||||
.bind(WORKSPACE_ID)
|
||||
.bind(&publication_source)
|
||||
.fetch_one(sandbox.registry.pool())
|
||||
.await
|
||||
.expect("publication source must still exist");
|
||||
assert_eq!(
|
||||
publication_lifecycle, "active",
|
||||
"a Draft edit must not detach the publication owning source"
|
||||
);
|
||||
|
||||
// Snapshot остаётся exact и читается через publication owning source.
|
||||
let resolved = sandbox
|
||||
.registry
|
||||
.resolve_resource_publication(WORKSPACE_ID, &resource_id, 1)
|
||||
.await
|
||||
.expect("published version must stay resolvable after the edit");
|
||||
assert_eq!(resolved.publication, publication);
|
||||
let bytes = sandbox
|
||||
.store
|
||||
.read(&resolved.artifact_ref)
|
||||
.expect("published bytes must stay readable");
|
||||
assert_eq!(bytes, b"registry payload");
|
||||
}
|
||||
|
||||
async fn totals(sandbox: &Sandbox) -> (i64, i64, i64, i64, i64) {
|
||||
(
|
||||
count(sandbox, "select count(*) from resources").await,
|
||||
count(sandbox, "select count(*) from resource_versions").await,
|
||||
count(sandbox, "select count(*) from artifact_sources").await,
|
||||
count(sandbox, "select count(*) from artifact_blobs").await,
|
||||
count(sandbox, "select count(*) from resource_publications").await,
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story37_at03_stale_repeat_and_refusal_never_write_rows() {
|
||||
let sandbox = sandbox("at37_publication_stale").await;
|
||||
let resource_id = seeded_draft(&sandbox).await;
|
||||
let card_before = sandbox
|
||||
.registry
|
||||
.get_resource_draft(WORKSPACE_ID, &resource_id)
|
||||
.await
|
||||
.expect("card must be readable");
|
||||
|
||||
// Отказ по несовпавшему snapshot (TOCTOU) — stale и без записей, ещё до публикации.
|
||||
let initial = totals(&sandbox).await;
|
||||
let mismatched = sandbox
|
||||
.registry
|
||||
.publish_resource_version(PublishResourceVersionRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: resource_id.clone(),
|
||||
expected_updated_at: card_before.resource.updated_at,
|
||||
expected_version: card_before.version.version,
|
||||
expected_digest: sha256_hex(b"not the stored payload"),
|
||||
expected_size_bytes: card_before.version.size_bytes,
|
||||
artifact: registered(&sandbox, b"registry payload"),
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect_err("a snapshot mismatch must be refused");
|
||||
assert!(matches!(mismatched, ResourceError::Stale));
|
||||
assert_eq!(
|
||||
totals(&sandbox).await,
|
||||
initial,
|
||||
"a refused snapshot must not write rows"
|
||||
);
|
||||
|
||||
let publication = sandbox
|
||||
.registry
|
||||
.publish_resource_version(PublishResourceVersionRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: resource_id.clone(),
|
||||
expected_updated_at: card_before.resource.updated_at,
|
||||
expected_version: card_before.version.version,
|
||||
expected_digest: card_before.version.digest.clone(),
|
||||
expected_size_bytes: card_before.version.size_bytes,
|
||||
artifact: registered(&sandbox, b"registry payload"),
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("a valid current draft must publish");
|
||||
assert_eq!(publication.version, 1);
|
||||
let after_publish = totals(&sandbox).await;
|
||||
let published_card = sandbox
|
||||
.registry
|
||||
.get_resource_draft(WORKSPACE_ID, &resource_id)
|
||||
.await
|
||||
.expect("card must be readable");
|
||||
assert!(
|
||||
published_card.resource.updated_at > card_before.resource.updated_at,
|
||||
"a successful publish must advance the CAS revision monotonically"
|
||||
);
|
||||
|
||||
// Повтор той же публикации с прежней карточкой: CAS уже сдвинут.
|
||||
let repeated = sandbox
|
||||
.registry
|
||||
.publish_resource_version(PublishResourceVersionRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: resource_id.clone(),
|
||||
expected_updated_at: card_before.resource.updated_at,
|
||||
expected_version: 1,
|
||||
expected_digest: card_before.version.digest.clone(),
|
||||
expected_size_bytes: card_before.version.size_bytes,
|
||||
artifact: registered(&sandbox, b"registry payload"),
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect_err("repeating the same publish must be stale");
|
||||
assert!(matches!(repeated, ResourceError::Stale));
|
||||
|
||||
// Повтор со свежей карточкой без правки Draft: версия уже опубликована (no duplicate).
|
||||
let duplicate = sandbox
|
||||
.registry
|
||||
.publish_resource_version(PublishResourceVersionRequest {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: resource_id.clone(),
|
||||
expected_updated_at: published_card.resource.updated_at,
|
||||
expected_version: published_card.version.version,
|
||||
expected_digest: published_card.version.digest.clone(),
|
||||
expected_size_bytes: published_card.version.size_bytes,
|
||||
artifact: registered(&sandbox, b"registry payload"),
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect_err("re-publishing an unchanged published draft must be stale");
|
||||
assert!(matches!(duplicate, ResourceError::Stale));
|
||||
|
||||
assert_eq!(
|
||||
totals(&sandbox).await,
|
||||
after_publish,
|
||||
"stale/refused publications must not write rows"
|
||||
);
|
||||
let card_after = sandbox
|
||||
.registry
|
||||
.get_resource_draft(WORKSPACE_ID, &resource_id)
|
||||
.await
|
||||
.expect("card must be readable");
|
||||
assert_eq!(
|
||||
card_after.resource.updated_at, published_card.resource.updated_at,
|
||||
"a refused publish must not advance the CAS revision"
|
||||
);
|
||||
let resolved = sandbox
|
||||
.registry
|
||||
.resolve_resource_publication(WORKSPACE_ID, &resource_id, 1)
|
||||
.await
|
||||
.expect("published version must stay readable");
|
||||
assert_eq!(resolved.publication, publication);
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
//! BUILD-ONLY PG Story 3.10 (FR-16): version-keyed template definitions (V20).
|
||||
//!
|
||||
//! Проверяет то, что видно только на реальной схеме: definition-строки
|
||||
//! insert-only, публикация ссылается на ту же version-keyed строку, правка Draft
|
||||
//! не меняет опубликованное определение, CAS-гарды не создают дублей/сирот, а
|
||||
//! artifact-строки сохраняют прежние инварианты.
|
||||
|
||||
use sha2::{Digest, Sha256};
|
||||
use sqlx::Row as _;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use crank_core::ids::ResourceId;
|
||||
use crank_registry::model::resource::{
|
||||
CreateResourceTemplateDraftRequest, PublishResourceTemplateVersionRequest,
|
||||
ResourceTemplateDraftRecord, UpdateResourceTemplateDraftRequest,
|
||||
};
|
||||
|
||||
use super::*;
|
||||
use crank_registry::PostgresRegistry;
|
||||
|
||||
const WORKSPACE: &str = WORKSPACE_ID;
|
||||
|
||||
fn sha256_hex(value: &str) -> String {
|
||||
format!("{:x}", Sha256::digest(value.as_bytes()))
|
||||
}
|
||||
|
||||
fn definition(operation_id: &str, uri_template: &str) -> String {
|
||||
json!({
|
||||
"operation_id": operation_id,
|
||||
"operation_version": 1,
|
||||
"uri_template": uri_template,
|
||||
"parameters": [{
|
||||
"name": "order_id",
|
||||
"input_path": "input.order_id",
|
||||
"schema": { "type": "string", "required": true, "format": "uuid" }
|
||||
}],
|
||||
"cache": { "ttl_ms": 60000, "vary": ["order_id"], "max_bytes": 65536 },
|
||||
"failure": { "outcome": "error" }
|
||||
})
|
||||
.to_string()
|
||||
}
|
||||
|
||||
async fn create_template(
|
||||
registry: &PostgresRegistry,
|
||||
resource_id: &ResourceId,
|
||||
uri: &str,
|
||||
name: &str,
|
||||
definition_json: &str,
|
||||
) -> ResourceTemplateDraftRecord {
|
||||
registry
|
||||
.create_resource_template_draft(CreateResourceTemplateDraftRequest {
|
||||
workspace_id: WORKSPACE.into(),
|
||||
resource_id: resource_id.clone(),
|
||||
uri: uri.to_owned(),
|
||||
name: name.to_owned(),
|
||||
description: String::new(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
definition_json: definition_json.to_owned(),
|
||||
definition_digest: sha256_hex(definition_json),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("template draft must be created")
|
||||
}
|
||||
|
||||
async fn publish_template(
|
||||
registry: &PostgresRegistry,
|
||||
resource_id: &ResourceId,
|
||||
record: &ResourceTemplateDraftRecord,
|
||||
) -> Result<(), crank_core::resource::ResourceError> {
|
||||
registry
|
||||
.publish_resource_template_version(PublishResourceTemplateVersionRequest {
|
||||
workspace_id: WORKSPACE.into(),
|
||||
resource_id: resource_id.clone(),
|
||||
expected_updated_at: record.snapshot.resource.updated_at,
|
||||
expected_version: record.snapshot.version.version,
|
||||
expected_digest: record.source.definition_digest.clone(),
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story310_at06_template_source_is_immutable_in_postgres() {
|
||||
let sandbox = sandbox("story310_template_immutable").await;
|
||||
let registry = &sandbox.registry;
|
||||
let resource_id = ResourceId::new("res_story310_template_immutable");
|
||||
let first = definition("op_story310_first", "crank://orders/{order_id}");
|
||||
let created = create_template(
|
||||
registry,
|
||||
&resource_id,
|
||||
"crank://story310/immutable",
|
||||
"story310_immutable",
|
||||
&first,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(created.snapshot.version.source_kind, "template");
|
||||
assert_eq!(created.snapshot.version.size_bytes, 0);
|
||||
assert_eq!(created.source.definition_json, first);
|
||||
|
||||
// Definition-строка insert-only: UPDATE отвергается trigger-ом БД.
|
||||
let tamper = sqlx::query(
|
||||
"update resource_template_sources set definition_json = $1
|
||||
where workspace_id = $2 and resource_id = $3 and version = 1",
|
||||
)
|
||||
.bind(definition("op_story310_other", "crank://orders/{order_id}"))
|
||||
.bind(WORKSPACE)
|
||||
.bind(resource_id.as_str())
|
||||
.execute(registry.pool())
|
||||
.await;
|
||||
assert!(
|
||||
tamper.is_err(),
|
||||
"a stored template definition must not be mutable"
|
||||
);
|
||||
|
||||
publish_template(registry, &resource_id, &created)
|
||||
.await
|
||||
.expect("the draft must publish");
|
||||
let (publication, source) = registry
|
||||
.resolve_resource_template_publication(WORKSPACE, &resource_id, 1)
|
||||
.await
|
||||
.expect("published template snapshot must resolve");
|
||||
assert_eq!(publication.source_kind, "template");
|
||||
assert_eq!(publication.size_bytes, 0);
|
||||
assert_eq!(source.definition_json, first);
|
||||
assert_eq!(source.definition_digest, sha256_hex(&first));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story310_at06_draft_edit_does_not_mutate_published_source() {
|
||||
let sandbox = sandbox("story310_template_edit").await;
|
||||
let registry = &sandbox.registry;
|
||||
let resource_id = ResourceId::new("res_story310_template_edit");
|
||||
let first = definition("op_story310_first", "crank://orders/{order_id}");
|
||||
let second = definition("op_story310_second", "crank://orders/{order_id}");
|
||||
let created = create_template(
|
||||
registry,
|
||||
&resource_id,
|
||||
"crank://story310/edit",
|
||||
"story310_edit",
|
||||
&first,
|
||||
)
|
||||
.await;
|
||||
publish_template(registry, &resource_id, &created)
|
||||
.await
|
||||
.expect("first publication must succeed");
|
||||
// Публикация сдвигает CAS-ревизию карточки: редактирование берёт её из свежего чтения.
|
||||
let published_draft = registry
|
||||
.get_resource_draft(WORKSPACE, &resource_id)
|
||||
.await
|
||||
.expect("published draft card must be readable");
|
||||
|
||||
let updated = registry
|
||||
.update_resource_template_draft(UpdateResourceTemplateDraftRequest {
|
||||
workspace_id: WORKSPACE.into(),
|
||||
resource_id: resource_id.clone(),
|
||||
description: "retargeted".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
expected_updated_at: published_draft.resource.updated_at,
|
||||
definition_json: second.clone(),
|
||||
definition_digest: sha256_hex(&second),
|
||||
})
|
||||
.await
|
||||
.expect("draft edit must create the next version");
|
||||
assert_eq!(updated.snapshot.version.version, 2);
|
||||
assert_eq!(updated.source.definition_json, second);
|
||||
|
||||
// Published v1 остаётся прежним source-снимком.
|
||||
let (_, published_source) = registry
|
||||
.resolve_resource_template_publication(WORKSPACE, &resource_id, 1)
|
||||
.await
|
||||
.expect("published v1 must stay readable");
|
||||
assert_eq!(published_source.definition_json, first);
|
||||
|
||||
// Устаревший precondition публикации не создаёт новую версию и не пишет сирот.
|
||||
let stale = registry
|
||||
.publish_resource_template_version(PublishResourceTemplateVersionRequest {
|
||||
workspace_id: WORKSPACE.into(),
|
||||
resource_id: resource_id.clone(),
|
||||
expected_updated_at: created.snapshot.resource.updated_at,
|
||||
expected_version: created.snapshot.version.version,
|
||||
expected_digest: created.source.definition_digest.clone(),
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await;
|
||||
assert_eq!(stale, Err(crank_core::resource::ResourceError::Stale));
|
||||
let publications: i64 = sqlx::query(
|
||||
"select count(*) as count from resource_publications
|
||||
where workspace_id = $1 and resource_id = $2",
|
||||
)
|
||||
.bind(WORKSPACE)
|
||||
.bind(resource_id.as_str())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.expect("publication count must be readable")
|
||||
.try_get("count")
|
||||
.expect("count column");
|
||||
assert_eq!(publications, 1, "a stale publish must not add a row");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story310_at06_concurrent_publish_uses_the_existing_guard() {
|
||||
let sandbox = sandbox("story310_template_concurrent").await;
|
||||
let registry = &sandbox.registry;
|
||||
let resource_id = ResourceId::new("res_story310_template_concurrent");
|
||||
let created = create_template(
|
||||
registry,
|
||||
&resource_id,
|
||||
"crank://story310/concurrent",
|
||||
"story310_concurrent",
|
||||
&definition("op_story310_first", "crank://orders/{order_id}"),
|
||||
)
|
||||
.await;
|
||||
let request = || PublishResourceTemplateVersionRequest {
|
||||
workspace_id: WORKSPACE.into(),
|
||||
resource_id: resource_id.clone(),
|
||||
expected_updated_at: created.snapshot.resource.updated_at,
|
||||
expected_version: created.snapshot.version.version,
|
||||
expected_digest: created.source.definition_digest.clone(),
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
};
|
||||
// Один и тот же precondition: row-lock + CAS пропускают ровно одну публикацию.
|
||||
let (first, second) = tokio::join!(
|
||||
registry.publish_resource_template_version(request()),
|
||||
registry.publish_resource_template_version(request()),
|
||||
);
|
||||
let successes = usize::from(first.is_ok()) + usize::from(second.is_ok());
|
||||
assert_eq!(successes, 1, "exactly one concurrent publish may win");
|
||||
let stale = [first, second]
|
||||
.into_iter()
|
||||
.filter_map(Result::err)
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(stale, vec![crank_core::resource::ResourceError::Stale]);
|
||||
let publications: i64 = sqlx::query(
|
||||
"select count(*) as count from resource_publications
|
||||
where workspace_id = $1 and resource_id = $2",
|
||||
)
|
||||
.bind(WORKSPACE)
|
||||
.bind(resource_id.as_str())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.expect("publication count must be readable")
|
||||
.try_get("count")
|
||||
.expect("count column");
|
||||
assert_eq!(publications, 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn story310_at06_failed_template_create_leaves_no_orphan_and_static_rows_keep_checks() {
|
||||
let sandbox = sandbox("story310_template_orphan").await;
|
||||
let registry = &sandbox.registry;
|
||||
// Static Draft по-прежнему создаётся и остаётся artifact-строкой.
|
||||
let static_id = seeded_draft(&sandbox).await;
|
||||
let static_record = registry
|
||||
.get_resource_draft(WORKSPACE, &static_id)
|
||||
.await
|
||||
.expect("static draft must stay readable");
|
||||
assert_eq!(static_record.version.source_kind, "artifact");
|
||||
assert!(static_record.version.size_bytes > 0);
|
||||
|
||||
// Дубликат URI: транзакция create шаблона обязана откатиться целиком.
|
||||
let resource_id = ResourceId::new("res_story310_template_orphan");
|
||||
let definition_json = definition("op_story310_first", "crank://orders/{order_id}");
|
||||
let duplicate = registry
|
||||
.create_resource_template_draft(CreateResourceTemplateDraftRequest {
|
||||
workspace_id: WORKSPACE.into(),
|
||||
resource_id: resource_id.clone(),
|
||||
uri: static_record.resource.uri.clone(),
|
||||
name: "story310_orphan".to_owned(),
|
||||
description: String::new(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
definition_json: definition_json.clone(),
|
||||
definition_digest: sha256_hex(&definition_json),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
duplicate,
|
||||
Err(crank_core::resource::ResourceError::UriDuplicate)
|
||||
);
|
||||
let orphans: i64 = sqlx::query(
|
||||
"select count(*) as count from resource_template_sources
|
||||
where workspace_id = $1 and resource_id = $2",
|
||||
)
|
||||
.bind(WORKSPACE)
|
||||
.bind(resource_id.as_str())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.expect("template source count must be readable")
|
||||
.try_get("count")
|
||||
.expect("count column");
|
||||
assert_eq!(orphans, 0, "a rejected create must not leave a definition");
|
||||
let versions: i64 = sqlx::query(
|
||||
"select count(*) as count from resource_versions
|
||||
where workspace_id = $1 and resource_id = $2",
|
||||
)
|
||||
.bind(WORKSPACE)
|
||||
.bind(resource_id.as_str())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.expect("version count must be readable")
|
||||
.try_get("count")
|
||||
.expect("count column");
|
||||
assert_eq!(versions, 0, "a rejected create must not leave a version");
|
||||
}
|
||||
Reference in new issue
Block a user