sqry-core 12.0.3

Core library for sqry - semantic code search engine
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Sparse node metadata store for macro boundary analysis and classpath provenance.
//!
//! This module provides [`NodeMetadataStore`], a sparse metadata store keyed by
//! full [`NodeId`] (index + generation) to prevent stale metadata when the
//! generational arena reuses a slot index with a new generation.
//!
//! Only nodes with metadata get entries, keeping memory overhead
//! proportional to the number of annotated symbols rather than total node count.

use std::collections::HashMap;

use serde::{Deserialize, Serialize};

use super::super::node::id::NodeId;

/// Optional metadata for nodes that participate in macro boundary analysis.
///
/// Stored separately from [`NodeEntry`] to avoid bloating the arena for the
/// majority of nodes that don't need macro metadata.
///
/// Each field is `Option` (or `Vec` with empty default) so only relevant
/// metadata consumes space in the serialized representation.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct MacroNodeMetadata {
    /// Whether this symbol was generated by macro expansion.
    pub macro_generated: Option<bool>,

    /// Qualified name of the macro that generated this symbol.
    pub macro_source: Option<String>,

    /// The cfg predicate string (e.g., `"test"`, `"feature = \"serde\""`)
    pub cfg_condition: Option<String>,

    /// Whether this cfg is active (`None` = unknown, requires external config).
    pub cfg_active: Option<bool>,

    /// Proc-macro kind for proc-macro function nodes.
    pub proc_macro_kind: Option<ProcMacroFunctionKind>,

    /// Whether expansion data came from cache vs live `cargo expand`.
    pub expansion_cached: Option<bool>,

    /// Unresolved attribute paths that could not be positively identified
    /// as proc-macro attributes. Stored for potential future resolution.
    pub unresolved_attributes: Vec<String>,
}

/// Classification of proc-macro function types.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProcMacroFunctionKind {
    /// `#[proc_macro_derive(Name)]` — generates impls for structs/enums.
    Derive,
    /// `#[proc_macro_attribute]` — transforms annotated items.
    Attribute,
    /// `#[proc_macro]` — function-like `my_macro!(...)` invocation.
    FunctionLike,
}

/// Metadata for nodes originating from JVM classpath bytecode.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ClasspathNodeMetadata {
    /// Maven coordinates (e.g., `"com.google.guava:guava:33.0.0"`).
    pub coordinates: Option<String>,
    /// JAR file path this node was extracted from.
    pub jar_path: String,
    /// Fully qualified name in JVM format (e.g., `"java.util.HashMap"`).
    pub fqn: String,
    /// Whether this is a direct or transitive dependency.
    pub is_direct_dependency: bool,
}

/// Metadata that can be attached to graph nodes.
///
/// This enum is not directly `Serialize`/`Deserialize` because `postcard`
/// does not support Rust enum variants wrapping structs. Instead,
/// `NodeMetadataStore` handles serialization/deserialization through flat
/// entry structs with explicit discriminant bytes.
///
/// For JSON use (e.g., MCP export), use the `serde_json`-compatible
/// `to_json`/`from_json` convenience methods.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NodeMetadata {
    /// Rust macro-related metadata.
    Macro(MacroNodeMetadata),
    /// JVM classpath provenance metadata.
    Classpath(ClasspathNodeMetadata),
    /// Synthetic placeholder node marker (C_SUPPRESS).
    ///
    /// Identifies internal-use-only nodes that language plugins emit as
    /// shadows / scaffolding for binding-plane analysis (e.g. the Go
    /// plugin's `<field:operand.field>` field-access placeholders and the
    /// `name@<offset>` per-binding-site Variable nodes from the local-scope
    /// resolver). These nodes must be suppressed from user-facing search
    /// surfaces (`sqry search --exact`, MCP `semantic_search`,
    /// `relation_query`, etc.) but remain reachable to internal callers
    /// (binding plane, scope/alias analysis) via the explicit
    /// `include_synthetic` opt-in path.
    ///
    /// Carries no payload — presence in the metadata store at a given
    /// `NodeId` IS the flag.
    ///
    /// Wire format: serializes with `kind == NODE_METADATA_SYNTHETIC`
    /// (discriminant 2) and BOTH `macro_data` and `classpath_data`
    /// payload fields encoded as `None`. The on-wire shape stays at the
    /// existing 5-field per-entry layout, so V10 snapshots written before
    /// this variant existed (which only carry kinds 0 and 1) decode
    /// without change, and V10 snapshots written after this variant
    /// exists are decoded by the new reader by dispatching on `kind`.
    /// The arena layout (`NodeEntry`) is unchanged.
    Synthetic,
}

/// Discriminant values for `NodeMetadata` wire format.
const NODE_METADATA_MACRO: u8 = 0;
const NODE_METADATA_CLASSPATH: u8 = 1;
const NODE_METADATA_SYNTHETIC: u8 = 2;

/// Sparse metadata store keyed by full `NodeId` (index + generation).
///
/// Uses `(u32, u64)` tuple key to prevent stale metadata when the
/// generational arena reuses a slot index with a new generation.
/// A lookup with `NodeId { index: 5, generation: 3 }` will NOT match metadata
/// stored for `NodeId { index: 5, generation: 2 }`.
///
/// # Memory characteristics
///
/// For a typical large codebase (100K nodes), only ~5-10% of nodes have
/// metadata. A store with 10K entries at ~200 bytes each = ~2MB, which is
/// acceptable given snapshots are already 10-50MB.
///
/// # Serialization
///
/// The in-memory representation uses `HashMap` for O(1) lookups. For postcard
/// serialization (which doesn't support tuple keys natively), we serialize as
/// a `Vec` of `NodeMetadataEntry` structs with explicit `index` and `generation`
/// fields, then reconstruct the `HashMap` on deserialization.
///
/// For backwards compatibility, legacy entries serialized as bare
/// `MacroNodeMetadata` (without a wrapping `NodeMetadata` enum tag) are
/// transparently deserialized as `NodeMetadata::Macro`.
#[derive(Debug, Clone, Default)]
pub struct NodeMetadataStore {
    /// Metadata entries keyed by `(NodeId::index(), NodeId::generation())`.
    entries: HashMap<(u32, u64), NodeMetadata>,
}

/// Serialization wrapper for a V7 metadata entry with explicit discriminant.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct NodeMetadataEntryV7 {
    index: u32,
    generation: u64,
    /// Discriminant: 0 = Macro, 1 = Classpath
    kind: u8,
    /// Macro metadata (present when kind == 0)
    macro_data: Option<MacroNodeMetadata>,
    /// Classpath metadata (present when kind == 1)
    classpath_data: Option<ClasspathNodeMetadata>,
}

impl Serialize for NodeMetadataStore {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let entries: Vec<NodeMetadataEntryV7> = self
            .entries
            .iter()
            .map(|(&(index, generation), metadata)| match metadata {
                NodeMetadata::Macro(m) => NodeMetadataEntryV7 {
                    index,
                    generation,
                    kind: NODE_METADATA_MACRO,
                    macro_data: Some(m.clone()),
                    classpath_data: None,
                },
                NodeMetadata::Classpath(c) => NodeMetadataEntryV7 {
                    index,
                    generation,
                    kind: NODE_METADATA_CLASSPATH,
                    macro_data: None,
                    classpath_data: Some(c.clone()),
                },
                // C_SUPPRESS: Synthetic flag has no payload. Wire shape
                // stays at the existing 5-field layout — both Option
                // payload fields are `None`, only `kind` distinguishes
                // the variant. Old V10 snapshots only carry kinds 0 and
                // 1, so they continue to decode unchanged.
                NodeMetadata::Synthetic => NodeMetadataEntryV7 {
                    index,
                    generation,
                    kind: NODE_METADATA_SYNTHETIC,
                    macro_data: None,
                    classpath_data: None,
                },
            })
            .collect();
        entries.serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for NodeMetadataStore {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        // V7 format: each entry has an explicit `kind` discriminant.
        // Legacy V6 entries had no `kind` field, so `kind` will default to 0
        // (which maps to Macro) via postcard's sequential field decoding.
        // However, since we bumped the snapshot version to V7, V6 snapshots
        // will be rejected at the magic byte check before reaching this code.
        let entries: Vec<NodeMetadataEntryV7> = Vec::deserialize(deserializer)?;
        let mut map = HashMap::with_capacity(entries.len());
        for e in entries {
            let metadata = match e.kind {
                NODE_METADATA_CLASSPATH => {
                    let data = e.classpath_data.ok_or_else(|| {
                        serde::de::Error::custom(
                            "missing classpath_data for Classpath metadata entry",
                        )
                    })?;
                    NodeMetadata::Classpath(data)
                }
                NODE_METADATA_SYNTHETIC => NodeMetadata::Synthetic,
                _ => {
                    // Default: treat as Macro (covers both explicit 0 and legacy)
                    let data = e.macro_data.unwrap_or_default();
                    NodeMetadata::Macro(data)
                }
            };
            map.insert((e.index, e.generation), metadata);
        }
        Ok(Self { entries: map })
    }
}

impl NodeMetadataStore {
    /// Create a new empty metadata store.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Get metadata for a node, if any exists.
    ///
    /// Returns `None` if no metadata is stored for this node, or if the
    /// generation doesn't match (indicating a stale reference).
    #[must_use]
    pub fn get(&self, node_id: NodeId) -> Option<&MacroNodeMetadata> {
        match self.entries.get(&(node_id.index(), node_id.generation()))? {
            NodeMetadata::Macro(m) => Some(m),
            NodeMetadata::Classpath(_) | NodeMetadata::Synthetic => None,
        }
    }

    /// Get the full `NodeMetadata` envelope for a node, if any exists.
    ///
    /// Returns `None` if no metadata is stored for this node, or if the
    /// generation doesn't match (indicating a stale reference).
    #[must_use]
    pub fn get_metadata(&self, node_id: NodeId) -> Option<&NodeMetadata> {
        self.entries.get(&(node_id.index(), node_id.generation()))
    }

    /// Get mutable metadata for a node, if any exists.
    #[must_use]
    pub fn get_mut(&mut self, node_id: NodeId) -> Option<&mut MacroNodeMetadata> {
        match self
            .entries
            .get_mut(&(node_id.index(), node_id.generation()))?
        {
            NodeMetadata::Macro(m) => Some(m),
            NodeMetadata::Classpath(_) | NodeMetadata::Synthetic => None,
        }
    }

    /// Insert macro metadata for a node, replacing any existing entry.
    ///
    /// Convenience method that wraps the metadata in `NodeMetadata::Macro`.
    pub fn insert(&mut self, node_id: NodeId, metadata: MacroNodeMetadata) {
        self.entries.insert(
            (node_id.index(), node_id.generation()),
            NodeMetadata::Macro(metadata),
        );
    }

    /// Insert typed metadata for a node, replacing any existing entry.
    pub fn insert_metadata(&mut self, node_id: NodeId, metadata: NodeMetadata) {
        self.entries
            .insert((node_id.index(), node_id.generation()), metadata);
    }

    /// Mark a node as synthetic (C_SUPPRESS).
    ///
    /// Synthetic nodes are internal placeholders the language plugins
    /// emit for binding-plane / scope analysis (e.g., the Go plugin's
    /// `<field:operand.field>` field-access shadows and the
    /// `name@<offset>` per-binding-site Variable nodes from the local
    /// scope resolver). They MUST be filtered out of every user-facing
    /// surface (CLI `search`, MCP `semantic_search` / `relation_query`,
    /// etc.) but stay reachable to internal binding-plane callers via
    /// the explicit `include_synthetic` opt-in path on
    /// [`crate::graph::unified::concurrent::graph::GraphSnapshot::find_by_pattern_with_options`].
    ///
    /// If the node already has macro or classpath metadata, calling this
    /// method REPLACES it with the synthetic marker. Synthetic nodes by
    /// construction never carry macro/classpath provenance — the Go
    /// plugin emits them as plain Variable / Property scaffolding —
    /// so the replacement collision is benign.
    pub fn mark_synthetic(&mut self, node_id: NodeId) {
        self.entries.insert(
            (node_id.index(), node_id.generation()),
            NodeMetadata::Synthetic,
        );
    }

    /// Returns `true` iff the node is flagged as synthetic.
    ///
    /// Returns `false` for non-synthetic nodes, missing entries, and
    /// stale `NodeId` generations. Companion to [`Self::mark_synthetic`];
    /// see [`NodeMetadata::Synthetic`] for the full semantic contract.
    #[must_use]
    pub fn is_synthetic(&self, node_id: NodeId) -> bool {
        matches!(
            self.entries.get(&(node_id.index(), node_id.generation())),
            Some(NodeMetadata::Synthetic)
        )
    }

    /// Get or insert default macro metadata for a node.
    ///
    /// # Panics
    ///
    /// Panics if the node already has a `Classpath` metadata entry at this key,
    /// which indicates a programming error — callers must not mix metadata types
    /// for the same node.
    pub fn get_or_insert_default(&mut self, node_id: NodeId) -> &mut MacroNodeMetadata {
        let entry = self
            .entries
            .entry((node_id.index(), node_id.generation()))
            .or_insert_with(|| NodeMetadata::Macro(MacroNodeMetadata::default()));
        match entry {
            NodeMetadata::Macro(m) => m,
            // If a non-macro entry already exists at this key, this is a
            // programming error — callers should not mix metadata types for the
            // same node. Panic in debug, return a default in release.
            NodeMetadata::Classpath(_) => {
                panic!("get_or_insert_default called on a Classpath metadata entry")
            }
            NodeMetadata::Synthetic => {
                panic!("get_or_insert_default called on a Synthetic metadata entry")
            }
        }
    }

    /// Remove metadata for a node.
    pub fn remove(&mut self, node_id: NodeId) -> Option<MacroNodeMetadata> {
        match self
            .entries
            .remove(&(node_id.index(), node_id.generation()))?
        {
            NodeMetadata::Macro(m) => Some(m),
            NodeMetadata::Classpath(_) | NodeMetadata::Synthetic => None,
        }
    }

    /// Remove typed metadata for a node.
    pub fn remove_metadata(&mut self, node_id: NodeId) -> Option<NodeMetadata> {
        self.entries
            .remove(&(node_id.index(), node_id.generation()))
    }

    /// Returns the number of nodes with metadata.
    #[must_use]
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns true if no nodes have metadata.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Iterate over all metadata entries.
    pub fn iter(&self) -> impl Iterator<Item = ((u32, u64), &MacroNodeMetadata)> {
        self.entries.iter().filter_map(|(&k, v)| match v {
            NodeMetadata::Macro(m) => Some((k, m)),
            NodeMetadata::Classpath(_) | NodeMetadata::Synthetic => None,
        })
    }

    /// Iterate over all metadata entries as typed `NodeMetadata`.
    pub fn iter_all(&self) -> impl Iterator<Item = ((u32, u64), &NodeMetadata)> {
        self.entries.iter().map(|(&k, v)| (k, v))
    }

    /// Merge another metadata store into this one.
    ///
    /// Entries from `other` overwrite existing entries with the same key.
    pub fn merge(&mut self, other: &NodeMetadataStore) {
        for (&key, value) in &other.entries {
            self.entries.insert(key, value.clone());
        }
    }

    /// Retain only entries whose `(index, generation)` key satisfies `keep`.
    ///
    /// Used by the Gate 0b [`NodeIdBearing`] impl
    /// (`sqry-core/src/graph/unified/rebuild/coverage.rs`) to drop
    /// metadata for tombstoned NodeIds during
    /// `RebuildGraph::finalize()`. Exposed at `pub(crate)` scope because
    /// only the rebuild pipeline needs predicate-based filtering;
    /// downstream callers use the targeted [`Self::remove`] /
    /// [`Self::remove_metadata`] entry points.
    ///
    /// `#[allow(dead_code)]` is present because Gate 0b delivers only
    /// the scaffolding — the call sites in `RebuildGraph::finalize()`
    /// (Gate 0c) and the residue check (Gate 0d) land in follow-up
    /// commits. Unit coverage in
    /// `sqry-core/src/graph/unified/rebuild/coverage.rs::tests` already
    /// exercises this helper through the [`NodeIdBearing::retain_nodes`]
    /// impl.
    ///
    /// [`NodeIdBearing`]: crate::graph::unified::rebuild::coverage::NodeIdBearing
    /// [`NodeIdBearing::retain_nodes`]: crate::graph::unified::rebuild::coverage::NodeIdBearing::retain_nodes
    #[allow(dead_code)]
    pub(crate) fn retain_entries<F>(&mut self, mut keep: F)
    where
        F: FnMut(u32, u64) -> bool,
    {
        self.entries
            .retain(|&(index, generation), _meta| keep(index, generation));
    }
}

impl PartialEq for NodeMetadataStore {
    fn eq(&self, other: &Self) -> bool {
        self.entries == other.entries
    }
}

impl Eq for NodeMetadataStore {}

impl crate::graph::unified::memory::GraphMemorySize for NodeMetadataStore {
    fn heap_bytes(&self) -> usize {
        use crate::graph::unified::memory::HASHMAP_ENTRY_OVERHEAD;

        let base = self.entries.capacity()
            * (std::mem::size_of::<(u32, u64)>()
                + std::mem::size_of::<NodeMetadata>()
                + HASHMAP_ENTRY_OVERHEAD);
        // Account for heap Strings inside each metadata variant.
        let inner: usize = self
            .entries
            .values()
            .map(|meta| match meta {
                NodeMetadata::Macro(m) => {
                    m.macro_source.as_ref().map_or(0, String::capacity)
                        + m.cfg_condition.as_ref().map_or(0, String::capacity)
                        + m.unresolved_attributes
                            .iter()
                            .map(String::capacity)
                            .sum::<usize>()
                        + m.unresolved_attributes.capacity() * std::mem::size_of::<String>()
                }
                NodeMetadata::Classpath(c) => {
                    c.coordinates.as_ref().map_or(0, String::capacity)
                        + c.jar_path.capacity()
                        + c.fqn.capacity()
                }
                // Payload-less marker: only the enum tag itself, which
                // is already counted by `mem::size_of::<NodeMetadata>()`
                // in the `base` calculation above.
                NodeMetadata::Synthetic => 0,
            })
            .sum();
        base + inner
    }
}

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

    #[test]
    fn test_metadata_store_basic_operations() {
        let mut store = NodeMetadataStore::new();
        assert!(store.is_empty());
        assert_eq!(store.len(), 0);

        let node = NodeId::new(5, 1);
        let metadata = MacroNodeMetadata {
            macro_generated: Some(true),
            macro_source: Some("derive_Debug".to_string()),
            ..Default::default()
        };

        store.insert(node, metadata.clone());
        assert_eq!(store.len(), 1);
        assert!(!store.is_empty());

        let retrieved = store.get(node).unwrap();
        assert_eq!(retrieved.macro_generated, Some(true));
        assert_eq!(retrieved.macro_source.as_deref(), Some("derive_Debug"));
    }

    #[test]
    fn test_metadata_full_nodeid_key() {
        let mut store = NodeMetadataStore::new();

        let node_gen1 = NodeId::new(5, 1);
        let node_gen2 = NodeId::new(5, 2);

        store.insert(
            node_gen1,
            MacroNodeMetadata {
                macro_generated: Some(true),
                ..Default::default()
            },
        );

        // Same index, different generation → should NOT match
        assert!(store.get(node_gen2).is_none());

        // Same index, same generation → should match
        assert!(store.get(node_gen1).is_some());
    }

    #[test]
    fn test_metadata_slot_reuse_no_stale_data() {
        let mut store = NodeMetadataStore::new();

        // Simulate: node at index 5 gen 1 has metadata
        let old_node = NodeId::new(5, 1);
        store.insert(
            old_node,
            MacroNodeMetadata {
                cfg_condition: Some("test".to_string()),
                ..Default::default()
            },
        );

        // Simulate: slot 5 is reused with generation 2 (new node)
        let new_node = NodeId::new(5, 2);

        // New node should NOT see old metadata
        assert!(store.get(new_node).is_none());

        // Old node still accessible
        assert_eq!(
            store.get(old_node).unwrap().cfg_condition.as_deref(),
            Some("test")
        );
    }

    #[test]
    fn test_metadata_store_postcard_roundtrip() {
        let mut store = NodeMetadataStore::new();

        store.insert(
            NodeId::new(1, 0),
            MacroNodeMetadata {
                macro_generated: Some(true),
                macro_source: Some("derive_Debug".to_string()),
                cfg_condition: Some("test".to_string()),
                cfg_active: Some(true),
                proc_macro_kind: Some(ProcMacroFunctionKind::Derive),
                expansion_cached: Some(false),
                unresolved_attributes: vec!["my_attr".to_string()],
            },
        );

        store.insert(
            NodeId::new(42, 3),
            MacroNodeMetadata {
                cfg_condition: Some("feature = \"serde\"".to_string()),
                ..Default::default()
            },
        );

        let bytes = postcard::to_allocvec(&store).expect("serialize");
        let deserialized: NodeMetadataStore = postcard::from_bytes(&bytes).expect("deserialize");

        assert_eq!(store, deserialized);
    }

    #[test]
    fn test_empty_metadata_store_zero_overhead() {
        let store = NodeMetadataStore::new();
        let bytes = postcard::to_allocvec(&store).expect("serialize");

        // Empty HashMap serializes to a single varint length of 0
        assert!(
            bytes.len() <= 2,
            "Empty store should serialize to minimal bytes, got {} bytes",
            bytes.len()
        );
    }

    #[test]
    fn test_metadata_store_merge() {
        let mut store1 = NodeMetadataStore::new();
        let mut store2 = NodeMetadataStore::new();

        store1.insert(
            NodeId::new(1, 0),
            MacroNodeMetadata {
                macro_generated: Some(true),
                ..Default::default()
            },
        );

        store2.insert(
            NodeId::new(2, 0),
            MacroNodeMetadata {
                cfg_condition: Some("test".to_string()),
                ..Default::default()
            },
        );

        store1.merge(&store2);
        assert_eq!(store1.len(), 2);
        assert!(store1.get(NodeId::new(1, 0)).is_some());
        assert!(store1.get(NodeId::new(2, 0)).is_some());
    }

    #[test]
    fn test_proc_macro_function_kind_serde() {
        let kinds = [
            ProcMacroFunctionKind::Derive,
            ProcMacroFunctionKind::Attribute,
            ProcMacroFunctionKind::FunctionLike,
        ];

        for kind in kinds {
            let bytes = postcard::to_allocvec(&kind).expect("serialize");
            let deserialized: ProcMacroFunctionKind =
                postcard::from_bytes(&bytes).expect("deserialize");
            assert_eq!(kind, deserialized);
        }
    }

    #[test]
    fn test_metadata_get_or_insert_default() {
        let mut store = NodeMetadataStore::new();
        let node = NodeId::new(10, 0);

        // First access creates default
        let meta = store.get_or_insert_default(node);
        meta.cfg_condition = Some("test".to_string());

        // Second access returns existing
        let meta = store.get(node).unwrap();
        assert_eq!(meta.cfg_condition.as_deref(), Some("test"));
    }

    #[test]
    fn test_metadata_remove() {
        let mut store = NodeMetadataStore::new();
        let node = NodeId::new(1, 0);

        store.insert(
            node,
            MacroNodeMetadata {
                macro_generated: Some(true),
                ..Default::default()
            },
        );

        assert!(store.get(node).is_some());
        let removed = store.remove(node);
        assert!(removed.is_some());
        assert!(store.get(node).is_none());
        assert!(store.is_empty());
    }

    #[test]
    fn test_metadata_store_large_scale() {
        let mut store = NodeMetadataStore::new();

        // Insert 10K entries (simulating ~10% of a 100K-node codebase)
        for i in 0..10_000u32 {
            store.insert(
                NodeId::new(i, 0),
                MacroNodeMetadata {
                    cfg_condition: Some(format!("feature_{i}")),
                    ..Default::default()
                },
            );
        }

        assert_eq!(store.len(), 10_000);

        // Verify O(1) lookups
        assert!(store.get(NodeId::new(0, 0)).is_some());
        assert!(store.get(NodeId::new(5_000, 0)).is_some());
        assert!(store.get(NodeId::new(9_999, 0)).is_some());
        assert!(store.get(NodeId::new(10_000, 0)).is_none());

        // Verify round-trip
        let bytes = postcard::to_allocvec(&store).expect("serialize");
        let deserialized: NodeMetadataStore = postcard::from_bytes(&bytes).expect("deserialize");
        assert_eq!(store, deserialized);
    }

    #[test]
    fn test_classpath_metadata_insert_and_get() {
        let mut store = NodeMetadataStore::new();
        let node = NodeId::new(100, 0);

        let cp_meta = ClasspathNodeMetadata {
            coordinates: Some("com.google.guava:guava:33.0.0".to_string()),
            jar_path: "/home/user/.m2/repository/guava-33.0.0.jar".to_string(),
            fqn: "com.google.common.collect.ImmutableList".to_string(),
            is_direct_dependency: true,
        };

        store.insert_metadata(node, NodeMetadata::Classpath(cp_meta.clone()));
        assert_eq!(store.len(), 1);

        // get() should return None (only returns macro metadata)
        assert!(store.get(node).is_none());

        // get_metadata() should return the classpath metadata
        let retrieved = store.get_metadata(node).unwrap();
        match retrieved {
            NodeMetadata::Classpath(cp) => {
                assert_eq!(cp.fqn, "com.google.common.collect.ImmutableList");
                assert_eq!(
                    cp.coordinates.as_deref(),
                    Some("com.google.guava:guava:33.0.0")
                );
                assert!(cp.is_direct_dependency);
            }
            NodeMetadata::Macro(_) => panic!("expected Classpath variant"),
            NodeMetadata::Synthetic => panic!("expected Classpath variant, got Synthetic"),
        }
    }

    #[test]
    fn test_classpath_metadata_postcard_roundtrip() {
        let mut store = NodeMetadataStore::new();

        // Mix of macro and classpath metadata
        store.insert(
            NodeId::new(1, 0),
            MacroNodeMetadata {
                macro_generated: Some(true),
                ..Default::default()
            },
        );

        store.insert_metadata(
            NodeId::new(2, 0),
            NodeMetadata::Classpath(ClasspathNodeMetadata {
                coordinates: Some("org.slf4j:slf4j-api:2.0.0".to_string()),
                jar_path: "slf4j-api-2.0.0.jar".to_string(),
                fqn: "org.slf4j.Logger".to_string(),
                is_direct_dependency: false,
            }),
        );

        let bytes = postcard::to_allocvec(&store).expect("serialize");
        let deserialized: NodeMetadataStore = postcard::from_bytes(&bytes).expect("deserialize");
        assert_eq!(store, deserialized);
        assert_eq!(deserialized.len(), 2);

        // Verify macro entry
        assert!(deserialized.get(NodeId::new(1, 0)).is_some());

        // Verify classpath entry via get_metadata
        let cp = deserialized.get_metadata(NodeId::new(2, 0)).unwrap();
        assert!(matches!(cp, NodeMetadata::Classpath(_)));
    }

    #[test]
    fn test_node_metadata_store_json_roundtrip() {
        let mut store = NodeMetadataStore::new();

        store.insert(
            NodeId::new(1, 0),
            MacroNodeMetadata {
                macro_generated: Some(true),
                macro_source: Some("serde_derive".to_string()),
                ..Default::default()
            },
        );

        store.insert_metadata(
            NodeId::new(2, 0),
            NodeMetadata::Classpath(ClasspathNodeMetadata {
                coordinates: None,
                jar_path: "rt.jar".to_string(),
                fqn: "java.lang.String".to_string(),
                is_direct_dependency: true,
            }),
        );

        let json = serde_json::to_string(&store).unwrap();
        let deserialized: NodeMetadataStore = serde_json::from_str(&json).unwrap();
        assert_eq!(store, deserialized);
    }

    #[test]
    fn test_iter_all_includes_both_types() {
        let mut store = NodeMetadataStore::new();

        store.insert(
            NodeId::new(1, 0),
            MacroNodeMetadata {
                macro_generated: Some(true),
                ..Default::default()
            },
        );

        store.insert_metadata(
            NodeId::new(2, 0),
            NodeMetadata::Classpath(ClasspathNodeMetadata {
                coordinates: None,
                jar_path: "test.jar".to_string(),
                fqn: "com.example.Test".to_string(),
                is_direct_dependency: true,
            }),
        );

        // iter() only yields macro entries
        let macro_entries: Vec<_> = store.iter().collect();
        assert_eq!(macro_entries.len(), 1);

        // iter_all() yields all entries
        let all_entries: Vec<_> = store.iter_all().collect();
        assert_eq!(all_entries.len(), 2);
    }

    #[test]
    fn test_remove_metadata_classpath() {
        let mut store = NodeMetadataStore::new();
        let node = NodeId::new(50, 0);

        store.insert_metadata(
            node,
            NodeMetadata::Classpath(ClasspathNodeMetadata {
                coordinates: None,
                jar_path: "test.jar".to_string(),
                fqn: "Test".to_string(),
                is_direct_dependency: true,
            }),
        );

        assert_eq!(store.len(), 1);

        // remove() returns None for non-macro entries
        let removed = store.remove(node);
        assert!(removed.is_none());
        // The entry is still gone from the store because remove() always removes
        assert!(store.is_empty());
    }

    // ------------------------------------------------------------------
    // C_SUPPRESS: NodeMetadata::Synthetic variant
    // ------------------------------------------------------------------

    #[test]
    fn synthetic_mark_and_query() {
        let mut store = NodeMetadataStore::new();
        let node = NodeId::new(7, 1);

        assert!(!store.is_synthetic(node), "missing entry must report false");

        store.mark_synthetic(node);
        assert!(store.is_synthetic(node));
        assert_eq!(store.len(), 1);

        // get() returns None — synthetic carries no MacroNodeMetadata payload.
        assert!(store.get(node).is_none());

        // get_metadata() returns the typed envelope.
        assert!(matches!(
            store.get_metadata(node),
            Some(NodeMetadata::Synthetic),
        ));

        // Stale generation must NOT see the synthetic flag.
        let stale = NodeId::new(7, 2);
        assert!(!store.is_synthetic(stale));
    }

    #[test]
    fn synthetic_replaces_other_variants() {
        let mut store = NodeMetadataStore::new();
        let node = NodeId::new(11, 1);

        store.insert(
            node,
            MacroNodeMetadata {
                cfg_condition: Some("test".to_string()),
                ..Default::default()
            },
        );
        assert!(store.get(node).is_some());

        store.mark_synthetic(node);
        assert!(store.is_synthetic(node));
        // The macro payload is replaced — `get` no longer surfaces a MacroNodeMetadata.
        assert!(store.get(node).is_none());
        assert_eq!(store.len(), 1);
    }

    #[test]
    fn synthetic_postcard_roundtrip_preserves_v10_wire_shape() {
        // Build a store that mixes all three variants so the postcard
        // round-trip exercises the `kind` discriminant dispatch end-to-end.
        let mut store = NodeMetadataStore::new();

        store.insert(
            NodeId::new(1, 0),
            MacroNodeMetadata {
                macro_generated: Some(true),
                ..Default::default()
            },
        );
        store.insert_metadata(
            NodeId::new(2, 0),
            NodeMetadata::Classpath(ClasspathNodeMetadata {
                coordinates: None,
                jar_path: "x.jar".to_string(),
                fqn: "com.example.X".to_string(),
                is_direct_dependency: true,
            }),
        );
        store.mark_synthetic(NodeId::new(3, 0));
        store.mark_synthetic(NodeId::new(99, 5));

        let bytes = postcard::to_allocvec(&store).expect("serialize");
        let decoded: NodeMetadataStore = postcard::from_bytes(&bytes).expect("deserialize");

        assert_eq!(store, decoded);
        assert_eq!(decoded.len(), 4);
        assert!(decoded.is_synthetic(NodeId::new(3, 0)));
        assert!(decoded.is_synthetic(NodeId::new(99, 5)));
        assert!(matches!(
            decoded.get_metadata(NodeId::new(2, 0)),
            Some(NodeMetadata::Classpath(_))
        ));
        assert!(matches!(
            decoded.get_metadata(NodeId::new(1, 0)),
            Some(NodeMetadata::Macro(_))
        ));
    }

    #[test]
    fn synthetic_v10_legacy_snapshot_decodes_without_synthetic_entries() {
        // Simulate a "legacy" V10 snapshot written before the Synthetic
        // variant existed — only kinds 0 and 1 appear on the wire.
        let mut legacy = NodeMetadataStore::new();
        legacy.insert(
            NodeId::new(1, 0),
            MacroNodeMetadata {
                macro_generated: Some(true),
                ..Default::default()
            },
        );
        legacy.insert_metadata(
            NodeId::new(2, 0),
            NodeMetadata::Classpath(ClasspathNodeMetadata {
                coordinates: None,
                jar_path: "y.jar".to_string(),
                fqn: "com.example.Y".to_string(),
                is_direct_dependency: false,
            }),
        );

        // Round-trip through the same writer/reader the new code uses;
        // the legacy fixture has zero synthetic entries because they did
        // not exist when it was written.
        let bytes = postcard::to_allocvec(&legacy).expect("serialize");
        let decoded: NodeMetadataStore = postcard::from_bytes(&bytes).expect("deserialize");

        assert_eq!(legacy, decoded);
        assert!(!decoded.is_synthetic(NodeId::new(1, 0)));
        assert!(!decoded.is_synthetic(NodeId::new(2, 0)));
        assert_eq!(decoded.len(), 2);
    }

    #[test]
    fn test_remove_metadata_typed() {
        let mut store = NodeMetadataStore::new();
        let node = NodeId::new(50, 0);

        store.insert_metadata(
            node,
            NodeMetadata::Classpath(ClasspathNodeMetadata {
                coordinates: None,
                jar_path: "test.jar".to_string(),
                fqn: "Test".to_string(),
                is_direct_dependency: true,
            }),
        );

        // remove_metadata() returns the full NodeMetadata
        let removed = store.remove_metadata(node);
        assert!(matches!(removed, Some(NodeMetadata::Classpath(_))));
        assert!(store.is_empty());
    }
}