Skip to main content

systemprompt_database/lifecycle/migrations/
repair.rs

1//! Migration checksum-drift repair.
2//!
3//! When an already-applied migration file is edited in place, its stored
4//! checksum stops matching the file and the runner refuses to proceed.
5//! [`MigrationService::repair_drift`] re-executes each drifted migration and
6//! rewrites its stored checksum in the same transaction; the tracking row is
7//! never deleted, so a failed re-apply rolls back to "drifted but tracked"
8//! instead of leaving the migration untracked and crash-looping the next
9//! boot. Re-applying requires the migration SQL to be re-executable against
10//! the current schema — a later migration may have invalidated that, in which
11//! case [`MigrationService::reconcile_drift`] rewrites the stored checksum
12//! without executing any SQL. `no_transaction` migrations cannot be repaired
13//! atomically: a mid-SQL failure leaves the row tracked with the old
14//! checksum, which still reports as drift rather than crash-looping.
15//!
16//! Both entry points act only on the drift they read *under* the bootstrap
17//! lock, so two concurrent repairs never act on the same drift set; a read
18//! before the lock only refuses early or skips taking it when there is none.
19//! Both refuse outright when the recorded row for a slot names a different
20//! migration than the file now occupying it. That is a reused slot, not drift,
21//! and reconciling it would stamp one migration's checksum onto a row
22//! describing another — silencing that row's drift detector for good.
23//!
24//! Copyright (c) systemprompt.io — Business Source License 1.1.
25//! See <https://systemprompt.io> for licensing details.
26
27use super::exec::{TrackingWrite, check_cross_extension_alters, execute_statements_transactional};
28use super::{ChecksumDrift, ExtensionMigrationStatus, MigrationService};
29use crate::lifecycle::installation::BootstrapLockGuard;
30use crate::services::SqlExecutor;
31use systemprompt_extension::{Extension, LoaderError, Migration};
32use systemprompt_identifiers::{ExtensionId, ToDbValue};
33
34const UPDATE_CHECKSUM_SQL: &str =
35    "UPDATE extension_migrations SET checksum = $3 WHERE extension_id = $1 AND version = $2";
36
37#[derive(Debug, Default, Clone)]
38pub struct RepairResult {
39    pub repaired: Vec<ChecksumDrift>,
40    pub reapplied: usize,
41    pub migrations_run: usize,
42}
43
44impl MigrationService<'_> {
45    pub async fn repair_drift(
46        &self,
47        extension: &dyn Extension,
48    ) -> Result<RepairResult, LoaderError> {
49        if !self.has_repairable_drift(extension).await? {
50            return Ok(RepairResult::default());
51        }
52        let guard = BootstrapLockGuard::acquire(self.db).await?;
53        let outcome = self.repair_drift_locked(extension).await;
54        guard.release().await;
55        outcome
56    }
57
58    pub async fn reconcile_drift(
59        &self,
60        extension: &dyn Extension,
61    ) -> Result<RepairResult, LoaderError> {
62        if !self.has_repairable_drift(extension).await? {
63            return Ok(RepairResult::default());
64        }
65        let guard = BootstrapLockGuard::acquire(self.db).await?;
66        let outcome = self.reconcile_drift_locked(extension).await;
67        guard.release().await;
68        outcome
69    }
70
71    async fn repair_drift_locked(
72        &self,
73        extension: &dyn Extension,
74    ) -> Result<RepairResult, LoaderError> {
75        let status = self.status(extension).await?;
76        Self::refuse_slot_collisions(&status)?;
77        if status.drift.is_empty() {
78            return Ok(RepairResult::default());
79        }
80        self.reapply_drifted(extension, &status.drift).await?;
81        let result = self.run_pending_migrations(extension).await?;
82        Ok(RepairResult {
83            reapplied: status.drift.len(),
84            repaired: status.drift,
85            migrations_run: result.migrations_run,
86        })
87    }
88
89    async fn reconcile_drift_locked(
90        &self,
91        extension: &dyn Extension,
92    ) -> Result<RepairResult, LoaderError> {
93        let status = self.status(extension).await?;
94        Self::refuse_slot_collisions(&status)?;
95        for drift in &status.drift {
96            self.rewrite_checksum(drift).await?;
97        }
98        Ok(RepairResult {
99            repaired: status.drift,
100            reapplied: 0,
101            migrations_run: 0,
102        })
103    }
104
105    async fn has_repairable_drift(&self, extension: &dyn Extension) -> Result<bool, LoaderError> {
106        let status = self.status(extension).await?;
107        Self::refuse_slot_collisions(&status)?;
108        Ok(!status.drift.is_empty())
109    }
110
111    pub fn refuse_slot_collisions(status: &ExtensionMigrationStatus) -> Result<(), LoaderError> {
112        let Some(collision) = status.slot_collisions.first() else {
113            return Ok(());
114        };
115        Err(LoaderError::MigrationSlotReused {
116            extension: collision.extension_id.clone(),
117            version: collision.version,
118            stored_name: collision.stored_name.clone(),
119            current_name: collision.current_name.clone(),
120        })
121    }
122
123    async fn rewrite_checksum(&self, drift: &ChecksumDrift) -> Result<(), LoaderError> {
124        self.db
125            .execute(
126                &UPDATE_CHECKSUM_SQL,
127                &[&drift.extension_id, &drift.version, &drift.current_checksum],
128            )
129            .await
130            .map_err(|e| LoaderError::MigrationStepFailed {
131                extension: drift.extension_id.clone(),
132                context: format!(
133                    "Failed to rewrite checksum for migration {} ('{}')",
134                    drift.version, drift.name
135                ),
136                source: Box::new(e),
137            })?;
138        Ok(())
139    }
140
141    async fn reapply_drifted(
142        &self,
143        extension: &dyn Extension,
144        drift: &[ChecksumDrift],
145    ) -> Result<(), LoaderError> {
146        let ext_id = &ExtensionId::new(extension.metadata().id);
147        let migrations = extension.migrations();
148
149        for d in drift {
150            let migration = migrations
151                .iter()
152                .find(|m| m.version == d.version)
153                .ok_or_else(|| LoaderError::MigrationFailed {
154                    extension: ext_id.clone(),
155                    message: format!(
156                        "Drifted migration {} ('{}') is no longer declared by extension \
157                         '{ext_id}'",
158                        d.version, d.name
159                    ),
160                })?;
161            self.reapply_one(extension, migration, d).await?;
162        }
163
164        Ok(())
165    }
166
167    async fn reapply_one(
168        &self,
169        extension: &dyn Extension,
170        migration: &Migration,
171        drift: &ChecksumDrift,
172    ) -> Result<(), LoaderError> {
173        let ext_id = &ExtensionId::new(extension.metadata().id);
174
175        check_cross_extension_alters(extension, migration)?;
176
177        tracing::info!(
178            extension = %ext_id,
179            version = migration.version,
180            name = %migration.name,
181            no_transaction = migration.no_transaction,
182            "Re-applying drifted migration"
183        );
184
185        let update_params: [&dyn ToDbValue; 3] =
186            [&drift.extension_id, &drift.version, &drift.current_checksum];
187
188        if migration.no_transaction {
189            SqlExecutor::execute_statements_parsed(self.db, migration.sql)
190                .await
191                .map_err(|e| LoaderError::MigrationStepFailed {
192                    extension: ext_id.clone(),
193                    context: format!(
194                        "Failed to re-apply drifted migration {} ({})",
195                        migration.version, migration.name
196                    ),
197                    source: Box::new(e),
198                })?;
199            self.rewrite_checksum(drift).await
200        } else {
201            let statements = SqlExecutor::parse_sql_statements(migration.sql).map_err(|e| {
202                LoaderError::MigrationStepFailed {
203                    extension: ext_id.clone(),
204                    context: format!(
205                        "Failed to parse migration {} ({})",
206                        migration.version, migration.name
207                    ),
208                    source: Box::new(e),
209                }
210            })?;
211            execute_statements_transactional(
212                self.db,
213                &statements,
214                ext_id,
215                migration,
216                Some(TrackingWrite {
217                    sql: UPDATE_CHECKSUM_SQL,
218                    params: &update_params,
219                }),
220            )
221            .await
222        }
223    }
224}