1use std::cell::RefCell;
4use std::collections::{BTreeMap, BTreeSet, HashSet, VecDeque};
5use std::fs;
6use std::path::{Path, PathBuf};
7
8use crate::cli_args::{self, CheckTypesCommand, WeakTypesCommand};
9use calcit_core::ProgramEntries;
10use calcit_core::calcit::{CalcitTrait, CalcitTypeAnnotation, LocatedWarning, NodeLocation};
11use calcit_core::call_stack::CallStackList;
12use calcit_core::{program, project_state, runner, snapshot};
13use md5::{Digest, Md5};
14use serde::de::DeserializeOwned;
15use serde::{Deserialize, Serialize};
16
17use crate::cli_handlers;
18use crate::type_coverage::{self, TypeCoverageRow, WeakTypeKind, WeakTypeRow};
19
20const CACHE_SCHEMA_VERSION: u32 = 3;
21const CACHE_FILE: &str = "analysis-cache-v1.cirru";
22const INPUT_CACHE_SCHEMA_VERSION: u32 = 2;
23const INPUT_CACHE_FILE: &str = "analysis-input-cache-v2.cirru";
24
25#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
26pub struct InputCacheStats {
27 pub status: String,
28 pub reason: Option<String>,
29 #[serde(skip_serializing_if = "Option::is_none")]
30 pub entry: Option<String>,
31 pub sources: usize,
32 pub main_reused: bool,
33 pub module_hits: usize,
34 pub module_misses: usize,
35 pub module_miss_reasons: BTreeMap<String, usize>,
36}
37
38impl InputCacheStats {
39 fn warm(sources: usize, module_hits: usize) -> Self {
40 Self {
41 status: "warm".to_owned(),
42 reason: None,
43 entry: None,
44 sources,
45 main_reused: true,
46 module_hits,
47 module_misses: 0,
48 module_miss_reasons: BTreeMap::new(),
49 }
50 }
51
52 fn cold(reason: impl Into<String>, sources: usize, module_misses: usize, module_miss_reasons: BTreeMap<String, usize>) -> Self {
53 Self {
54 status: "cold".to_owned(),
55 reason: Some(reason.into()),
56 entry: None,
57 sources,
58 main_reused: false,
59 module_hits: 0,
60 module_misses,
61 module_miss_reasons,
62 }
63 }
64
65 fn partial(
66 reason: impl Into<String>,
67 sources: usize,
68 main_reused: bool,
69 module_hits: usize,
70 module_misses: usize,
71 module_miss_reasons: BTreeMap<String, usize>,
72 ) -> Self {
73 Self {
74 status: "partial".to_owned(),
75 reason: Some(reason.into()),
76 entry: None,
77 sources,
78 main_reused,
79 module_hits,
80 module_misses,
81 module_miss_reasons,
82 }
83 }
84
85 pub fn bypassed(reason: impl Into<String>) -> Self {
86 Self {
87 status: "bypassed".to_owned(),
88 reason: Some(reason.into()),
89 entry: None,
90 sources: 0,
91 main_reused: false,
92 module_hits: 0,
93 module_misses: 0,
94 module_miss_reasons: BTreeMap::new(),
95 }
96 }
97
98 pub fn ensure_complete(&self) -> Result<(), String> {
99 let failures = self.module_miss_reasons.get("module-load-failed").copied().unwrap_or_default();
100 if failures == 0 {
101 Ok(())
102 } else {
103 Err(format!(
104 "Incremental analysis requires a complete Snapshot, but {failures} active-entry module(s) failed to load."
105 ))
106 }
107 }
108}
109
110#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
111pub struct CacheStats {
112 pub hits: usize,
113 pub misses: usize,
114 pub miss_reasons: BTreeMap<String, usize>,
115 #[serde(skip_serializing_if = "Option::is_none")]
116 pub input: Option<InputCacheStats>,
117 #[serde(skip_serializing_if = "Option::is_none")]
118 pub dependency_index: Option<DependencyIndexStats>,
119}
120
121#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
122pub struct DependencyIndexStats {
123 pub status: String,
124 pub hits: usize,
125 pub misses: usize,
126 pub unresolved: usize,
127 pub edges: usize,
128 pub changed: usize,
129 pub affected: usize,
130 pub miss_reasons: BTreeMap<String, usize>,
131}
132
133#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
134pub struct PreprocessingCacheStats {
135 pub status: String,
136 pub preprocessing_cached: bool,
137 pub reason: Option<String>,
138 pub input: InputCacheStats,
139 pub dependency_index: DependencyIndexStats,
140}
141
142impl PreprocessingCacheStats {
143 pub fn as_json(&self) -> serde_json::Value {
144 serde_json::json!({
145 "enabled": true,
146 "scope": "entry-dependency-closure",
147 "preprocessing_cached": self.preprocessing_cached,
148 "status": self.status,
149 "reason": self.reason,
150 "cache_file": ".calcit/analysis-cache-v1.cirru",
151 "input": self.input,
152 "dependency_index": self.dependency_index,
153 })
154 }
155
156 pub fn human_line(&self) -> String {
157 format!(
158 "- incremental-cache: scope=entry-dependency-closure preprocessing-cached={} status={} reason={} input={} dependencies={}\n",
159 self.preprocessing_cached,
160 self.status,
161 self.reason.as_deref().unwrap_or("none"),
162 self.input.status,
163 self.dependency_index.status,
164 )
165 }
166}
167
168impl CacheStats {
169 pub fn status(&self) -> &'static str {
170 match (self.hits, self.misses) {
171 (0, 0) => "empty",
172 (_, 0) => "warm",
173 (0, _) => "cold",
174 _ => "partial",
175 }
176 }
177
178 fn record_miss(&mut self, reason: &str) {
179 self.misses += 1;
180 *self.miss_reasons.entry(reason.to_owned()).or_insert(0) += 1;
181 }
182
183 pub fn as_json(&self) -> serde_json::Value {
184 serde_json::json!({
185 "enabled": true,
186 "scope": "definition-local-inventory",
187 "preprocessing_cached": false,
188 "status": self.status(),
189 "hits": self.hits,
190 "misses": self.misses,
191 "miss_reasons": self.miss_reasons,
192 "cache_file": ".calcit/analysis-cache-v1.cirru",
193 "input": self.input,
194 "dependency_index": self.dependency_index,
195 })
196 }
197
198 pub fn human_line(&self) -> String {
199 let reasons = self
200 .miss_reasons
201 .iter()
202 .map(|(reason, count)| format!("{reason}={count}"))
203 .collect::<Vec<_>>()
204 .join(",");
205 format!(
206 "- incremental-cache: scope=definition-local-inventory preprocessing-cached=false status={} hits={} misses={} reasons={} input={} dependencies={}\n",
207 self.status(),
208 self.hits,
209 self.misses,
210 if reasons.is_empty() { "none" } else { reasons.as_str() },
211 self
212 .input
213 .as_ref()
214 .map(|input| {
215 let reason = input.reason.as_deref().unwrap_or("none");
216 format!(
217 "{}(reason={reason},entry={},main-reused={},module-hits={},module-misses={})",
218 input.status,
219 input.entry.as_deref().unwrap_or("not-recorded"),
220 input.main_reused,
221 input.module_hits,
222 input.module_misses
223 )
224 })
225 .unwrap_or_else(|| "not-recorded".to_owned()),
226 self
227 .dependency_index
228 .as_ref()
229 .map(|index| format!(
230 "{}(hits={},misses={},changed={},affected={},edges={},unresolved={})",
231 index.status, index.hits, index.misses, index.changed, index.affected, index.edges, index.unresolved
232 ))
233 .unwrap_or_else(|| "not-recorded".to_owned())
234 )
235 }
236}
237
238#[derive(Debug, Clone, Serialize, Deserialize)]
239struct CachedAnalysisInput {
240 schema_version: u32,
241 calcit_version: String,
242 core_revision: String,
243 input_path: String,
244 main: CachedSnapshotUnit,
245 modules: BTreeMap<String, CachedSnapshotUnit>,
246}
247
248#[derive(Debug, Clone, Serialize, Deserialize)]
249struct CachedSnapshotUnit {
250 snapshot: snapshot::Snapshot,
251 sources: BTreeMap<String, String>,
252 module_resolutions: BTreeMap<String, String>,
253 ffi: BTreeMap<String, String>,
254}
255
256#[derive(Debug, Clone, Serialize, Deserialize)]
257struct CachedDefinition {
258 revision: String,
259 #[serde(default)]
260 check_types: Option<TypeCoverageRow>,
261 #[serde(default)]
262 weak_types_ready: bool,
263 #[serde(default)]
264 weak_types: Option<WeakTypeRow>,
265}
266
267#[derive(Debug, Clone, Serialize, Deserialize)]
268struct AnalysisCache {
269 schema_version: u32,
270 calcit_version: String,
271 context_revision: String,
272 definitions: BTreeMap<String, CachedDefinition>,
273 #[serde(default)]
274 dependency_index: BTreeMap<String, CachedDependency>,
275 #[serde(default)]
276 dynamic_methods: Option<CachedDynamicMethods>,
277 #[serde(default)]
278 strict_check: Option<CachedStrictCheck>,
279}
280
281#[derive(Debug, Clone, Serialize, Deserialize)]
282struct CachedDynamicMethods {
283 closure_revision: String,
284 #[serde(default)]
285 core_revision: String,
286 findings: Vec<CachedWarning>,
287}
288
289#[derive(Debug, Clone, Serialize, Deserialize)]
290struct CachedStrictCheck {
291 closure_revision: String,
292 #[serde(default)]
293 core_revision: String,
294 strict_types: bool,
295 warn_dynamic_methods: bool,
296 #[serde(default)]
298 proof_audit: bool,
299 #[serde(default)]
300 deny_migration_warnings: bool,
301}
302
303#[derive(Debug, Clone, Serialize, Deserialize)]
304struct CachedWarning {
305 message: String,
306 namespace: String,
307 definition: String,
308 coordinate: Vec<u16>,
309 code: Option<String>,
310 hint: Option<String>,
311}
312
313impl From<&LocatedWarning> for CachedWarning {
314 fn from(warning: &LocatedWarning) -> Self {
315 Self {
316 message: warning.message().to_owned(),
317 namespace: warning.location().ns.to_string(),
318 definition: warning.location().def.to_string(),
319 coordinate: warning.location().coord.to_vec(),
320 code: warning.code().map(str::to_owned),
321 hint: warning.hint().map(str::to_owned),
322 }
323 }
324}
325
326impl From<CachedWarning> for LocatedWarning {
327 fn from(warning: CachedWarning) -> Self {
328 LocatedWarning::new_with_detail(
329 warning.message,
330 NodeLocation::new(
331 warning.namespace.into(),
332 warning.definition.into(),
333 std::sync::Arc::new(warning.coordinate),
334 ),
335 warning.code,
336 warning.hint,
337 )
338 }
339}
340
341#[derive(Debug, Clone, Serialize, Deserialize)]
342struct CachedDependency {
343 definition_revision: String,
344 namespace_revision: String,
345 ready: bool,
346 dependencies: BTreeSet<String>,
347}
348
349#[derive(Debug, Clone)]
350struct DependencySource {
351 ns: String,
352 definition: String,
353 definition_revision: String,
354 namespace_revision: String,
355 schema: std::sync::Arc<CalcitTypeAnnotation>,
356}
357
358impl AnalysisCache {
359 fn empty(context_revision: String) -> Self {
360 Self {
361 schema_version: CACHE_SCHEMA_VERSION,
362 calcit_version: cli_args::CALCIT_VERSION.to_owned(),
363 context_revision,
364 definitions: BTreeMap::new(),
365 dependency_index: BTreeMap::new(),
366 dynamic_methods: None,
367 strict_check: None,
368 }
369 }
370}
371
372fn cache_path(snapshot_file: &str) -> PathBuf {
373 project_state::state_file_for_snapshot(snapshot_file, CACHE_FILE)
374}
375
376fn input_cache_path(snapshot_file: &str) -> PathBuf {
377 project_state::state_file_for_snapshot(snapshot_file, INPUT_CACHE_FILE)
378}
379
380fn source_revision(path: &Path) -> Result<String, String> {
381 let bytes = fs::read(path).map_err(|error| format!("Failed to read analysis input '{}': {error}", path.display()))?;
382 let mut hasher = Md5::new();
383 hasher.update(bytes);
384 Ok(format!("md5:{}", hex::encode(hasher.finalize())))
385}
386
387fn canonical_path(path: &Path) -> Result<String, String> {
388 fs::canonicalize(path)
389 .map(|path| path.to_string_lossy().into_owned())
390 .map_err(|error| format!("Failed to resolve analysis input '{}': {error}", path.display()))
391}
392
393fn validate_input_cache_header(cache: &CachedAnalysisInput, expected_input: &str) -> Result<(), String> {
394 if cache.schema_version != INPUT_CACHE_SCHEMA_VERSION {
395 return Err("cache-schema-changed".to_owned());
396 }
397 if cache.calcit_version != cli_args::CALCIT_VERSION {
398 return Err("compiler-version-changed".to_owned());
399 }
400 if cache.core_revision != calcit_core::core_snapshot_revision() {
401 return Err("core-revision-changed".to_owned());
402 }
403 if cache.input_path != expected_input {
404 return Err("input-path-changed".to_owned());
405 }
406 Ok(())
407}
408
409fn validate_cached_snapshot_unit(unit: &CachedSnapshotUnit, base_dir: &Path, module_folder: &Path) -> Result<(), String> {
410 for (path, expected_revision) in &unit.sources {
411 let revision = source_revision(Path::new(path)).map_err(|_| "source-missing".to_owned())?;
412 if &revision != expected_revision {
413 return Err("source-changed".to_owned());
414 }
415 }
416 for (request, expected_path) in &unit.module_resolutions {
417 let (_, resolved_path, _) = calcit_core::resolve_module_snapshot_path(request, base_dir, module_folder);
418 let resolved_path = canonical_path(&resolved_path).map_err(|_| "module-resolution-changed".to_owned())?;
419 if &resolved_path != expected_path {
420 return Err("module-resolution-changed".to_owned());
421 }
422 }
423 Ok(())
424}
425
426fn build_cached_snapshot_unit(
427 snapshot: snapshot::Snapshot,
428 source_paths: impl IntoIterator<Item = PathBuf>,
429 module_resolutions: impl IntoIterator<Item = (String, PathBuf)>,
430) -> Result<CachedSnapshotUnit, String> {
431 let mut sources = BTreeMap::new();
432 for source in source_paths {
433 let path = canonical_path(&source)?;
434 sources.insert(path.clone(), source_revision(Path::new(&path))?);
435 }
436 let mut resolutions = BTreeMap::new();
437 for (request, path) in module_resolutions {
438 resolutions.insert(request, canonical_path(&path)?);
439 }
440 let ffi = encode_cached_ffi(&snapshot)?;
441 Ok(CachedSnapshotUnit {
442 snapshot,
443 sources,
444 module_resolutions: resolutions,
445 ffi,
446 })
447}
448
449fn restore_cached_snapshot_unit(unit: &CachedSnapshotUnit) -> Result<snapshot::Snapshot, String> {
450 let mut snapshot = unit.snapshot.clone();
451 restore_cached_ffi(&mut snapshot, &unit.ffi)?;
452 Ok(snapshot)
453}
454
455fn uncached_snapshot_unit(snapshot: snapshot::Snapshot) -> CachedSnapshotUnit {
456 CachedSnapshotUnit {
457 snapshot,
458 sources: BTreeMap::new(),
459 module_resolutions: BTreeMap::new(),
460 ffi: BTreeMap::new(),
461 }
462}
463
464fn encode_cache<T: Serialize>(value: &T, label: &str) -> Result<String, String> {
465 let data = cirru_edn::to_edn(value).map_err(|error| format!("Failed to encode {label} as Cirru EDN: {error}"))?;
466 cirru_edn::format(&data, true).map_err(|error| format!("Failed to format {label} as Cirru EDN: {error}"))
467}
468
469fn decode_cache<T: DeserializeOwned>(content: &str) -> Result<T, String> {
470 let data = cirru_edn::parse(content).map_err(|error| error.to_string())?;
471 cirru_edn::from_edn(data)
472}
473
474fn write_input_cache(snapshot_file: &str, cache: &CachedAnalysisInput) -> Result<(), String> {
475 let project_directory = project_state::project_directory_for_snapshot(snapshot_file);
476 let directory = project_state::ensure_state_directory(project_directory)
477 .map_err(|error| format!("Failed to create analysis input cache directory: {error}"))?;
478 let path = directory.join(INPUT_CACHE_FILE);
479 let temporary = directory.join(format!(".{INPUT_CACHE_FILE}.{}.tmp", std::process::id()));
480 let content = encode_cache(cache, "analysis input cache")?;
481 fs::write(&temporary, content).map_err(|error| format!("Failed to write analysis input cache staging file: {error}"))?;
482 fs::rename(&temporary, &path).map_err(|error| format!("Failed to install analysis input cache: {error}"))?;
483 Ok(())
484}
485
486fn encode_cached_ffi(snapshot: &snapshot::Snapshot) -> Result<BTreeMap<String, String>, String> {
487 let mut ffi = BTreeMap::new();
488 for (namespace, file) in &snapshot.files {
489 for (definition, entry) in &file.defs {
490 if let Some(metadata) = &entry.ffi {
491 let rendered = cirru_edn::format(metadata, true)
492 .map_err(|error| format!("Failed to encode cached FFI metadata for {namespace}/{definition}: {error}"))?;
493 ffi.insert(format!("{namespace}/{definition}"), rendered);
494 }
495 }
496 }
497 Ok(ffi)
498}
499
500fn restore_cached_ffi(snapshot: &mut snapshot::Snapshot, cached: &BTreeMap<String, String>) -> Result<(), String> {
501 let mut restored = 0;
502 for (namespace, file) in &mut snapshot.files {
503 for (definition, entry) in &mut file.defs {
504 if entry.ffi.is_some() {
505 let id = format!("{namespace}/{definition}");
506 let rendered = cached.get(&id).ok_or_else(|| "cache-corrupt".to_owned())?;
507 entry.ffi = Some(cirru_edn::parse(rendered).map_err(|_| "cache-corrupt".to_owned())?);
508 restored += 1;
509 }
510 }
511 }
512 if restored != cached.len() {
513 return Err("cache-corrupt".to_owned());
514 }
515 Ok(())
516}
517
518pub fn load_snapshot_for_incremental_analysis(
519 snapshot_file: &str,
520 selected_entry: Option<&str>,
521) -> Result<(snapshot::Snapshot, InputCacheStats, HashSet<String>), String> {
522 let expected_input = canonical_path(Path::new(snapshot_file))?;
523 let path = input_cache_path(snapshot_file);
524 let (cached, global_reason) = match fs::read_to_string(&path) {
525 Ok(content) => match decode_cache::<CachedAnalysisInput>(&content) {
526 Ok(cache) => match validate_input_cache_header(&cache, &expected_input) {
527 Ok(()) => (Some(cache), None),
528 Err(reason) => (None, Some(reason)),
529 },
530 Err(_) => (None, Some("cache-corrupt".to_owned())),
531 },
532 Err(error) if error.kind() == std::io::ErrorKind::NotFound => (None, Some("cache-missing".to_owned())),
533 Err(_) => (None, Some("cache-unreadable".to_owned())),
534 };
535
536 let base_dir = Path::new(&expected_input).parent().unwrap_or_else(|| Path::new("."));
537 let module_folder = calcit_core::project_module_folder(base_dir);
538 let mut first_reason = global_reason.clone();
539 let mut cacheable = true;
540
541 let cached_main = cached.as_ref().map(|cache| &cache.main);
542 let (mut snapshot, main_unit, main_reused) = match cached_main
543 .ok_or_else(|| global_reason.clone().unwrap_or_else(|| "not-cached".to_owned()))
544 .and_then(|unit| {
545 validate_cached_snapshot_unit(unit, base_dir, &module_folder)?;
546 restore_cached_snapshot_unit(unit).map(|snapshot| (snapshot, unit.clone()))
547 }) {
548 Ok((snapshot, unit)) => (snapshot, unit, true),
549 Err(reason) => {
550 first_reason.get_or_insert_with(|| reason.clone());
551 let snapshot = cli_handlers::load_main_snapshot(snapshot_file)?;
552 let unit = match build_cached_snapshot_unit(snapshot.clone(), [PathBuf::from(snapshot_file)], []) {
553 Ok(unit) => unit,
554 Err(error) => {
555 cacheable = false;
556 first_reason = Some("source-unreadable".to_owned());
557 eprintln!("Warning: Failed to cache main analysis input: {error}");
558 uncached_snapshot_unit(snapshot.clone())
559 }
560 };
561 (snapshot, unit, false)
562 }
563 };
564
565 snapshot.select_entry(selected_entry)?;
566 let active_entry = snapshot.active_entry_name().to_owned();
567 let project_namespaces = snapshot.files.keys().cloned().collect::<HashSet<_>>();
568 let mut modules_to_load = snapshot.active_entry()?.modules.clone();
569 let mut seen_modules = HashSet::new();
570 modules_to_load.retain(|module_path| seen_modules.insert(module_path.to_owned()));
571
572 let mut module_units = BTreeMap::new();
573 let mut module_hits = 0;
574 let mut module_misses = 0;
575 let mut module_miss_reasons = BTreeMap::new();
576 for module_path in &modules_to_load {
577 let cached_unit = cached.as_ref().and_then(|cache| cache.modules.get(module_path));
578 let reused = cached_unit
579 .ok_or_else(|| global_reason.clone().unwrap_or_else(|| "not-cached".to_owned()))
580 .and_then(|unit| {
581 validate_cached_snapshot_unit(unit, base_dir, &module_folder)?;
582 restore_cached_snapshot_unit(unit).map(|snapshot| (snapshot, unit.clone()))
583 });
584 let (module_snapshot, unit) = match reused {
585 Ok((module_snapshot, unit)) => {
586 module_hits += 1;
587 (module_snapshot, unit)
588 }
589 Err(reason) => {
590 module_misses += 1;
591 first_reason.get_or_insert_with(|| reason.clone());
592 match cli_handlers::load_module_with_sources_silent(module_path, base_dir, &module_folder) {
593 Ok(loaded) => {
594 *module_miss_reasons.entry(reason).or_insert(0) += 1;
595 let unit = match build_cached_snapshot_unit(loaded.snapshot.clone(), loaded.source_paths, loaded.module_resolutions) {
596 Ok(unit) => unit,
597 Err(error) => {
598 cacheable = false;
599 eprintln!("Warning: Failed to cache module '{module_path}': {error}");
600 uncached_snapshot_unit(loaded.snapshot.clone())
601 }
602 };
603 (loaded.snapshot, unit)
604 }
605 Err(error) => {
606 cacheable = false;
607 first_reason = Some("module-load-failed".to_owned());
608 *module_miss_reasons.entry("module-load-failed".to_owned()).or_insert(0) += 1;
609 eprintln!("Warning: Failed to load module '{module_path}': {error}");
610 continue;
611 }
612 }
613 }
614 };
615 calcit_core::merge_project_module_files(&mut snapshot, &module_snapshot, module_path)?;
616 module_units.insert(module_path.clone(), unit);
617 }
618
619 let core_snapshot = calcit_core::load_core_snapshot()?;
620 for (namespace, file_data) in core_snapshot.files {
621 snapshot.files.entry(namespace).or_insert(file_data);
622 }
623 runner::preprocess::set_project_namespaces(&project_namespaces);
624
625 let source_count = std::iter::once(&main_unit)
626 .chain(module_units.values())
627 .flat_map(|unit| unit.sources.keys())
628 .collect::<BTreeSet<_>>()
629 .len();
630 if cacheable {
631 let cache = CachedAnalysisInput {
632 schema_version: INPUT_CACHE_SCHEMA_VERSION,
633 calcit_version: cli_args::CALCIT_VERSION.to_owned(),
634 core_revision: calcit_core::core_snapshot_revision(),
635 input_path: expected_input,
636 main: main_unit,
637 modules: module_units,
638 };
639 if let Err(error) = write_input_cache(snapshot_file, &cache) {
640 eprintln!("Warning: {error}; incremental analysis continued without persisting the input cache.");
641 }
642 }
643
644 let reason = first_reason.unwrap_or_else(|| "not-cached".to_owned());
645 let mut stats = if main_reused && module_misses == 0 {
646 InputCacheStats::warm(source_count, module_hits)
647 } else if main_reused || module_hits > 0 {
648 InputCacheStats::partial(reason, source_count, main_reused, module_hits, module_misses, module_miss_reasons)
649 } else {
650 InputCacheStats::cold(reason, source_count, module_misses, module_miss_reasons)
651 };
652 stats.entry = Some(active_entry);
653 Ok((snapshot, stats, project_namespaces))
654}
655
656fn context_revision(snapshot: &snapshot::Snapshot) -> Result<String, String> {
657 let context = serde_json::json!({
658 "package": snapshot.package,
659 "active_entry": snapshot.active_entry_name(),
660 "entry": snapshot.active_entry()?,
661 });
662 let bytes = serde_json::to_vec(&context).map_err(|error| format!("Failed to encode analysis cache context: {error}"))?;
663 let mut hasher = Md5::new();
664 hasher.update(bytes);
665 Ok(format!("md5:{}", hex::encode(hasher.finalize())))
666}
667
668fn load_cache(path: &Path, expected_context: &str) -> (AnalysisCache, Option<String>) {
669 let Ok(content) = fs::read_to_string(path) else {
670 return (AnalysisCache::empty(expected_context.to_owned()), Some("cache-missing".to_owned()));
671 };
672 let Ok(cache) = decode_cache::<AnalysisCache>(&content) else {
673 return (AnalysisCache::empty(expected_context.to_owned()), Some("cache-corrupt".to_owned()));
674 };
675 if cache.schema_version != CACHE_SCHEMA_VERSION {
676 return (
677 AnalysisCache::empty(expected_context.to_owned()),
678 Some("cache-schema-changed".to_owned()),
679 );
680 }
681 if cache.calcit_version != cli_args::CALCIT_VERSION {
682 return (
683 AnalysisCache::empty(expected_context.to_owned()),
684 Some("compiler-version-changed".to_owned()),
685 );
686 }
687 if cache.context_revision != expected_context {
688 return (
689 AnalysisCache::empty(expected_context.to_owned()),
690 Some("entry-policy-changed".to_owned()),
691 );
692 }
693 (cache, None)
694}
695
696fn write_cache(snapshot_file: &str, cache: &AnalysisCache) -> Result<(), String> {
697 let project_directory = project_state::project_directory_for_snapshot(snapshot_file);
698 let directory = project_state::ensure_state_directory(project_directory)
699 .map_err(|error| format!("Failed to create analysis cache directory: {error}"))?;
700 let path = directory.join(CACHE_FILE);
701 let temporary = directory.join(format!(".{CACHE_FILE}.{}.tmp", std::process::id()));
702 let content = encode_cache(cache, "analysis cache")?;
703 fs::write(&temporary, content).map_err(|error| format!("Failed to write analysis cache staging file: {error}"))?;
704 fs::rename(&temporary, &path).map_err(|error| format!("Failed to install analysis cache: {error}"))?;
705 Ok(())
706}
707
708fn miss_reason(entry: Option<&CachedDefinition>, revision: &str, global_reason: Option<&str>, ready: bool) -> String {
709 if let Some(reason) = global_reason {
710 return reason.to_owned();
711 }
712 match entry {
713 None => "not-cached".to_owned(),
714 Some(cached) if cached.revision != revision => "definition-changed".to_owned(),
715 Some(_) if !ready => "analysis-missing".to_owned(),
716 Some(_) => "not-cached".to_owned(),
717 }
718}
719
720fn prune_removed_definitions(cache: &mut AnalysisCache, snapshot: &snapshot::Snapshot) {
721 let current = snapshot
722 .files
723 .iter()
724 .flat_map(|(namespace, file)| file.defs.keys().map(move |definition| format!("{namespace}/{definition}")))
725 .collect::<BTreeSet<_>>();
726 cache.definitions.retain(|id, _| current.contains(id));
727}
728
729fn namespace_revision(file: &snapshot::FileInSnapShot) -> Result<String, String> {
730 let bytes = serde_json::to_vec(&file.ns).map_err(|error| format!("Failed to encode namespace revision: {error}"))?;
731 let mut hasher = Md5::new();
732 hasher.update(bytes);
733 Ok(format!("md5:{}", hex::encode(hasher.finalize())))
734}
735
736fn collect_schema_dependencies(schema: &std::sync::Arc<CalcitTypeAnnotation>) -> BTreeSet<String> {
737 let dependencies = RefCell::new(BTreeSet::new());
738 let _ = runner::preprocess::map_schema_references(
739 schema.clone(),
740 &|name, args| {
741 let normalized = name.trim_start_matches('\'');
742 if normalized.contains('/') {
743 dependencies.borrow_mut().insert(normalized.to_owned());
744 }
745 std::sync::Arc::new(CalcitTypeAnnotation::TypeRef(name.clone(), args))
746 },
747 &|trait_def: std::sync::Arc<CalcitTrait>| {
748 if let Some(definition_ref) = trait_def.definition_ref.as_deref() {
749 dependencies.borrow_mut().insert(definition_ref.to_owned());
750 }
751 trait_def
752 },
753 );
754 dependencies.into_inner()
755}
756
757fn reverse_affected_definitions(
758 previous: &BTreeMap<String, CachedDependency>,
759 current: &BTreeMap<String, CachedDependency>,
760 changed: &BTreeSet<String>,
761) -> BTreeSet<String> {
762 let mut reverse = BTreeMap::<String, BTreeSet<String>>::new();
763 for (dependent, record) in previous.iter().chain(current.iter()) {
764 for dependency in &record.dependencies {
765 reverse.entry(dependency.clone()).or_default().insert(dependent.clone());
766 }
767 }
768
769 let mut affected = changed.clone();
770 let mut pending = changed.iter().cloned().collect::<VecDeque<_>>();
771 while let Some(definition) = pending.pop_front() {
772 if let Some(dependents) = reverse.get(&definition) {
773 for dependent in dependents {
774 if affected.insert(dependent.clone()) {
775 pending.push_back(dependent.clone());
776 }
777 }
778 }
779 }
780 affected
781}
782
783fn unresolved_dependency_record(source: &DependencySource, previous: Option<&CachedDependency>) -> CachedDependency {
784 CachedDependency {
785 definition_revision: source.definition_revision.clone(),
786 namespace_revision: source.namespace_revision.clone(),
787 ready: false,
788 dependencies: previous.map(|record| record.dependencies.clone()).unwrap_or_default(),
789 }
790}
791
792fn trace_dependency_record(source: &DependencySource, previous: Option<&CachedDependency>) -> CachedDependency {
793 let warnings = RefCell::<Vec<LocatedWarning>>::new(Vec::new());
794 match runner::preprocess::trace_definition_source_usages(&source.ns, &source.definition, &warnings, &CallStackList::default()) {
795 Ok(usages) => {
796 let mut dependencies = usages
797 .into_iter()
798 .map(|usage| format!("{}/{}", usage.target_ns, usage.target_def))
799 .collect::<BTreeSet<_>>();
800 dependencies.extend(collect_schema_dependencies(&source.schema));
801 CachedDependency {
802 definition_revision: source.definition_revision.clone(),
803 namespace_revision: source.namespace_revision.clone(),
804 ready: true,
805 dependencies,
806 }
807 }
808 Err(_) => unresolved_dependency_record(source, previous),
809 }
810}
811
812fn collect_dependency_index(
813 cache: &mut AnalysisCache,
814 snapshot: &snapshot::Snapshot,
815 namespace: Option<&str>,
816 namespace_prefix: Option<&str>,
817 include_dependencies: bool,
818) -> Result<DependencyIndexStats, String> {
819 let entries = type_coverage::scoped_definition_entries(snapshot, namespace, namespace_prefix, include_dependencies)?;
820 let previous = cache.dependency_index.clone();
821 let all_ids = snapshot
822 .files
823 .iter()
824 .flat_map(|(ns, file)| file.defs.keys().map(move |definition| format!("{ns}/{definition}")))
825 .collect::<BTreeSet<_>>();
826 let mut changed = BTreeSet::new();
827 let mut pending = BTreeSet::new();
828 let mut sources = BTreeMap::new();
829 let mut stats = DependencyIndexStats::default();
830
831 for (ns, definition, entry) in entries {
832 let id = format!("{ns}/{definition}");
833 let definition_revision = snapshot::definition_revision(entry)?;
834 let namespace_revision = namespace_revision(snapshot.files.get(ns).expect("scoped namespace must exist"))?;
835 sources.insert(
836 id.clone(),
837 DependencySource {
838 ns: ns.to_owned(),
839 definition: definition.to_owned(),
840 definition_revision: definition_revision.clone(),
841 namespace_revision: namespace_revision.clone(),
842 schema: entry.schema.clone(),
843 },
844 );
845 match previous.get(&id) {
846 Some(record) if record.definition_revision == definition_revision && record.namespace_revision == namespace_revision => {
847 stats.hits += 1;
848 if !record.ready {
849 stats.unresolved += 1;
850 }
851 }
852 cached => {
853 stats.misses += 1;
854 let reason = match cached {
855 None => "not-indexed",
856 Some(record) if record.definition_revision != definition_revision => "definition-changed",
857 Some(record) if record.namespace_revision != namespace_revision => "namespace-changed",
858 Some(_) => "index-stale",
859 };
860 *stats.miss_reasons.entry(reason.to_owned()).or_insert(0) += 1;
861 changed.insert(id.clone());
862 pending.insert(id);
863 }
864 }
865 }
866
867 for removed in previous.keys().filter(|id| !all_ids.contains(*id)) {
868 changed.insert(removed.clone());
869 }
870
871 let affected = reverse_affected_definitions(&previous, &cache.dependency_index, &changed);
872 let refresh = affected
873 .iter()
874 .filter(|id| sources.contains_key(*id))
875 .cloned()
876 .collect::<BTreeSet<_>>();
877 for id in refresh.iter().filter(|id| !pending.contains(*id)) {
878 debug_assert!(previous.contains_key(id));
879 stats.hits = stats.hits.saturating_sub(1);
880 if previous.get(id).is_some_and(|record| !record.ready) {
881 stats.unresolved = stats.unresolved.saturating_sub(1);
882 }
883 stats.misses += 1;
884 *stats.miss_reasons.entry("dependency-affected".to_owned()).or_insert(0) += 1;
885 }
886
887 if !refresh.is_empty() {
888 if let Ok(program_data) = program::extract_program_data(snapshot) {
889 *program::PROGRAM_CODE_DATA.write().expect("open program data for dependency index") = program_data;
890 for id in &refresh {
891 let source = sources.get(id).expect("refresh source must exist");
892 let record = trace_dependency_record(source, previous.get(id));
893 if !record.ready {
894 stats.unresolved += 1;
895 }
896 cache.dependency_index.insert(id.clone(), record);
897 }
898 } else {
899 stats.unresolved += refresh.len();
900 *stats.miss_reasons.entry("program-index-failed".to_owned()).or_insert(0) += refresh.len();
901 for id in &refresh {
902 let source = sources.get(id).expect("refresh source must exist");
903 cache
904 .dependency_index
905 .insert(id.clone(), unresolved_dependency_record(source, previous.get(id)));
906 }
907 }
908 }
909
910 cache.dependency_index.retain(|id, _| all_ids.contains(id));
911 stats.changed = changed.len();
912 stats.affected = affected.len();
913 stats.edges = cache
914 .dependency_index
915 .values()
916 .filter(|record| record.ready)
917 .map(|record| record.dependencies.len())
918 .sum();
919 match (stats.hits, stats.misses) {
920 (0, 0) => "empty",
921 (_, 0) => "warm",
922 (0, _) => "cold",
923 _ => "partial",
924 }
925 .clone_into(&mut stats.status);
926 Ok(stats)
927}
928
929fn dependency_closure_revision(
930 cache: &AnalysisCache,
931 entries: &ProgramEntries,
932 snapshot: &snapshot::Snapshot,
933) -> Result<String, String> {
934 let roots = [
935 format!("{}/{}", entries.init_ns, entries.init_def),
936 format!("{}/{}", entries.reload_ns, entries.reload_def),
937 ];
938 let root_ids = roots.iter().cloned().collect::<BTreeSet<_>>();
939 let mut pending = roots.iter().cloned().collect::<VecDeque<_>>();
940 let mut visited = BTreeSet::new();
941 let mut closure = Vec::new();
942
943 while let Some(id) = pending.pop_front() {
944 if !visited.insert(id.clone()) {
945 continue;
946 }
947 let Some(record) = cache.dependency_index.get(&id) else {
948 if root_ids.contains(&id) {
949 return Err(format!("dependency-root-missing:{id}"));
950 }
951 closure.push((id, "external".to_owned(), String::new(), BTreeSet::new()));
954 continue;
955 };
956 let definition = id.split_once('/').and_then(|(ns, name)| snapshot.files.get(ns)?.defs.get(name));
958 if definition
959 .is_some_and(|entry| matches!(entry.schema.as_ref(), CalcitTypeAnnotation::Macro(signature) if !signature.is_cache_eligible()))
960 {
961 return Err(format!("effectful-macro:{id}"));
962 }
963 if !record.ready {
964 return Err(format!("dependency-unresolved:{id}"));
965 }
966 for dependency in &record.dependencies {
967 pending.push_back(dependency.clone());
968 }
969 closure.push((
970 id,
971 record.definition_revision.clone(),
972 record.namespace_revision.clone(),
973 record.dependencies.clone(),
974 ));
975 }
976
977 closure.sort_by(|a, b| a.0.cmp(&b.0));
978 let bytes = serde_json::to_vec(&(roots, closure)).map_err(|error| format!("Failed to encode dependency closure: {error}"))?;
979 let mut hasher = Md5::new();
980 hasher.update(bytes);
981 Ok(format!("md5:{}", hex::encode(hasher.finalize())))
982}
983
984fn preprocess_dynamic_methods(snapshot: &snapshot::Snapshot, entries: &ProgramEntries) -> Result<Vec<LocatedWarning>, String> {
985 *program::PROGRAM_CODE_DATA
986 .write()
987 .expect("open program data for dynamic method analysis") = program::extract_program_data(snapshot)?;
988 runner::preprocess::ensure_ns_def_compiled(
989 calcit_core::calcit::CORE_NS,
990 calcit_core::calcit::BUILTIN_IMPLS_ENTRY,
991 &RefCell::new(Vec::new()),
992 &CallStackList::default(),
993 )
994 .map_err(|failure| failure.to_string())?;
995 Ok(
996 crate::preprocess_dynamic_method_entries(entries)?
997 .into_iter()
998 .filter(|warning| matches!(warning.code(), Some("P_DYNAMIC_METHOD_DISPATCH" | "P_DYNAMIC_POSTFIX_METHOD")))
999 .collect(),
1000 )
1001}
1002
1003pub fn collect_dynamic_methods(
1004 snapshot: &snapshot::Snapshot,
1005 snapshot_file: &str,
1006 entries: &ProgramEntries,
1007 input: InputCacheStats,
1008) -> Result<(Vec<LocatedWarning>, PreprocessingCacheStats), String> {
1009 let context = context_revision(snapshot)?;
1010 let path = cache_path(snapshot_file);
1011 let (mut cache, global_reason) = load_cache(&path, &context);
1012 let dependency_index =
1015 runner::preprocess::with_restored_compiled_program(|| collect_dependency_index(&mut cache, snapshot, None, None, true))?;
1016 let closure_revision = dependency_closure_revision(&cache, entries, snapshot);
1017 let core_revision = calcit_core::core_snapshot_revision();
1018
1019 let (findings, status, preprocessing_cached, reason) = match closure_revision {
1020 Ok(revision) => match cache.dynamic_methods.as_ref() {
1021 Some(cached) if cached.closure_revision == revision && cached.core_revision == core_revision => (
1022 cached.findings.clone().into_iter().map(LocatedWarning::from).collect(),
1023 "warm".to_owned(),
1024 true,
1025 None,
1026 ),
1027 cached => {
1028 let findings = preprocess_dynamic_methods(snapshot, entries)?;
1029 let reason = global_reason.or_else(|| {
1030 cached
1031 .map(|cached| {
1032 if cached.core_revision != core_revision {
1033 "core-revision-changed".to_owned()
1034 } else {
1035 "dependency-closure-changed".to_owned()
1036 }
1037 })
1038 .or_else(|| Some("preprocessing-not-cached".to_owned()))
1039 });
1040 cache.dynamic_methods = Some(CachedDynamicMethods {
1041 closure_revision: revision,
1042 core_revision,
1043 findings: findings.iter().map(CachedWarning::from).collect(),
1044 });
1045 (findings, "cold".to_owned(), false, reason)
1046 }
1047 },
1048 Err(reason) => (
1049 preprocess_dynamic_methods(snapshot, entries)?,
1050 "bypassed".to_owned(),
1051 false,
1052 Some(reason),
1053 ),
1054 };
1055
1056 if let Err(error) = write_cache(snapshot_file, &cache) {
1057 eprintln!("Warning: {error}; incremental analysis continued without persisting the cache.");
1058 }
1059 Ok((
1060 findings,
1061 PreprocessingCacheStats {
1062 status,
1063 preprocessing_cached,
1064 reason,
1065 input,
1066 dependency_index,
1067 },
1068 ))
1069}
1070
1071pub fn run_incremental_strict_check(
1072 snapshot: &snapshot::Snapshot,
1073 snapshot_file: &str,
1074 entries: &ProgramEntries,
1075 input: InputCacheStats,
1076 check: impl FnOnce() -> Result<(), String>,
1077) -> Result<PreprocessingCacheStats, String> {
1078 let context = context_revision(snapshot)?;
1079 let path = cache_path(snapshot_file);
1080 let (mut cache, global_reason) = load_cache(&path, &context);
1081 let dependency_index = collect_dependency_index(&mut cache, snapshot, None, None, true)?;
1082 let closure_revision = dependency_closure_revision(&cache, entries, snapshot);
1083 let core_revision = calcit_core::core_snapshot_revision();
1084 let strict_types = runner::preprocess::is_strict_types_enabled();
1085 let warn_dynamic_methods = runner::preprocess::is_warn_dyn_method_enabled();
1086 let proof_audit = runner::preprocess::default_proof_enabled();
1087 let deny_migration_warnings = runner::preprocess::is_deny_migration_warnings_enabled();
1088
1089 let (status, preprocessing_cached, reason) = match closure_revision {
1090 Ok(revision) => match cache.strict_check.as_ref() {
1091 Some(cached)
1092 if cached.closure_revision == revision
1093 && cached.core_revision == core_revision
1094 && cached.strict_types == strict_types
1095 && cached.warn_dynamic_methods == warn_dynamic_methods
1096 && cached.proof_audit == proof_audit
1097 && cached.deny_migration_warnings == deny_migration_warnings =>
1098 {
1099 ("warm".to_owned(), true, None)
1100 }
1101 cached => {
1102 check()?;
1103 let reason = global_reason.or_else(|| {
1104 cached
1105 .map(|cached| {
1106 if cached.core_revision != core_revision {
1107 "core-revision-changed".to_owned()
1108 } else if cached.closure_revision != revision {
1109 "dependency-closure-changed".to_owned()
1110 } else if cached.strict_types != strict_types
1111 || cached.warn_dynamic_methods != warn_dynamic_methods
1112 || cached.proof_audit != proof_audit
1113 || cached.deny_migration_warnings != deny_migration_warnings
1114 {
1115 "preprocessing-policy-changed".to_owned()
1116 } else {
1117 "preprocessing-not-cached".to_owned()
1118 }
1119 })
1120 .or_else(|| Some("preprocessing-not-cached".to_owned()))
1121 });
1122 cache.strict_check = Some(CachedStrictCheck {
1123 closure_revision: revision,
1124 core_revision,
1125 strict_types,
1126 warn_dynamic_methods,
1127 proof_audit,
1128 deny_migration_warnings,
1129 });
1130 ("cold".to_owned(), false, reason)
1131 }
1132 },
1133 Err(reason) => {
1134 check()?;
1135 ("bypassed".to_owned(), false, Some(reason))
1136 }
1137 };
1138
1139 if let Err(error) = write_cache(snapshot_file, &cache) {
1140 eprintln!("Warning: {error}; incremental analysis continued without persisting the cache.");
1141 }
1142 Ok(PreprocessingCacheStats {
1143 status,
1144 preprocessing_cached,
1145 reason,
1146 input,
1147 dependency_index,
1148 })
1149}
1150
1151pub fn collect_check_types(
1152 options: &CheckTypesCommand,
1153 snapshot: &snapshot::Snapshot,
1154 snapshot_file: &str,
1155) -> Result<(Vec<TypeCoverageRow>, CacheStats), String> {
1156 let context = context_revision(snapshot)?;
1157 let path = cache_path(snapshot_file);
1158 let (mut cache, global_reason) = load_cache(&path, &context);
1159 let entries = type_coverage::scoped_definition_entries(snapshot, options.ns.as_deref(), options.ns_prefix.as_deref(), options.deps)?;
1160 let mut rows = Vec::with_capacity(entries.len());
1161 let mut stats = CacheStats::default();
1162
1163 for (namespace, definition, entry) in entries {
1164 let id = format!("{namespace}/{definition}");
1165 let revision = snapshot::definition_revision(entry)?;
1166 let cached = cache.definitions.get(&id);
1167 if let Some(row) = cached
1168 .filter(|cached| cached.revision == revision)
1169 .and_then(|cached| cached.check_types.clone())
1170 {
1171 stats.hits += 1;
1172 rows.push(row);
1173 continue;
1174 }
1175 stats.record_miss(&miss_reason(
1176 cached,
1177 &revision,
1178 global_reason.as_deref(),
1179 cached.and_then(|item| item.check_types.as_ref()).is_some(),
1180 ));
1181 let row = type_coverage::analyze_code_entry(namespace, definition, entry);
1182 let record = cache.definitions.entry(id).or_insert_with(|| CachedDefinition {
1183 revision: revision.clone(),
1184 check_types: None,
1185 weak_types_ready: false,
1186 weak_types: None,
1187 });
1188 if record.revision != revision {
1189 *record = CachedDefinition {
1190 revision,
1191 check_types: None,
1192 weak_types_ready: false,
1193 weak_types: None,
1194 };
1195 }
1196 record.check_types = Some(row.clone());
1197 rows.push(row);
1198 }
1199
1200 type_coverage::filter_type_coverage_rows(options, &mut rows)?;
1201 stats.dependency_index = Some(collect_dependency_index(
1202 &mut cache,
1203 snapshot,
1204 options.ns.as_deref(),
1205 options.ns_prefix.as_deref(),
1206 options.deps,
1207 )?);
1208 prune_removed_definitions(&mut cache, snapshot);
1209 if let Err(error) = write_cache(snapshot_file, &cache) {
1210 eprintln!("Warning: {error}; incremental analysis continued without persisting the cache.");
1211 }
1212 Ok((rows, stats))
1213}
1214
1215pub fn collect_weak_types(
1216 options: &WeakTypesCommand,
1217 snapshot: &snapshot::Snapshot,
1218 snapshot_file: &str,
1219) -> Result<(Vec<WeakTypeRow>, CacheStats), String> {
1220 let context = context_revision(snapshot)?;
1221 let path = cache_path(snapshot_file);
1222 let (mut cache, global_reason) = load_cache(&path, &context);
1223 let entries = type_coverage::scoped_definition_entries(snapshot, options.ns.as_deref(), options.ns_prefix.as_deref(), options.deps)?;
1224 let mut rows = Vec::new();
1225 let mut stats = CacheStats::default();
1226
1227 for (namespace, definition, entry) in entries {
1228 let id = format!("{namespace}/{definition}");
1229 let revision = snapshot::definition_revision(entry)?;
1230 let cached = cache.definitions.get(&id);
1231 if let Some(cached) = cached.filter(|cached| cached.revision == revision && cached.weak_types_ready) {
1232 stats.hits += 1;
1233 if let Some(row) = cached.weak_types.clone() {
1234 rows.push(row);
1235 }
1236 continue;
1237 }
1238 stats.record_miss(&miss_reason(
1239 cached,
1240 &revision,
1241 global_reason.as_deref(),
1242 cached.is_some_and(|item| item.weak_types_ready),
1243 ));
1244 let row = type_coverage::analyze_weak_types_entry(namespace, definition, entry, &WeakTypeKind::collected());
1245 let record = cache.definitions.entry(id).or_insert_with(|| CachedDefinition {
1246 revision: revision.clone(),
1247 check_types: None,
1248 weak_types_ready: false,
1249 weak_types: None,
1250 });
1251 if record.revision != revision {
1252 *record = CachedDefinition {
1253 revision,
1254 check_types: None,
1255 weak_types_ready: false,
1256 weak_types: None,
1257 };
1258 }
1259 record.weak_types_ready = true;
1260 record.weak_types.clone_from(&row);
1261 if let Some(row) = row {
1262 rows.push(row);
1263 }
1264 }
1265
1266 type_coverage::filter_weak_type_rows(options, &mut rows)?;
1267 stats.dependency_index = Some(collect_dependency_index(
1268 &mut cache,
1269 snapshot,
1270 options.ns.as_deref(),
1271 options.ns_prefix.as_deref(),
1272 options.deps,
1273 )?);
1274 prune_removed_definitions(&mut cache, snapshot);
1275 if let Err(error) = write_cache(snapshot_file, &cache) {
1276 eprintln!("Warning: {error}; incremental analysis continued without persisting the cache.");
1277 }
1278 Ok((rows, stats))
1279}
1280
1281#[cfg(test)]
1282mod tests {
1283 use super::{CachedDependency, CachedWarning, DependencySource, reverse_affected_definitions, unresolved_dependency_record};
1284 use calcit_core::calcit::{DYNAMIC_TYPE, LocatedWarning, NodeLocation};
1285 use std::collections::{BTreeMap, BTreeSet};
1286 use std::sync::Arc;
1287
1288 fn dependency(dependencies: &[&str]) -> CachedDependency {
1289 CachedDependency {
1290 definition_revision: "revision".to_owned(),
1291 namespace_revision: "namespace".to_owned(),
1292 ready: true,
1293 dependencies: dependencies.iter().map(|item| (*item).to_owned()).collect(),
1294 }
1295 }
1296
1297 #[test]
1298 fn cached_dynamic_warning_preserves_diagnostic_details() {
1299 let warning = LocatedWarning::new_with_detail(
1300 "dynamic receiver".to_owned(),
1301 NodeLocation::new(Arc::from("app.main"), Arc::from("main!"), Arc::new(vec![2, 1])),
1302 Some("P_DYNAMIC_METHOD_DISPATCH".to_owned()),
1303 Some("add a receiver schema".to_owned()),
1304 );
1305 let restored = LocatedWarning::from(CachedWarning::from(&warning));
1306 assert_eq!(restored, warning);
1307 }
1308
1309 #[test]
1310 fn reverse_dependency_index_collects_transitive_callers_and_cycles() {
1311 let graph = BTreeMap::from([
1312 ("app/main".to_owned(), dependency(&["app/render"])),
1313 ("app/render".to_owned(), dependency(&["app/model"])),
1314 ("app/model".to_owned(), dependency(&["app/helper"])),
1315 ("app/helper".to_owned(), dependency(&["app/model"])),
1316 ("app/unrelated".to_owned(), dependency(&[])),
1317 ]);
1318 let changed = BTreeSet::from(["app/model".to_owned()]);
1319
1320 assert_eq!(
1321 reverse_affected_definitions(&BTreeMap::new(), &graph, &changed),
1322 BTreeSet::from([
1323 "app/helper".to_owned(),
1324 "app/main".to_owned(),
1325 "app/model".to_owned(),
1326 "app/render".to_owned(),
1327 ])
1328 );
1329 }
1330
1331 #[test]
1332 fn reverse_dependency_index_retains_removed_definition_edges() {
1333 let previous = BTreeMap::from([
1334 ("app/main".to_owned(), dependency(&["app/removed"])),
1335 ("app/removed".to_owned(), dependency(&[])),
1336 ]);
1337 let current = BTreeMap::from([("app/main".to_owned(), dependency(&["app/replacement"]))]);
1338 let changed = BTreeSet::from(["app/removed".to_owned()]);
1339
1340 assert_eq!(
1341 reverse_affected_definitions(&previous, ¤t, &changed),
1342 BTreeSet::from(["app/main".to_owned(), "app/removed".to_owned()])
1343 );
1344 }
1345
1346 #[test]
1347 fn unresolved_dependency_records_advance_revisions_but_keep_prior_edges() {
1348 let previous = dependency(&["app/old-target"]);
1349 let source = DependencySource {
1350 ns: "app".to_owned(),
1351 definition: "caller".to_owned(),
1352 definition_revision: "next-definition".to_owned(),
1353 namespace_revision: "next-namespace".to_owned(),
1354 schema: DYNAMIC_TYPE.clone(),
1355 };
1356
1357 let record = unresolved_dependency_record(&source, Some(&previous));
1358 assert!(!record.ready);
1359 assert_eq!(record.definition_revision, "next-definition");
1360 assert_eq!(record.namespace_revision, "next-namespace");
1361 assert_eq!(record.dependencies, BTreeSet::from(["app/old-target".to_owned()]));
1362 }
1363}