pubsat 0.1.0

Building blocks for SAT-based dependency resolvers: a node-semver-compatible range parser, an ecosystem-independent constraint vocabulary, and a backend-agnostic SAT problem/solver abstraction with a Varisat backend.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
//! Error types for dependency resolution
//!
//! This module defines comprehensive error types for all resolution scenarios,
//! from SAT solver failures to dependency conflicts and version
//! incompatibilities.

use std::time::Duration;

use thiserror::Error;

/// Main error type for dependency resolution operations
#[derive(Debug, Error)]
pub enum ResolutionError {
    /// SAT solver encountered an error
    #[error("SAT solver error: {0}")]
    Solver(#[from] SatError),

    /// No solution exists for the given constraints
    #[error("Dependency conflict: {message}")]
    Conflict {
        message: String,
        conflicts: Vec<ConflictDetail>,
    },

    /// Resolution timed out
    #[error("Resolution timed out after {timeout:?}")]
    Timeout { timeout: Duration },

    /// Invalid package specification
    #[error("Invalid package specification: {package} {version}")]
    InvalidPackage { package: String, version: String },

    /// Version constraint is malformed
    #[error("Invalid version constraint: '{constraint}' for package {package}")]
    InvalidConstraint { package: String, constraint: String },

    /// Circular dependency detected
    #[error("Circular dependency detected: {cycle}")]
    CircularDependency { cycle: String },

    /// Registry communication failed
    #[error("Registry error: {0}")]
    Registry(#[from] anyhow::Error),

    /// Registry specific error
    #[error("Registry error: {message}")]
    RegistryError { message: String },

    /// Invalid version constraint (alias for InvalidConstraint)
    #[error("Invalid version constraint: '{constraint}' for package {package}")]
    InvalidVersionConstraint { package: String, constraint: String },

    /// Package not found in registry
    #[error("Package not found: {package}@{version}")]
    PackageNotFound { package: String, version: String },

    /// Peer dependency cannot be satisfied
    #[error("Peer dependency conflict: {package} requires {peer} {constraint}")]
    PeerConflict {
        package: String,
        peer: String,
        constraint: String,
        reason: String,
    },

    /// Optional dependency resolution failed (warning, not fatal)
    #[error("Optional dependency unavailable: {package}@{version}")]
    OptionalUnavailable { package: String, version: String },

    /// Internal resolver error (shouldn't happen in normal operation)
    #[error("Internal resolver error: {message}")]
    Internal { message: String },
}

/// SAT solver specific errors
#[derive(Debug, Error)]
pub enum SatError {
    /// SAT solver initialization failed
    #[error("Failed to initialize SAT solver: {reason}")]
    InitializationFailed { reason: String },

    /// Problem encoding failed
    #[error("Failed to encode problem: {reason}")]
    EncodingFailed { reason: String },

    /// Solver crashed or returned invalid result
    #[error("SAT solver failure: {reason}")]
    SolverFailure { reason: String },

    /// Problem is unsatisfiable (no solution)
    #[error("Problem is unsatisfiable")]
    Unsatisfiable,

    /// Solver timed out
    #[error("SAT solver timed out after {duration:?}")]
    Timeout { duration: Duration },

    /// Out of memory during solving
    #[error("SAT solver ran out of memory")]
    OutOfMemory,

    /// Invalid model returned by solver
    #[error("Invalid solution model from solver")]
    InvalidModel,

    /// Clause generation error
    #[error("Failed to generate clauses: {reason}")]
    ClauseGeneration { reason: String },
}

/// Details about a specific dependency conflict
#[derive(Debug, Clone)]
pub struct ConflictDetail {
    /// Package that has the conflict
    pub package: String,
    /// Version or constraint causing the conflict
    pub constraint: String,
    /// Conflicting package
    pub conflicts_with: String,
    /// Reason for the conflict
    pub reason: ConflictReason,
}

/// Types of dependency conflicts
#[derive(Debug, Clone)]
pub enum ConflictReason {
    /// Version ranges don't overlap
    VersionIncompatible,
    /// Peer dependency cannot be satisfied
    PeerDependency,
    /// Circular dependency
    CircularDependency,
    /// Package not found
    PackageNotFound,
    /// Engine incompatibility (node version, etc.)
    EngineIncompatible,
    /// Platform incompatibility (OS, architecture)
    PlatformIncompatible,
}

impl ConflictDetail {
    /// Create a new conflict detail
    pub fn new(
        package: String,
        constraint: String,
        conflicts_with: String,
        reason: ConflictReason,
    ) -> Self {
        Self {
            package,
            constraint,
            conflicts_with,
            reason,
        }
    }

    /// Create a version incompatibility conflict
    pub fn version_conflict(package: String, constraint: String, conflicts_with: String) -> Self {
        Self::new(
            package,
            constraint,
            conflicts_with,
            ConflictReason::VersionIncompatible,
        )
    }

    /// Create a peer dependency conflict
    pub fn peer_conflict(package: String, constraint: String, conflicts_with: String) -> Self {
        Self::new(
            package,
            constraint,
            conflicts_with,
            ConflictReason::PeerDependency,
        )
    }
}

impl ResolutionError {
    /// Create a conflict error with details
    pub fn conflict(message: String, conflicts: Vec<ConflictDetail>) -> Self {
        Self::Conflict { message, conflicts }
    }

    /// Create a simple conflict error
    pub fn simple_conflict(message: String) -> Self {
        Self::Conflict {
            message,
            conflicts: Vec::new(),
        }
    }

    /// Create a timeout error
    pub fn timeout(timeout: Duration) -> Self {
        Self::Timeout { timeout }
    }

    /// Create an invalid package error
    pub fn invalid_package(package: String, version: String) -> Self {
        Self::InvalidPackage { package, version }
    }

    /// Create a no matching versions error  
    pub fn no_matching_versions(package: String, version_set: crate::version::VersionSet) -> Self {
        Self::InvalidPackage {
            package: format!("{} with constraint {}", package, version_set),
            version: "no matching versions".to_string(),
        }
    }

    /// Create an invalid constraint error
    pub fn invalid_constraint(package: String, constraint: String) -> Self {
        Self::InvalidConstraint {
            package,
            constraint,
        }
    }

    /// Create a circular dependency error
    pub fn circular_dependency(cycle: String) -> Self {
        Self::CircularDependency { cycle }
    }

    /// Create a package not found error
    pub fn package_not_found(package: String, version: String) -> Self {
        Self::PackageNotFound { package, version }
    }

    /// Create a peer dependency conflict error
    pub fn peer_conflict(
        package: String,
        peer: String,
        constraint: String,
        reason: String,
    ) -> Self {
        Self::PeerConflict {
            package,
            peer,
            constraint,
            reason,
        }
    }

    /// Create an internal error
    pub fn internal(message: String) -> Self {
        Self::Internal { message }
    }

    /// Check if this error represents a conflict that might be resolvable
    pub fn is_resolvable_conflict(&self) -> bool {
        matches!(
            self,
            Self::Conflict { .. } | Self::PeerConflict { .. } | Self::InvalidConstraint { .. }
        )
    }

    /// Check if this error is fatal (no point in retrying)
    pub fn is_fatal(&self) -> bool {
        matches!(
            self,
            Self::CircularDependency { .. }
                | Self::PackageNotFound { .. }
                | Self::InvalidPackage { .. }
                | Self::Internal { .. }
        )
    }

    /// Get a user-friendly error message with suggestions
    pub fn user_message(&self) -> String {
        match self {
            Self::Conflict { message, conflicts } => {
                let mut msg = format!("Dependency conflict: {}", message);
                if !conflicts.is_empty() {
                    msg.push_str("\n\nConflicts:");
                    for conflict in conflicts {
                        msg.push_str(&format!(
                            "\n  • {} {} conflicts with {}",
                            conflict.package, conflict.constraint, conflict.conflicts_with
                        ));
                    }
                    msg.push_str(
                        "\n\nTry:\n  • Update conflicting packages\n  • Use --force to override \
                         (not recommended)",
                    );
                }
                msg
            }
            Self::PackageNotFound { package, version } => {
                format!(
                    "Package not found: {}@{}\n\nTry:\n  • Check package name spelling\n  • \
                     Verify version exists\n  • Check registry configuration",
                    package, version
                )
            }
            Self::CircularDependency { cycle } => {
                format!(
                    "Circular dependency detected: {}\n\nThis indicates a problem with the \
                     packages themselves.",
                    cycle
                )
            }
            _ => self.to_string(),
        }
    }
}

impl SatError {
    /// Create an initialization failed error
    pub fn initialization_failed(reason: String) -> Self {
        Self::InitializationFailed { reason }
    }

    /// Create an encoding failed error
    pub fn encoding_failed(reason: String) -> Self {
        Self::EncodingFailed { reason }
    }

    /// Create a solver failure error
    pub fn solver_failure(reason: String) -> Self {
        Self::SolverFailure { reason }
    }

    /// Create a timeout error
    pub fn timeout(duration: Duration) -> Self {
        Self::Timeout { duration }
    }

    /// Create a clause generation error
    pub fn clause_generation(reason: String) -> Self {
        Self::ClauseGeneration { reason }
    }

    /// Check if the error indicates the problem is unsatisfiable
    pub fn is_unsatisfiable(&self) -> bool {
        matches!(self, Self::Unsatisfiable)
    }

    /// Check if the error indicates a solver failure
    pub fn is_solver_failure(&self) -> bool {
        matches!(
            self,
            Self::SolverFailure { .. } | Self::OutOfMemory | Self::InvalidModel
        )
    }
}

/// Result type for resolution operations
pub type ResolutionResult<T> = std::result::Result<T, ResolutionError>;

/// Result type for SAT operations  
pub type SatResult<T> = std::result::Result<T, SatError>;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_conflict_detail_creation() {
        let conflict = ConflictDetail::version_conflict(
            "lodash".to_string(),
            "^4.0.0".to_string(),
            "lodash@3.10.1".to_string(),
        );

        assert_eq!(conflict.package, "lodash");
        assert_eq!(conflict.constraint, "^4.0.0");
        assert_eq!(conflict.conflicts_with, "lodash@3.10.1");
        assert!(matches!(
            conflict.reason,
            ConflictReason::VersionIncompatible
        ));
    }

    #[test]
    fn test_resolution_error_classification() {
        let conflict = ResolutionError::simple_conflict("test conflict".to_string());
        assert!(conflict.is_resolvable_conflict());
        assert!(!conflict.is_fatal());

        let circular = ResolutionError::circular_dependency("A -> B -> A".to_string());
        assert!(!circular.is_resolvable_conflict());
        assert!(circular.is_fatal());

        let not_found =
            ResolutionError::package_not_found("missing".to_string(), "1.0.0".to_string());
        assert!(!not_found.is_resolvable_conflict());
        assert!(not_found.is_fatal());
    }

    #[test]
    fn test_sat_error_classification() {
        let unsatisfiable = SatError::Unsatisfiable;
        assert!(unsatisfiable.is_unsatisfiable());
        assert!(!unsatisfiable.is_solver_failure());

        let failure = SatError::solver_failure("crashed".to_string());
        assert!(!failure.is_unsatisfiable());
        assert!(failure.is_solver_failure());

        let timeout = SatError::timeout(Duration::from_secs(30));
        assert!(!timeout.is_unsatisfiable());
        assert!(!timeout.is_solver_failure());
    }

    #[test]
    fn test_user_friendly_messages() {
        let conflict =
            ResolutionError::package_not_found("lodash".to_string(), "999.0.0".to_string());
        let message = conflict.user_message();
        assert!(message.contains("Package not found"));
        assert!(message.contains("Check package name spelling"));
    }
}