aptu-core 0.10.12

Core library for Aptu - OSS issue triage with AI assistance
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
// SPDX-License-Identifier: Apache-2.0

//! On-disk cache for structural graphs, keyed by repository and commit SHA.
//!
//! Cache format: 8 raw bytes of header followed by a postcard-encoded
//! [`super::GraphDb`] payload. The header is two little-endian `u32`s:
//! `FORMAT_VERSION` (bytes 0..4) then `schema_hash` (bytes 4..8), a
//! compile-time FNV-1a hash over the `Node`/`Edge` variant names used to
//! invalidate stale caches when the schema changes. `Modifies` edges are
//! ephemeral (derived from the current diff) and are always removed before
//! serialization; they never appear in a cached graph.
//!
//! Only the actual file I/O (`load_or_build`, `persist_graph`) is gated to
//! non-WASM targets. Path construction and byte encode/decode are pure
//! functions usable on any target.

use std::io::Write;
use std::path::PathBuf;

use super::{Edge, GraphDb};
use crate::config::GraphConfig;

/// Cache format version. Bump when the encoding changes in an incompatible way.
const FORMAT_VERSION: u32 = 3;

/// Compile-time FNV-1a hash over the `Node`/`Edge` variant names.
///
/// Any change to the set (or order) of `Node`/`Edge` variant names must be
/// reflected in [`SCHEMA_STRING`] so that stale cached graphs are invalidated
/// by [`decode_graph`] rather than postcard mis-decoding.
const SCHEMA_STRING: &str = "File|Module|Function|Struct|Enum|Trait|Impl|Contains|Calls|Imports|Implements|HasMethod|Modifies|Tests";

/// Computes the compile-time FNV-1a hash of [`SCHEMA_STRING`].
#[must_use]
pub const fn schema_hash() -> u32 {
    let bytes = SCHEMA_STRING.as_bytes();
    let mut hash: u32 = 0x811c_9dc5;
    let mut i = 0;
    while i < bytes.len() {
        hash ^= bytes[i] as u32;
        hash = hash.wrapping_mul(0x0100_0193);
        i += 1;
    }
    hash
}

/// Returns the on-disk cache path for a given repository and commit SHA.
///
/// Path shape: `~/.local/share/aptu/graph/<owner>/<repo>/<sha>.bin`.
#[must_use]
pub fn cache_path(owner: &str, repo: &str, sha: &str) -> PathBuf {
    crate::config::data_dir()
        .join("graph")
        .join(owner)
        .join(repo)
        .join(format!("{sha}.bin"))
}

/// Encodes `graph` into the on-disk cache byte format.
///
/// Removes `Modifies` edges by rebuilding a filtered graph (single O(N+E) pass
/// over nodes and edges), then prepends the 8-byte header (`FORMAT_VERSION`
/// followed by `schema_hash`) to the postcard-encoded payload. Returns `None`
/// if postcard serialization fails.
#[must_use]
pub fn encode_graph(graph: &GraphDb) -> Option<Vec<u8>> {
    let mut filtered = GraphDb::new();
    for idx in graph.node_indices() {
        filtered.add_node(graph[idx].clone());
    }
    for idx in graph.edge_indices() {
        let (a, b) = graph.edge_endpoints(idx)?;
        if !matches!(graph[idx], Edge::Modifies) {
            filtered.add_edge(a, b, graph[idx]);
        }
    }

    let payload = postcard::to_allocvec(&filtered).ok()?;

    let mut bytes = Vec::with_capacity(8 + payload.len());
    bytes.extend_from_slice(&FORMAT_VERSION.to_le_bytes());
    bytes.extend_from_slice(&schema_hash().to_le_bytes());
    bytes.extend_from_slice(&payload);
    Some(bytes)
}

/// Decodes a graph from on-disk cache bytes.
///
/// Returns `None` (cache miss) if the bytes are too short, the format
/// version does not match [`FORMAT_VERSION`], the `schema_hash` does not
/// match [`schema_hash`], or postcard decoding fails.
#[must_use]
pub fn decode_graph(bytes: &[u8]) -> Option<GraphDb> {
    if bytes.len() < 8 {
        return None;
    }
    let version = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
    if version != FORMAT_VERSION {
        return None;
    }
    let hash = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
    if hash != schema_hash() {
        return None;
    }
    let graph: GraphDb = postcard::from_bytes(&bytes[8..]).ok()?;
    Some(graph)
}

/// Loads a cached graph from disk, or persists the provided graph to cache.
///
/// Returns `(graph, cache_hit)`. On cache hit, the provided `graph` is dropped
/// and the cached version is returned. On cache miss, the provided `graph` is
/// persisted to disk and returned.
///
/// On WASM targets, this always returns the provided graph with `cache_hit = false`
/// (no disk I/O).
#[cfg(not(target_arch = "wasm32"))]
#[must_use]
pub fn load_or_build(
    owner: &str,
    repo: &str,
    sha: &str,
    graph: GraphDb,
    cfg: &GraphConfig,
) -> (GraphDb, bool) {
    // Try cache first.
    let path = cache_path(owner, repo, sha);
    if let Ok(Some(cached)) = try_load_cached(&path, cfg) {
        return (cached, true);
    }

    // Persist to cache.
    persist_graph(&path, &graph);

    (graph, false)
}

/// WASM fallback: always return provided graph, no disk I/O.
#[cfg(target_arch = "wasm32")]
#[must_use]
pub fn load_or_build(
    _owner: &str,
    _repo: &str,
    _sha: &str,
    graph: GraphDb,
    _cfg: &GraphConfig,
) -> (GraphDb, bool) {
    (graph, false)
}

/// Tries to load a cached graph from `path`.
///
/// Returns `None` if the file doesn't exist, is too old (TTL expired),
/// or fails to decode.
#[cfg(not(target_arch = "wasm32"))]
fn try_load_cached(path: &PathBuf, cfg: &GraphConfig) -> std::io::Result<Option<GraphDb>> {
    let metadata = match std::fs::metadata(path) {
        Ok(m) => m,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(e) => return Err(e),
    };

    // Check TTL.
    let modified = metadata
        .modified()
        .unwrap_or_else(|_| std::time::SystemTime::now());
    let age = std::time::SystemTime::now()
        .duration_since(modified)
        .unwrap_or_default();
    let ttl = std::time::Duration::from_secs(cfg.cache_ttl_hours * 3600);
    if age > ttl {
        // Expired; caller will rebuild.
        return Ok(None);
    }

    let bytes = std::fs::read(path)?;
    Ok(decode_graph(&bytes))
}

/// Persists a graph to the cache path.
///
/// Creates parent directories if needed. Failures are logged at WARN level
/// and never propagated (caching is best-effort).
#[cfg(not(target_arch = "wasm32"))]
fn persist_graph(path: &PathBuf, graph: &GraphDb) {
    if let Some(parent) = path.parent()
        && let Err(e) = std::fs::create_dir_all(parent)
    {
        tracing::warn!(
            path = %parent.display(),
            error = %e,
            "graph cache: failed to create cache directory"
        );
        return;
    }

    let Some(bytes) = encode_graph(graph) else {
        tracing::warn!(path = %path.display(), "graph cache: encode failed, skipping write");
        return;
    };

    // Atomic write: write to a uniquely-named sibling temp file then rename to
    // prevent partial file corruption if the process crashes during the write
    // and avoid races between concurrent writers.
    let parent = path.parent().unwrap_or_else(|| std::path::Path::new("."));
    let mut tmp = match tempfile::Builder::new().tempfile_in(parent) {
        Ok(t) => t,
        Err(e) => {
            tracing::warn!(
                path = %parent.display(),
                error = %e,
                "graph cache: failed to create temp file"
            );
            return;
        }
    };
    if let Err(e) = tmp.write_all(&bytes) {
        tracing::warn!(
            path = %tmp.path().display(),
            error = %e,
            "graph cache: failed to write temp file"
        );
        let _ = std::fs::remove_file(tmp.path());
        return;
    }
    if let Err(e) = tmp.flush() {
        tracing::warn!(
            path = %tmp.path().display(),
            error = %e,
            "graph cache: failed to flush temp file"
        );
        let _ = std::fs::remove_file(tmp.path());
        return;
    }
    if let Err(e) = std::fs::rename(tmp.path(), path) {
        tracing::warn!(
            src = %tmp.path().display(),
            dst = %path.display(),
            error = %e,
            "graph cache: failed to rename temp file to cache path"
        );
    }
    // tmp drops here; the file has been renamed so the NamedTempFile destructor
    // will attempt to delete a path that no longer exists, which is harmless.
}

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

    #[test]
    fn test_round_trip_serialize_deserialize() {
        let mut graph = GraphDb::new();
        let n1 = graph.add_node(super::super::Node::Function {
            name: "foo".to_string(),
            path: "src/lib.rs".to_string(),
            visibility: "pub".to_string(),
        });
        let n2 = graph.add_node(super::super::Node::Function {
            name: "bar".to_string(),
            path: "src/lib.rs".to_string(),
            visibility: "pub".to_string(),
        });
        graph.add_edge(n1, n2, Edge::Calls);

        let bytes = encode_graph(&graph).expect("encode must succeed");
        let decoded = decode_graph(&bytes).expect("should decode successfully");

        assert_eq!(
            graph.node_count(),
            decoded.node_count(),
            "node count should match"
        );
        assert_eq!(
            graph.edge_count(),
            decoded.edge_count(),
            "edge count should match"
        );

        // Verify node names survived round-trip.
        let names: Vec<String> = decoded
            .node_indices()
            .map(|idx| decoded[idx].name().to_string())
            .collect();
        assert!(names.contains(&"foo".to_string()));
        assert!(names.contains(&"bar".to_string()));
    }

    #[test]
    fn test_decode_graph_version_mismatch() {
        let mut graph = GraphDb::new();
        graph.add_node(super::super::Node::Function {
            name: "foo".to_string(),
            path: "src/lib.rs".to_string(),
            visibility: "pub".to_string(),
        });

        // Encode, then corrupt the version byte.
        let mut bytes = encode_graph(&graph).expect("encode must succeed");
        bytes[0] = 0xFF; // Wrong version.

        let result = decode_graph(&bytes);
        assert!(result.is_none(), "version mismatch should return None");
    }

    #[test]
    fn test_decode_graph_empty_bytes() {
        let result = decode_graph(&[]);
        assert!(result.is_none(), "empty bytes should return None");
    }

    #[test]
    fn test_encode_decode_excludes_modifies_edges() {
        let mut graph = GraphDb::new();
        let n1 = graph.add_node(super::super::Node::Function {
            name: "foo".to_string(),
            path: "src/lib.rs".to_string(),
            visibility: "pub".to_string(),
        });
        let n2 = graph.add_node(super::super::Node::Function {
            name: "bar".to_string(),
            path: "src/lib.rs".to_string(),
            visibility: "pub".to_string(),
        });
        graph.add_edge(n1, n2, Edge::Calls);
        graph.add_edge(n1, n2, Edge::Modifies);

        let bytes = encode_graph(&graph).expect("encode must succeed");
        let decoded = decode_graph(&bytes).expect("should decode successfully");

        assert_eq!(decoded.edge_count(), 1, "only Calls edge should remain");
        let has_modifies = decoded
            .edge_indices()
            .any(|idx| matches!(decoded.edge_weight(idx), Some(Edge::Modifies)));
        assert!(!has_modifies, "Modifies edges should be excluded");
    }

    #[test]
    fn test_schema_hash_changes_on_variant_change() {
        // The hash must be non-zero (FNV-1a of a non-empty string is never 0).
        assert_ne!(schema_hash(), 0, "schema hash must be non-zero");

        // Verify that any change to SCHEMA_STRING produces a different hash by
        // computing FNV-1a on a mutated string and asserting divergence.
        const MUTATED: &str = "File|Module|Function|Struct|Enum|Trait|Impl|Contains|Calls|Imports|Implements|HasMethod|Modifies|Tests|NewVariant";
        let mut hash: u32 = 0x811c_9dc5;
        for &b in MUTATED.as_bytes() {
            hash ^= b as u32;
            hash = hash.wrapping_mul(0x0100_0193);
        }
        assert_ne!(
            schema_hash(),
            hash,
            "schema_hash must differ when SCHEMA_STRING gains a new variant"
        );
    }

    #[test]
    fn test_persist_graph_concurrent_writes_no_corruption() {
        let path =
            std::env::temp_dir().join(format!("aptu_cache_concurrent_{}.bin", std::process::id()));
        let _ = std::fs::remove_file(&path);

        let p1 = path.clone();
        let handle1 = std::thread::spawn(move || {
            let mut g = GraphDb::new();
            let n = g.add_node(super::super::Node::Function {
                name: "one".to_string(),
                path: "src/a.rs".to_string(),
                visibility: "pub".to_string(),
            });
            g.add_edge(n, n, Edge::Calls);
            persist_graph(&p1, &g);
        });
        let p2 = path.clone();
        let handle2 = std::thread::spawn(move || {
            let mut g = GraphDb::new();
            let n = g.add_node(super::super::Node::Function {
                name: "two".to_string(),
                path: "src/b.rs".to_string(),
                visibility: "pub".to_string(),
            });
            g.add_edge(n, n, Edge::Calls);
            persist_graph(&p2, &g);
        });

        handle1.join().expect("thread 1 must not panic");
        handle2.join().expect("thread 2 must not panic");

        // The file must be a valid, fully-decodable graph (no partial write).
        let bytes = std::fs::read(&path).expect("cache file must exist");
        let decoded = decode_graph(&bytes).expect("cache file must decode without corruption");
        assert_eq!(decoded.node_count(), 1, "decoded graph must have one node");
        assert_eq!(decoded.edge_count(), 1, "decoded graph must have one edge");

        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn test_cache_path_format() {
        let path = cache_path("owner", "repo", "abc123");
        let path_str = path.to_string_lossy();
        assert!(path_str.contains("owner"), "path should contain owner");
        assert!(path_str.contains("repo"), "path should contain repo");
        assert!(path_str.contains("abc123"), "path should contain sha");
        assert!(path_str.ends_with(".bin"), "path should end with .bin");
    }
}