systemprompt_database/lifecycle/migrations/
mod.rs1pub(crate) mod budget;
11mod checksum_transition;
12mod compat;
13mod down;
14mod exec;
15mod mark_applied;
16mod repair;
17mod run;
18mod stamp;
19mod status;
20mod step_error;
21mod triggers;
22mod verify;
23
24pub use mark_applied::MarkAppliedOutcome;
25pub use repair::RepairResult;
26pub use stamp::{BaselineStamp, FreshnessCheck, is_retirement};
27pub use status::{
28 AppliedMigration, ChecksumDrift, ExtensionMigrationStatus, MigrationResult, MigrationStatus,
29 OrphanedMigration, PendingMigration, SlotCollision, TombstonedSlot,
30};
31
32use crate::services::{DatabaseProvider, SqlExecutor};
33use std::collections::HashSet;
34use systemprompt_extension::{Extension, LoaderError, Migration};
35use systemprompt_identifiers::ExtensionId;
36use tracing::{debug, info, warn};
37
38pub(crate) const RECORD_MIGRATION_SQL: &str = "INSERT INTO extension_migrations (id, extension_id, version, \
39 name, checksum) VALUES ($1, $2, $3, $4, $5)";
40
41#[derive(Debug, Default, Clone, Copy)]
42pub struct MigrationConfig {
43 pub allow_checksum_drift: bool,
44 pub force_full_install: bool,
45}
46
47pub struct MigrationService<'a> {
48 db: &'a dyn DatabaseProvider,
49 config: MigrationConfig,
50}
51
52impl std::fmt::Debug for MigrationService<'_> {
53 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54 f.debug_struct("MigrationService")
55 .field("config", &self.config)
56 .finish_non_exhaustive()
57 }
58}
59
60impl<'a> MigrationService<'a> {
61 pub fn new(db: &'a dyn DatabaseProvider) -> Self {
62 Self {
63 db,
64 config: MigrationConfig::default(),
65 }
66 }
67
68 #[must_use]
69 pub const fn with_config(mut self, config: MigrationConfig) -> Self {
70 self.config = config;
71 self
72 }
73
74 async fn ensure_migrations_table_exists(&self) -> Result<(), LoaderError> {
75 let sql = include_str!("../../../schema/extension_migrations.sql");
76 SqlExecutor::execute_statements_parsed(self.db, sql)
77 .await
78 .map_err(|e| LoaderError::MigrationStepFailed {
79 extension: ExtensionId::new("database"),
80 context: "Failed to ensure migrations table exists".to_owned(),
81 source: Box::new(e),
82 })
83 }
84
85 pub async fn get_applied_migrations(
86 &self,
87 extension_id: &ExtensionId,
88 ) -> Result<Vec<AppliedMigration>, LoaderError> {
89 let result = self
90 .db
91 .query_raw_with(
92 &"SELECT extension_id, version, name, checksum, applied_at FROM \
93 extension_migrations WHERE extension_id = $1 ORDER BY version",
94 &[&extension_id],
95 )
96 .await
97 .map_err(|e| LoaderError::MigrationStepFailed {
98 extension: extension_id.clone(),
99 context: "Failed to query applied migrations".to_owned(),
100 source: Box::new(e),
101 })?;
102
103 result
104 .rows
105 .iter()
106 .map(|row| decode_applied_row(extension_id, row))
107 .collect()
108 }
109
110 pub async fn run_pending_migrations(
111 &self,
112 extension: &dyn Extension,
113 ) -> Result<MigrationResult, LoaderError> {
114 let ext_id = &ExtensionId::new(extension.metadata().id);
115 let migrations = extension.migrations();
116
117 if migrations.is_empty() {
118 return Ok(MigrationResult::default());
119 }
120
121 self.ensure_migrations_table_exists().await?;
122
123 let applied = self.get_applied_migrations(ext_id).await?;
124 let ahead = ahead_versions(&applied, &migrations);
125 if !ahead.is_empty() {
126 warn!(
127 extension = %ext_id,
128 versions = ?ahead,
129 "Database holds migrations newer than this binary; a newer release owns this \
130 extension's schema, so this binary applies and verifies nothing for it"
131 );
132 return Ok(MigrationResult::default());
133 }
134 self.transition_checksums(ext_id, &migrations, &applied)
135 .await?;
136 let applied_rows: std::collections::HashMap<u32, &AppliedMigration> =
137 applied.iter().map(|m| (m.version, m)).collect();
138
139 warn_orphaned_versions(ext_id, &applied, &migrations);
140
141 let mut migrations_run = 0;
142 let mut migrations_skipped = 0;
143
144 for migration in &migrations {
145 let row = applied_rows.get(&migration.version).copied();
146
147 if migration.tombstone {
148 debug!(
149 extension = %ext_id,
150 version = migration.version,
151 name = %migration.name,
152 tracked = row.is_some(),
153 "Migration slot is tombstoned, nothing to run"
154 );
155 continue;
156 }
157
158 if let Some(row) = row {
159 self.verify_slot_identity(ext_id, migration, Some(row))?;
160 self.verify_checksum(ext_id, migration, &row.checksum)?;
161 migrations_skipped += 1;
162 debug!(
163 extension = %ext_id,
164 version = migration.version,
165 "Migration already applied, skipping"
166 );
167 continue;
168 }
169
170 self.execute_migration(extension, migration).await?;
171 migrations_run += 1;
172 }
173
174 if migrations_run > 0 {
175 info!(
176 extension = %ext_id,
177 migrations_run,
178 migrations_skipped,
179 "Migrations completed"
180 );
181 }
182
183 Ok(MigrationResult {
184 migrations_run,
185 migrations_skipped,
186 })
187 }
188}
189
190pub(crate) fn orphaned_versions(applied: &[AppliedMigration], defined: &[Migration]) -> Vec<u32> {
191 let declared: HashSet<u32> = defined.iter().map(|m| m.version).collect();
192 applied
193 .iter()
194 .map(|m| m.version)
195 .filter(|version| !declared.contains(version))
196 .collect()
197}
198
199pub(crate) fn ahead_versions(applied: &[AppliedMigration], defined: &[Migration]) -> Vec<u32> {
203 let Some(latest) = defined.iter().map(|m| m.version).max() else {
204 return Vec::new();
205 };
206 applied
207 .iter()
208 .map(|m| m.version)
209 .filter(|version| *version > latest)
210 .collect()
211}
212
213fn warn_orphaned_versions(
214 ext_id: &ExtensionId,
215 applied: &[AppliedMigration],
216 defined: &[Migration],
217) {
218 let orphaned = orphaned_versions(applied, defined);
219 if orphaned.is_empty() {
220 return;
221 }
222 warn!(
223 extension = %ext_id,
224 versions = ?orphaned,
225 "Applied migrations are no longer declared by the extension; their files were deleted \
226 without leaving a tombstone, so the numbers look free but are spent"
227 );
228}
229
230fn decode_applied_row(
231 extension_id: &ExtensionId,
232 row: &crate::models::JsonRow,
233) -> Result<AppliedMigration, LoaderError> {
234 let malformed = |column: &str| LoaderError::MigrationFailed {
235 extension: extension_id.clone(),
236 message: format!("extension_migrations row has a malformed `{column}` column"),
237 };
238 let text = |column: &str| -> Result<String, LoaderError> {
239 row.get(column)
240 .and_then(serde_json::Value::as_str)
241 .map(str::to_owned)
242 .ok_or_else(|| malformed(column))
243 };
244 let version = row
245 .get("version")
246 .and_then(serde_json::Value::as_i64)
247 .and_then(|v| u32::try_from(v).ok())
248 .ok_or_else(|| malformed("version"))?;
249 let checksum = text("checksum")?;
250 Ok(AppliedMigration {
251 extension_id: extension_id.clone(),
252 version,
253 name: text("name")?,
254 checksum,
255 applied_at: row
256 .get("applied_at")
257 .and_then(serde_json::Value::as_str)
258 .map(str::to_owned),
259 })
260}