Skip to main content

ggen_core/codegen/
incremental.rs

1//! # Incremental Code Generator with SHA256-based JIT (Phase 4)
2//!
3//! This module implements incremental code generation that skips unchanged files
4//! using SHA256 content hashing and specification hash comparison.
5//!
6//! **Performance Target**: Skip ~70-80% of files when spec unchanged
7//! **SLO**: <60s for 10+ specs with incremental generation
8
9use crate::utils::error::{Error, Result};
10use sha2::{Digest, Sha256};
11use std::collections::HashMap;
12use std::fs;
13use std::io::Read;
14use std::path::{Path, PathBuf};
15
16/// Represents results of content hash computation
17#[derive(Debug, Clone)]
18pub struct ContentHash {
19    /// SHA256 hash of file content
20    pub hash: String,
21    /// File path that was hashed
22    pub file_path: PathBuf,
23}
24
25impl ContentHash {
26    /// Create new content hash
27    pub fn new(hash: String, file_path: PathBuf) -> Self {
28        Self { hash, file_path }
29    }
30}
31
32/// Represents state of a generated file for incremental checking
33#[derive(Debug, Clone)]
34pub struct FileState {
35    /// SHA256 hash of file content
36    pub content_hash: String,
37    /// SHA256 hash of the specification that generated this file
38    pub spec_hash: String,
39    /// File path
40    pub file_path: PathBuf,
41    /// Modification timestamp
42    pub timestamp: u64,
43}
44
45impl FileState {
46    /// Create new file state
47    pub fn new(
48        content_hash: String, spec_hash: String, file_path: PathBuf, timestamp: u64,
49    ) -> Self {
50        Self {
51            content_hash,
52            spec_hash,
53            file_path,
54            timestamp,
55        }
56    }
57
58    /// Check if file needs regeneration
59    pub fn needs_regeneration(&self, current_spec_hash: &str) -> bool {
60        self.spec_hash != current_spec_hash
61    }
62}
63
64/// Cache for file states keyed by file path
65#[derive(Debug, Clone, Default)]
66pub struct IncrementalCache {
67    /// Map of file paths to their states
68    states: HashMap<PathBuf, FileState>,
69    /// Total files in cache
70    cache_size: usize,
71}
72
73impl IncrementalCache {
74    /// Create new empty cache
75    pub fn new() -> Self {
76        Self {
77            states: HashMap::new(),
78            cache_size: 0,
79        }
80    }
81
82    /// Get file state from cache
83    pub fn get(&self, path: &Path) -> Option<&FileState> {
84        self.states.get(path)
85    }
86
87    /// Insert file state into cache
88    pub fn insert(&mut self, path: PathBuf, state: FileState) {
89        self.states.insert(path, state);
90        self.cache_size = self.states.len();
91    }
92
93    /// Check if file is in cache
94    pub fn contains(&self, path: &Path) -> bool {
95        self.states.contains_key(path)
96    }
97
98    /// Get cache size (number of files)
99    pub fn size(&self) -> usize {
100        self.cache_size
101    }
102
103    /// Clear entire cache
104    pub fn clear(&mut self) {
105        self.states.clear();
106        self.cache_size = 0;
107    }
108}
109
110/// Configuration for incremental generation
111#[derive(Debug, Clone)]
112pub struct IncrementalConfig {
113    /// Use caching (can be disabled for force regeneration)
114    pub use_cache: bool,
115    /// Maximum cache size in MB (0 = unlimited)
116    pub max_cache_size_mb: u64,
117}
118
119impl Default for IncrementalConfig {
120    fn default() -> Self {
121        Self {
122            use_cache: true,
123            max_cache_size_mb: 0, // Unlimited
124        }
125    }
126}
127
128/// Results of incremental generation
129#[derive(Debug, Clone)]
130pub struct IncrementalResult {
131    /// Total files requested
132    pub total_files: usize,
133    /// Files that were regenerated
134    pub regenerated_files: usize,
135    /// Files that were skipped (already up-to-date)
136    pub skipped_files: usize,
137    /// Skip percentage (skipped / total * 100)
138    pub skip_percentage: f64,
139    /// Files that errored
140    pub error_files: usize,
141}
142
143impl IncrementalResult {
144    /// Create new result
145    pub fn new(
146        total_files: usize, regenerated_files: usize, skipped_files: usize, error_files: usize,
147    ) -> Self {
148        let skip_percentage = if total_files > 0 {
149            (skipped_files as f64 / total_files as f64) * 100.0
150        } else {
151            0.0
152        };
153
154        Self {
155            total_files,
156            regenerated_files,
157            skipped_files,
158            error_files,
159            skip_percentage,
160        }
161    }
162
163    /// Check if all files passed (no errors)
164    pub fn all_passed(&self) -> bool {
165        self.error_files == 0
166    }
167}
168
169/// Incremental code generator with SHA256-based JIT
170#[derive(Default)]
171pub struct IncrementalGenerator {
172    /// In-memory cache of file states
173    cache: IncrementalCache,
174    /// Configuration
175    config: IncrementalConfig,
176}
177
178impl IncrementalGenerator {
179    /// Create new incremental generator
180    pub fn new(config: IncrementalConfig) -> Self {
181        Self {
182            cache: IncrementalCache::new(),
183            config,
184        }
185    }
186
187    /// Create with default configuration
188    pub fn with_default_config() -> Self {
189        Self::new(IncrementalConfig::default())
190    }
191
192    /// Compute SHA256 hash of file content
193    pub fn compute_content_hash(file_path: &Path) -> Result<String> {
194        let mut file = fs::File::open(file_path).map_err(|e| {
195            Error::io_error(format!(
196                "Failed to open file '{}': {}",
197                file_path.display(),
198                e
199            ))
200        })?;
201
202        let mut hasher = Sha256::new();
203        let mut buffer = [0; 8192]; // 8KB buffer for streaming
204
205        loop {
206            let bytes_read = file.read(&mut buffer).map_err(|e| {
207                Error::io_error(format!(
208                    "Failed to read file '{}': {}",
209                    file_path.display(),
210                    e
211                ))
212            })?;
213
214            if bytes_read == 0 {
215                break;
216            }
217
218            hasher.update(&buffer[..bytes_read]);
219        }
220
221        let hash = hasher.finalize();
222        Ok(format!("{:x}", hash))
223    }
224
225    /// Compute SHA256 hash of string (e.g., specification)
226    pub fn compute_string_hash(content: &str) -> String {
227        let mut hasher = Sha256::new();
228        hasher.update(content.as_bytes());
229        let hash = hasher.finalize();
230        format!("{:x}", hash)
231    }
232
233    /// Check if file should be regenerated
234    pub fn should_regenerate(&self, file_path: &Path, current_spec_hash: &str) -> Result<bool> {
235        if !self.config.use_cache {
236            // Force regeneration if caching disabled
237            return Ok(true);
238        }
239
240        // If file not in cache, regenerate
241        let Some(cached_state) = self.cache.get(file_path) else {
242            return Ok(true);
243        };
244
245        // If spec hash changed, regenerate
246        if cached_state.needs_regeneration(current_spec_hash) {
247            return Ok(true);
248        }
249
250        // Check if file still exists and content matches cache
251        if !file_path.exists() {
252            return Ok(true); // File deleted, regenerate
253        }
254
255        let current_content_hash = Self::compute_content_hash(file_path)?;
256        Ok(current_content_hash != cached_state.content_hash)
257    }
258
259    /// Store generated file state in cache
260    pub fn store_file_state(&mut self, file_path: PathBuf, spec_hash: &str) -> Result<()> {
261        let content_hash = Self::compute_content_hash(&file_path)?;
262        let timestamp = std::time::SystemTime::now()
263            .duration_since(std::time::UNIX_EPOCH)
264            .map_err(|e| Error::io_error(format!("Failed to get timestamp: {}", e)))?
265            .as_secs();
266
267        let file_state = FileState::new(
268            content_hash,
269            spec_hash.to_string(),
270            file_path.clone(),
271            timestamp,
272        );
273
274        self.cache.insert(file_path, file_state);
275        Ok(())
276    }
277
278    /// Process a batch of files with incremental checking
279    /// Returns which files need regeneration
280    pub fn check_files(&self, files: &[PathBuf], spec_hash: &str) -> Result<Vec<bool>> {
281        let mut results = Vec::with_capacity(files.len());
282
283        for file_path in files {
284            let needs_regen = self.should_regenerate(file_path, spec_hash)?;
285            results.push(needs_regen);
286        }
287
288        Ok(results)
289    }
290
291    /// Get cache size (number of cached files)
292    pub fn cache_size(&self) -> usize {
293        self.cache.size()
294    }
295
296    /// Clear the cache
297    pub fn clear_cache(&mut self) {
298        self.cache.clear();
299    }
300
301    /// Get reference to cache (read-only)
302    pub fn get_cache(&self) -> &IncrementalCache {
303        &self.cache
304    }
305}
306
307#[cfg(test)]
308mod tests {
309    use super::*;
310    use tempfile::tempdir;
311
312    #[test]
313    fn test_compute_content_hash() -> Result<()> {
314        let dir = tempdir().map_err(|e| Error::io_error(format!("{}", e)))?;
315        let file_path = dir.path().join("test.txt");
316
317        fs::write(&file_path, b"hello world").map_err(|e| Error::io_error(format!("{}", e)))?;
318
319        let hash1 = IncrementalGenerator::compute_content_hash(&file_path)?;
320        let hash2 = IncrementalGenerator::compute_content_hash(&file_path)?;
321
322        // Same content should produce same hash (deterministic)
323        assert_eq!(hash1, hash2);
324        assert!(!hash1.is_empty());
325
326        Ok(())
327    }
328
329    #[test]
330    fn test_compute_string_hash() {
331        let hash1 = IncrementalGenerator::compute_string_hash("test content");
332        let hash2 = IncrementalGenerator::compute_string_hash("test content");
333        let hash3 = IncrementalGenerator::compute_string_hash("different content");
334
335        // Same content produces same hash
336        assert_eq!(hash1, hash2);
337        // Different content produces different hash
338        assert_ne!(hash1, hash3);
339    }
340
341    #[test]
342    fn test_incremental_cache_operations() -> Result<()> {
343        let mut cache = IncrementalCache::new();
344        let path = PathBuf::from("test.rs");
345
346        assert!(!cache.contains(&path));
347        assert_eq!(cache.size(), 0);
348
349        let state = FileState::new(
350            "abc123".to_string(),
351            "def456".to_string(),
352            path.clone(),
353            12345,
354        );
355
356        cache.insert(path.clone(), state);
357        assert!(cache.contains(&path));
358        assert_eq!(cache.size(), 1);
359
360        let retrieved = cache.get(&path);
361        assert!(retrieved.is_some());
362        assert_eq!(retrieved.unwrap().content_hash, "abc123");
363
364        cache.clear();
365        assert!(!cache.contains(&path));
366        assert_eq!(cache.size(), 0);
367
368        Ok(())
369    }
370
371    #[test]
372    fn test_should_regenerate_force_mode() -> Result<()> {
373        let config = IncrementalConfig {
374            use_cache: false, // Force regeneration
375            max_cache_size_mb: 0,
376        };
377        let gen = IncrementalGenerator::new(config);
378
379        let dir = tempdir().map_err(|e| Error::io_error(format!("{}", e)))?;
380        let file_path = dir.path().join("test.rs");
381        fs::write(&file_path, b"code").map_err(|e| Error::io_error(format!("{}", e)))?;
382
383        // Force mode always regenerates
384        assert!(gen.should_regenerate(&file_path, "any_hash")?);
385
386        Ok(())
387    }
388
389    #[test]
390    fn test_incremental_result_percentage() {
391        let result = IncrementalResult::new(100, 20, 80, 0);
392        assert_eq!(result.skip_percentage, 80.0);
393        assert!(result.all_passed());
394
395        let result = IncrementalResult::new(100, 100, 0, 5);
396        assert_eq!(result.skip_percentage, 0.0);
397        assert!(!result.all_passed());
398
399        let result = IncrementalResult::new(0, 0, 0, 0);
400        assert_eq!(result.skip_percentage, 0.0);
401        assert!(result.all_passed());
402    }
403
404    #[test]
405    fn test_file_state_needs_regeneration() {
406        let state = FileState::new(
407            "content123".to_string(),
408            "spec456".to_string(),
409            PathBuf::from("test.rs"),
410            12345,
411        );
412
413        // Same spec hash → no regeneration needed
414        assert!(!state.needs_regeneration("spec456"));
415
416        // Different spec hash → regeneration needed
417        assert!(state.needs_regeneration("spec789"));
418    }
419}