Skip to main content

gaman_core/runner/
diagnostics.rs

1use std::error::Error as StdError;
2
3use serde::{Deserialize, Serialize};
4use thiserror::Error;
5
6use super::adapters::InspectionError;
7use super::protocol::COMMAND_PROTOCOL_VERSION;
8use crate::clarifier::Clarification;
9use crate::graphs::GraphError;
10use crate::migration_engine::{EngineError, ExecutorError, StoreError, TrackingError};
11use crate::offline_planner::OfflineError;
12use crate::redact_diagnostic_text;
13use crate::sql_plan::SqlPlanError;
14use crate::states::ReplayError;
15/// Structured semantic or host-adapter failure from runner command execution.
16#[derive(Debug, Error)]
17pub enum CommandError {
18    /// The host sent a command envelope using an unsupported protocol version.
19    #[error("unsupported command protocol version {observed}; expected {expected}")]
20    UnsupportedProtocolVersion {
21        /// Protocol version accepted by this build.
22        expected: u32,
23        /// Protocol version supplied by the host.
24        observed: u32,
25    },
26    /// Migration generation needs explicit caller-provided clarification decisions.
27    #[error("migration generation needs clarification input")]
28    NeedsInput(Vec<Clarification>),
29    /// Migration lifecycle execution failed.
30    #[error(transparent)]
31    Migration(EngineError),
32    /// Migration storage failed before lifecycle execution completed.
33    #[error(transparent)]
34    Store(StoreError),
35    /// Applied-state tracking failed.
36    #[error(transparent)]
37    Tracking(TrackingError),
38    /// SQL preparation or execution failed.
39    #[error(transparent)]
40    Execution(ExecutorError),
41    /// SQL segmentation failed before database preparation.
42    #[error("SQL parsing failed: {0}")]
43    Parse(String),
44    /// Live catalog inspection failed.
45    #[error(transparent)]
46    Inspection(#[from] InspectionError),
47    /// The host supplied an invalid resolved command.
48    #[error("invalid command: {0}")]
49    Invalid(String),
50}
51
52impl From<EngineError> for CommandError {
53    /// Preserves clarification suspension as a first-class runner error.
54    fn from(error: EngineError) -> Self {
55        match error {
56            EngineError::NeedsInput(clarifications) => Self::NeedsInput(clarifications),
57            EngineError::Store(error) => Self::Store(error),
58            EngineError::Tracking(error) => Self::Tracking(error),
59            EngineError::Executor(error) => Self::Execution(error),
60            error => Self::Migration(error),
61        }
62    }
63}
64
65/// Stable command failure categories shared by non-Rust hosts.
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
67#[serde(rename_all = "snake_case")]
68pub enum DiagnosticCode {
69    /// A transport consumer supplied an unsupported command protocol version.
70    UnsupportedProtocolVersion,
71    /// Migration generation requires explicit decisions.
72    ClarificationRequired,
73    /// The resolved command violates command-level constraints.
74    InvalidCommand,
75    /// Migration storage failed.
76    MigrationStoreFailed,
77    /// Applied-state tracking failed.
78    TrackingFailed,
79    /// SQL preparation or execution failed.
80    ExecutionFailed,
81    /// Live catalog inspection failed.
82    InspectionFailed,
83    /// Offline migration lifecycle work failed.
84    MigrationFailed,
85    /// SQL segmentation failed.
86    ParseFailed,
87}
88
89/// Serializable host-facing diagnostic derived from one [`CommandError`].
90#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
91pub struct CommandDiagnostic {
92    /// Stable diagnostic category.
93    pub code: DiagnosticCode,
94    /// Concise user-facing summary.
95    pub summary: String,
96    /// Optional actionable hint.
97    pub hint: Option<String>,
98    /// Additional concise diagnostic context.
99    pub details: Vec<String>,
100    /// Whether supplying new host input can make the same request succeed.
101    pub retryable: bool,
102}
103
104/// Versioned portable command failure with optional clarification payload.
105#[derive(Debug, Clone, Serialize)]
106pub struct CommandFailure {
107    /// Protocol version used to encode the failure.
108    pub protocol_version: u32,
109    /// Stable human and machine-readable diagnostic.
110    pub diagnostic: CommandDiagnostic,
111    /// Decisions requested from the caller, when applicable.
112    pub clarifications: Vec<Clarification>,
113}
114
115impl CommandError {
116    /// Returns concise shared diagnostic language without discarding the typed error.
117    pub fn diagnostic(&self) -> CommandDiagnostic {
118        match self {
119            Self::UnsupportedProtocolVersion { expected, observed } => command_diagnostic(
120                DiagnosticCode::UnsupportedProtocolVersion,
121                format!("unsupported command protocol version {observed}; expected {expected}"),
122                Some("update the host binding and retry the command".to_string()),
123                Vec::new(),
124                false,
125            ),
126            Self::NeedsInput(_) | Self::Migration(EngineError::NeedsInput(_)) => {
127                command_diagnostic(
128                    DiagnosticCode::ClarificationRequired,
129                    "migration generation needs clarification input".to_string(),
130                    Some("supply decisions and run the command again".to_string()),
131                    Vec::new(),
132                    true,
133                )
134            }
135            Self::Invalid(message) => command_diagnostic(
136                DiagnosticCode::InvalidCommand,
137                message.clone(),
138                None,
139                Vec::new(),
140                false,
141            ),
142            Self::Inspection(error) => inspection_diagnostic(error),
143            Self::Store(error) => adapter_diagnostic(
144                DiagnosticCode::MigrationStoreFailed,
145                "migration storage failed",
146                error,
147                "check the migration directory and resolve any conflicting migration id",
148            ),
149            Self::Tracking(error) => adapter_diagnostic(
150                DiagnosticCode::TrackingFailed,
151                "migration tracking failed",
152                error,
153                "check database connectivity, tracking-table permissions, and migration lock state",
154            ),
155            Self::Execution(error) => adapter_diagnostic(
156                DiagnosticCode::ExecutionFailed,
157                "database operation failed",
158                error,
159                "check database connectivity, permissions, and the reported database error",
160            ),
161            Self::Parse(error) => diagnostic_with_detail(
162                DiagnosticCode::ParseFailed,
163                "SQL parsing failed",
164                error,
165                "correct the SQL input and retry the command",
166                false,
167            ),
168            Self::Migration(error) => migration_diagnostic(error),
169        }
170    }
171
172    /// Returns sanitized internal causes for host-specific verbose diagnostics.
173    pub fn verbose_causes(&self) -> Vec<String> {
174        let mut causes = Vec::new();
175        let mut current: &(dyn StdError + 'static) = self;
176        while let Some(source) = current.source() {
177            let rendered = redact_diagnostic_text(&source.to_string());
178            if causes.last() != Some(&rendered) {
179                causes.push(rendered);
180            }
181            current = source;
182        }
183        if causes.is_empty() {
184            causes.push(redact_diagnostic_text(&self.to_string()));
185        }
186        causes
187    }
188
189    /// Returns a serializable failure preserving typed clarification requests.
190    pub fn failure(&self) -> CommandFailure {
191        let clarifications = match self {
192            Self::NeedsInput(clarifications)
193            | Self::Migration(EngineError::NeedsInput(clarifications)) => clarifications.clone(),
194            _ => Vec::new(),
195        };
196        CommandFailure {
197            protocol_version: COMMAND_PROTOCOL_VERSION,
198            diagnostic: self.diagnostic(),
199            clarifications,
200        }
201    }
202}
203
204/// Projects one migration-engine error without discarding nested lifecycle context.
205fn migration_diagnostic(error: &EngineError) -> CommandDiagnostic {
206    match error {
207        EngineError::MigrationExecution {
208            migration,
209            direction,
210            statement_ordinal,
211            statement,
212            source,
213        } => execution_diagnostic(migration, direction, *statement_ordinal, statement, source),
214        EngineError::Graph(error) => graph_diagnostic(error),
215        EngineError::Offline(error) => offline_diagnostic(error),
216        EngineError::SqlPlan(error) => sql_plan_diagnostic(error),
217        EngineError::Config(message) => diagnostic_with_detail(
218            DiagnosticCode::MigrationFailed,
219            "migration command cannot run",
220            message,
221            "correct the migration configuration and retry the command",
222            false,
223        ),
224        EngineError::NeedsInput(_) => command_diagnostic(
225            DiagnosticCode::ClarificationRequired,
226            "migration generation needs clarification input".to_string(),
227            Some("supply decisions and run the command again".to_string()),
228            Vec::new(),
229            true,
230        ),
231        EngineError::Store(error) => adapter_diagnostic(
232            DiagnosticCode::MigrationStoreFailed,
233            "migration storage failed",
234            error,
235            "check the migration directory and resolve any conflicting migration id",
236        ),
237        EngineError::Tracking(error) => adapter_diagnostic(
238            DiagnosticCode::TrackingFailed,
239            "migration tracking failed",
240            error,
241            "check database connectivity, tracking-table permissions, and migration lock state",
242        ),
243        EngineError::Executor(error) => adapter_diagnostic(
244            DiagnosticCode::ExecutionFailed,
245            "database operation failed",
246            error,
247            "check database connectivity, permissions, and the reported database error",
248        ),
249    }
250}
251
252/// Projects one rendered migration statement failure without exposing its complete SQL text.
253fn execution_diagnostic(
254    migration: &str,
255    direction: &str,
256    statement_ordinal: usize,
257    statement: &crate::migration_engine::execution_diagnostic::StatementDiagnostic,
258    source: &ExecutorError,
259) -> CommandDiagnostic {
260    let mut details = vec![
261        format!("migration: {migration}"),
262        format!(
263            "{direction} statement {statement_ordinal}: {}",
264            statement.signature
265        ),
266        database_failure_detail(source),
267    ];
268    if let Some(location) = &statement.location {
269        details.push(format!(
270            "at {} line {}, column {}",
271            location.source.label(),
272            location.line,
273            location.column
274        ));
275        details.push(format!("  {}", location.excerpt));
276        details.push(format!("  {}^", " ".repeat(location.caret_offset)));
277    }
278    command_diagnostic(
279        DiagnosticCode::ExecutionFailed,
280        "database operation failed".to_string(),
281        Some(format!(
282            "inspect migration '{migration}' with `gaman show {migration}`"
283        )),
284        details,
285        false,
286    )
287}
288
289/// Formats a stable database message without relying on driver display text conventions.
290fn database_failure_detail(error: &ExecutorError) -> String {
291    match error.database_failure() {
292        Some(failure) => match &failure.code {
293            Some(code) => format!("execute failed [{code}]: {}", failure.message),
294            None => format!("execute failed: {}", failure.message),
295        },
296        None => error.to_string(),
297    }
298}
299
300/// Projects planning failures by preserving the most actionable nested category.
301fn offline_diagnostic(error: &OfflineError) -> CommandDiagnostic {
302    match error {
303        OfflineError::Graph(error) => graph_diagnostic(error),
304        OfflineError::Replay(error) => replay_diagnostic(error),
305        OfflineError::SqlPlan(error) => sql_plan_diagnostic(error),
306        OfflineError::Schema(message) => diagnostic_with_detail(
307            DiagnosticCode::MigrationFailed,
308            "schema validation failed during migration planning",
309            message,
310            "correct the schema or migration history and retry the command",
311            false,
312        ),
313        OfflineError::NeedsInput(_) => command_diagnostic(
314            DiagnosticCode::ClarificationRequired,
315            "migration generation needs clarification input".to_string(),
316            Some("supply decisions and run the command again".to_string()),
317            Vec::new(),
318            true,
319        ),
320        _ => diagnostic_with_detail(
321            DiagnosticCode::MigrationFailed,
322            "migration planning failed",
323            error,
324            "correct the reported schema or migration definition and retry the command",
325            false,
326        ),
327    }
328}
329
330/// Projects SQL planning failures while retaining replay and graph causes.
331fn sql_plan_diagnostic(error: &SqlPlanError) -> CommandDiagnostic {
332    match error {
333        SqlPlanError::Graph(error) => graph_diagnostic(error),
334        SqlPlanError::Replay(error) => replay_diagnostic(error),
335        _ => diagnostic_with_detail(
336            DiagnosticCode::MigrationFailed,
337            "migration SQL planning failed",
338            error,
339            "correct the reported migration or use explicit SQL for unsupported changes",
340            false,
341        ),
342    }
343}
344
345/// Projects replay errors with migration and operation context in normal output.
346fn replay_diagnostic(error: &ReplayError) -> CommandDiagnostic {
347    match error {
348        ReplayError::WithContext {
349            migration,
350            op_num,
351            operation,
352            inner,
353        } => command_diagnostic(
354            DiagnosticCode::MigrationFailed,
355            format!("cannot replay migration '{migration}'"),
356            Some(replay_hint(inner)),
357            vec![format!("operation {op_num} ({operation}): {}", inner)],
358            false,
359        ),
360        _ => diagnostic_with_detail(
361            DiagnosticCode::MigrationFailed,
362            "cannot replay migration history",
363            error,
364            "correct the reported migration definition and retry the command",
365            false,
366        ),
367    }
368}
369
370fn replay_hint(error: &ReplayError) -> String {
371    match error {
372        ReplayError::InvalidOpaqueCreate { .. } => {
373            "replace the opaque source with one plain CREATE statement; Gaman owns existence and replacement"
374                .to_string()
375        }
376        _ => "correct the migration order or restore the missing prerequisite migration".to_string(),
377    }
378}
379
380/// Projects invalid migration-graph state into a corrective diagnostic.
381fn graph_diagnostic(error: &GraphError) -> CommandDiagnostic {
382    diagnostic_with_detail(
383        DiagnosticCode::MigrationFailed,
384        "migration graph is invalid",
385        error,
386        graph_hint(error),
387        false,
388    )
389}
390
391/// Returns the narrowest safe remediation for a migration-graph failure.
392fn graph_hint(error: &GraphError) -> &'static str {
393    match error {
394        GraphError::DuplicateId(_) => "rename or remove the duplicate migration id",
395        GraphError::CycleDetected => "remove the dependency cycle between migrations",
396        GraphError::Conflict => "run make --merge after resolving the competing migration heads",
397        GraphError::UnknownDependency { .. } => {
398            "restore the referenced dependency or correct the migration dependencies"
399        }
400        GraphError::InvalidId(_) => "rename the migration using a valid lowercase id",
401        GraphError::UnknownId(_) | GraphError::AmbiguousId { .. } => {
402            "use one exact migration id or an unambiguous prefix"
403        }
404        GraphError::Empty => "create a migration before requesting this operation",
405    }
406}
407
408/// Projects catalog inspection errors without exposing host-adapter internals in the summary.
409fn inspection_diagnostic(error: &InspectionError) -> CommandDiagnostic {
410    diagnostic_with_detail(
411        DiagnosticCode::InspectionFailed,
412        "database inspection failed",
413        error,
414        "check database connectivity, selected namespaces, and catalog permissions",
415        true,
416    )
417}
418
419/// Projects one host adapter failure with stable action wording and sanitized detail.
420fn adapter_diagnostic(
421    code: DiagnosticCode,
422    summary: &str,
423    error: &impl std::fmt::Display,
424    hint: &str,
425) -> CommandDiagnostic {
426    diagnostic_with_detail(code, summary, error, hint, false)
427}
428
429/// Creates one protocol-v2 diagnostic while keeping sensitive adapter text out of public fields.
430fn diagnostic_with_detail(
431    code: DiagnosticCode,
432    summary: &str,
433    detail: &impl std::fmt::Display,
434    hint: &str,
435    retryable: bool,
436) -> CommandDiagnostic {
437    command_diagnostic(
438        code,
439        summary.to_string(),
440        Some(hint.to_string()),
441        vec![detail.to_string()],
442        retryable,
443    )
444}
445
446/// Constructs a diagnostic after redacting every potentially adapter-controlled field.
447fn command_diagnostic(
448    code: DiagnosticCode,
449    summary: String,
450    hint: Option<String>,
451    details: Vec<String>,
452    retryable: bool,
453) -> CommandDiagnostic {
454    CommandDiagnostic {
455        code,
456        summary: redact_diagnostic_text(&summary),
457        hint: hint.map(|value| redact_diagnostic_text(&value)),
458        details: details
459            .into_iter()
460            .map(|value| redact_diagnostic_text(&value))
461            .collect(),
462        retryable,
463    }
464}
465
466#[cfg(test)]
467mod tests {
468    use super::*;
469
470    /// Verifies protocol mismatches use the current protocol-v6 diagnostic contract.
471    #[test]
472    fn protocol_mismatch_is_structured() {
473        let failure = CommandError::UnsupportedProtocolVersion {
474            expected: COMMAND_PROTOCOL_VERSION,
475            observed: 1,
476        }
477        .failure();
478
479        assert_eq!(failure.protocol_version, 6);
480        assert_eq!(
481            failure.diagnostic.code,
482            DiagnosticCode::UnsupportedProtocolVersion
483        );
484        assert!(!failure.diagnostic.retryable);
485    }
486
487    /// Verifies replay diagnostics preserve migration, operation, and root-cause context.
488    #[test]
489    fn replay_failure_is_actionable() {
490        let error = CommandError::Migration(EngineError::Offline(OfflineError::Replay(
491            ReplayError::WithContext {
492                migration: "0002_add_posts".to_string(),
493                op_num: 2,
494                operation: "add foreign key posts.author_id".to_string(),
495                inner: Box::new(ReplayError::TableNotFound("posts".to_string())),
496            },
497        )));
498
499        let diagnostic = error.diagnostic();
500        assert_eq!(diagnostic.code, DiagnosticCode::MigrationFailed);
501        assert_eq!(
502            diagnostic.summary,
503            "cannot replay migration '0002_add_posts'"
504        );
505        assert_eq!(
506            diagnostic.details,
507            ["operation 2 (add foreign key posts.author_id): table 'posts' not found"]
508        );
509        assert!(
510            diagnostic
511                .hint
512                .as_deref()
513                .is_some_and(|hint| hint.contains("migration order"))
514        );
515    }
516
517    /// Verifies opaque migration failures explain the plain-CREATE remediation.
518    #[test]
519    fn opaque_create_replay_failure_has_specific_hint() {
520        let error = CommandError::Migration(EngineError::Offline(OfflineError::Replay(
521            ReplayError::WithContext {
522                migration: "0003_active_users".to_string(),
523                op_num: 1,
524                operation: "create view active_users".to_string(),
525                inner: Box::new(ReplayError::InvalidOpaqueCreate {
526                    entity: "active_users".to_string(),
527                    reason: "CREATE OR REPLACE is not accepted; Gaman owns replacement".to_string(),
528                }),
529            },
530        )));
531
532        let diagnostic = error.diagnostic();
533        assert!(diagnostic.details[0].contains("CREATE OR REPLACE"));
534        assert!(
535            diagnostic
536                .hint
537                .as_deref()
538                .is_some_and(|hint| hint.contains("plain CREATE"))
539        );
540    }
541
542    /// Verifies adapter text cannot expose URL credentials or common secret assignments.
543    #[test]
544    fn diagnostics_redact_sensitive_adapter_text() {
545        let error = CommandError::Execution(ExecutorError::Connect(
546            "postgres://gaman:secret@localhost/app password=hunter2 token=abc".to_string(),
547        ));
548
549        let diagnostic = error.diagnostic();
550        let detail = &diagnostic.details[0];
551        assert!(!detail.contains("secret"));
552        assert!(!detail.contains("hunter2"));
553        assert!(!detail.contains("abc"));
554        assert!(detail.contains("gaman:***@localhost"));
555        let failure = serde_json::to_string(&error.failure()).expect("serialize command failure");
556        assert!(!failure.contains("secret"));
557        assert!(!error.verbose_causes().join(" ").contains("hunter2"));
558    }
559
560    /// Verifies migration execution diagnostics retain bounded statement context and SQLSTATE.
561    #[test]
562    fn migration_execution_failure_is_compact_and_actionable() {
563        let error = CommandError::Migration(EngineError::MigrationExecution {
564            migration: "0012_reports".to_string(),
565            direction: "apply",
566            statement_ordinal: 1,
567            statement: Box::new(crate::migration_engine::execution_diagnostic::StatementDiagnostic {
568                signature: "CREATE OR REPLACE FUNCTION dynrs_daily_report()".to_string(),
569                location: Some(
570                    crate::migration_engine::execution_diagnostic::StatementLocation {
571                        source: crate::migration_engine::execution_diagnostic::StatementLocationSource::Internal,
572                        line: 18,
573                        column: 9,
574                        excerpt: "SELECT session_type_provider_tip".to_string(),
575                        caret_offset: 8,
576                    },
577                ),
578            }),
579            source: Box::new(ExecutorError::ExecuteDatabase(
580                crate::migration_engine::DatabaseFailure::message(
581                    "column reference is ambiguous",
582                )
583                .with_code("42702"),
584            )),
585        });
586        let diagnostic = error.diagnostic();
587        assert_eq!(diagnostic.summary, "database operation failed");
588        assert!(
589            diagnostic
590                .details
591                .iter()
592                .any(|detail| detail == "migration: 0012_reports")
593        );
594        assert!(
595            diagnostic.details.iter().any(|detail| {
596                detail == "execute failed [42702]: column reference is ambiguous"
597            })
598        );
599        assert!(
600            diagnostic
601                .hint
602                .as_deref()
603                .is_some_and(|hint| hint.contains("gaman show 0012_reports"))
604        );
605    }
606}