Files
crank/crates/crank-registry/src/migrations/schema_guard_v22.rs
T
bsodfather 54ce770682
CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s
feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
Recovery delivery of the accumulated, TL-accepted Epic 3 work that had never been
committed to Git (stories 3.6-3.17, see the crank board). Story 3.18 is not accepted
yet and is deliberately excluded: its logging surface, its capability registration,
its oracle projections and its tests are not part of this tree.

Accepted scope
- 3.6 typed static Resource Drafts; 3.7 publication and exact binding of static
  Resource Versions; 3.8 MCP discovery/read and revocation of static Resources;
- 3.9 Resource import/export in API and UI plus TLS dependency maintenance;
  3.10 REST-backed Resource templates; 3.11 shared REST read runtime and the MCP
  revision/capability foundation;
- 3.12 parameterised Prompt Drafts with preview; 3.13 Prompt publication and exact
  version binding to Agents; 3.14 MCP prompts; 3.15 Prompt import/export;
- 3.16 composite Prompts with published Resources (dependency content scan plus
  dynamic read through the accepted 3.11 runtime, admin preview and MCP prompts/get);
- 3.17 bounded MCP completion suggestions from typed published schemas and the
  resources/list admission fix for bound template publications.

Accepted evidence being reused (unchanged code paths)
- 3.16 candidate: core 7, admin-api 22, registry 4, mcp-server 4, UI 6; one final
  `just verify` run 1651 passed / 0 failed / 2 ignored.
- 3.17 candidate: full run 1672 passed / 0 failed / 2 ignored, QA targeted reruns and
  a real MCP Inspector 2.12.0 client smoke.

Delivery engineering in this commit
- CI: one event per change (feature branches are gated by their pull request, push
  runs only on main), story events run the changed packages, the full workspace suite
  stays the feature/release gate; no cache/sharding without a measured runner check.
- Release: the packaged archives, checksums and SBOM are now uploaded to the Gitea
  release entry of the tag instead of dying with the runner workspace.

Not included on purpose: Story 3.18 work, build caches, runtime databases, local
credentials and scratch evidence.

Refs: crank kanban t_e39d7263; baseline 1b6db09bd1.
2026-10-25 09:08:22 +00:00

300 lines
9.8 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 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"))
}