-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph.go
More file actions
1417 lines (1314 loc) · 42.8 KB
/
Copy pathgraph.go
File metadata and controls
1417 lines (1314 loc) · 42.8 KB
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
package sdk
import (
"container/heap"
"errors"
"fmt"
"sort"
"strings"
"github.com/bomly-dev/bomly-sdk/purlkit"
)
var (
ErrNilNode = errors.New("graph node is nil")
ErrEmptyNodeID = errors.New("graph node id is empty")
ErrNodeAlreadyExist = errors.New("graph node already exists")
ErrNodeNotFound = errors.New("graph node not found")
ErrSelfDependency = errors.New("self dependency is not allowed")
ErrCycleDetected = errors.New("dependency creates a cycle")
)
// Path describes one path through the graph. Paths are heterogeneous: they
// traverse manifest and module nodes on their way to dependencies.
type Path struct {
Nodes []GraphNode
Cyclic bool
CycleTo string
}
// Diff summarizes the dependency changes between two graphs. Diffs are
// dependency-only: manifest and module nodes are structural and do not
// participate.
type Diff struct {
Added []*DependencyNode
Removed []*DependencyNode
Updated []VersionChange
Transitions []DependencyDetailTransition
}
// VersionChange captures a dependency identity that changed versions.
type VersionChange struct {
Before *DependencyNode
After *DependencyNode
}
// DependencyDetailField identifies one dependency property that changed
// independently of package identity or version.
type DependencyDetailField string
const (
// DependencyDetailRelationship is a direct, transitive, or unknown
// relationship change.
DependencyDetailRelationship DependencyDetailField = "relationship"
// DependencyDetailSource is a registry, workspace, file, Git, URL, or
// project source change.
DependencyDetailSource DependencyDetailField = "source"
// DependencyDetailRegistryEligibility indicates that external registry
// matching eligibility changed.
DependencyDetailRegistryEligibility DependencyDetailField = "registry_eligibility"
)
// DependencyDetailTransition captures same-identity dependency detail changes.
// Version changes remain represented separately by VersionChange.
type DependencyDetailTransition struct {
Before *DependencyNode `json:"before"`
After *DependencyNode `json:"after"`
ChangedFields []DependencyDetailField `json:"changedFields"`
BeforeRelationship DependencyRelationship `json:"beforeRelationship,omitempty"`
AfterRelationship DependencyRelationship `json:"afterRelationship,omitempty"`
BeforeRegistryEligible bool `json:"beforeRegistryEligible"`
AfterRegistryEligible bool `json:"afterRegistryEligible"`
}
// DependencyDetailReviewReason explains why a dependency detail change should
// receive extra review.
type DependencyDetailReviewReason string
const (
// DependencyDetailReviewSourceGit indicates that the dependency now comes
// from a Git repository.
DependencyDetailReviewSourceGit DependencyDetailReviewReason = "source-changed-to-git"
// DependencyDetailReviewSourceURL indicates that the dependency now comes
// from an arbitrary URL.
DependencyDetailReviewSourceURL DependencyDetailReviewReason = "source-changed-to-url"
)
// ReviewReasons returns the reasons this detail change needs extra review.
// The result is deterministic and does not treat missing evidence, coverage
// gains, or relationship-only changes as review signals.
func (t DependencyDetailTransition) ReviewReasons() []DependencyDetailReviewReason {
reasons := make([]DependencyDetailReviewReason, 0, 1)
if dependencyDetailFieldIncluded(t.ChangedFields, DependencyDetailSource) &&
t.Before != nil && strings.TrimSpace(string(t.Before.Source)) != "" &&
t.After != nil {
switch t.After.Source {
case DependencySourceGit:
reasons = append(reasons, DependencyDetailReviewSourceGit)
case DependencySourceURL:
reasons = append(reasons, DependencyDetailReviewSourceURL)
}
}
return reasons
}
// NeedsReview reports whether this detail change has at least one review reason.
func (t DependencyDetailTransition) NeedsReview() bool {
return len(t.ReviewReasons()) > 0
}
// CloneDependencyDetailTransitions returns a deep copy of dependency detail
// transitions suitable for crossing component and plugin boundaries.
func CloneDependencyDetailTransitions(transitions []DependencyDetailTransition) []DependencyDetailTransition {
if transitions == nil {
return nil
}
cloned := make([]DependencyDetailTransition, len(transitions))
for index, transition := range transitions {
cloned[index] = transition
cloned[index].ChangedFields = append([]DependencyDetailField(nil), transition.ChangedFields...)
if transition.Before != nil {
cloned[index].Before = transition.Before.Clone()
}
if transition.After != nil {
cloned[index].After = transition.After.Clone()
}
}
return cloned
}
func dependencyDetailFieldIncluded(fields []DependencyDetailField, wanted DependencyDetailField) bool {
for _, field := range fields {
if field == wanted {
return true
}
}
return false
}
// Graph stores the typed graph nodes as a directed graph, keyed by NodeID.
// A node's ID is its identity (ADR-0041), so the ID index doubles as the
// identity index: two nodes are the same node exactly when their IDs match.
type Graph struct {
indexByID map[string]int
nodes []GraphNode
alive []bool
outgoing []map[int]EdgeKind
incoming []map[int]EdgeKind
free []int
size int
}
// New creates an empty graph.
func New() *Graph {
return NewWithCapacity(0)
}
// NewWithCapacity creates an empty graph sized for the expected node count.
func NewWithCapacity(nodeCount int) *Graph {
return &Graph{
indexByID: make(map[string]int, nodeCount),
nodes: make([]GraphNode, 0, nodeCount),
alive: make([]bool, 0, nodeCount),
outgoing: make([]map[int]EdgeKind, 0, nodeCount),
incoming: make([]map[int]EdgeKind, 0, nodeCount),
}
}
// AddNode inserts a node, rejecting a duplicate identity. Use InsertNode
// for fold-by-identity insertion.
func (g *Graph) AddNode(node GraphNode) error {
if isNilNode(node) {
return ErrNilNode
}
if node.NodeID() == "" {
return ErrEmptyNodeID
}
if _, exists := g.indexByID[node.NodeID()]; exists {
return fmt.Errorf("%w: %s", ErrNodeAlreadyExist, node.NodeID())
}
idx := g.nextSlot()
g.nodes[idx] = node
g.alive[idx] = true
g.outgoing[idx] = make(map[int]EdgeKind)
g.incoming[idx] = make(map[int]EdgeKind)
g.indexByID[node.NodeID()] = idx
g.size++
return nil
}
// InsertNode is fold-by-identity insertion (ADR-0041): a node whose
// identity already exists in the graph unions into the existing record and
// the survivor is returned. Identity is the node ID, and IDs are disjoint
// across kinds, so a fold always joins records of one kind. Dependency
// folds union scopes, locations, and origins, merge the relationship, and
// fold registry-match eligibility toward eligible (any-witness: when
// exactly one witness is eligible, its source survives — withholding
// enrichment from a package a registry release genuinely uses would hide
// vulnerabilities). Module folds union locations; manifest folds are
// no-ops beyond the identity match.
func (g *Graph) InsertNode(node GraphNode) (GraphNode, error) {
if isNilNode(node) {
return nil, ErrNilNode
}
if node.NodeID() == "" {
return nil, ErrEmptyNodeID
}
existing, ok := g.Node(node.NodeID())
if !ok {
if err := g.AddNode(node); err != nil {
return nil, err
}
return node, nil
}
foldNodes(existing, node)
return existing, nil
}
// isNilNode reports whether a GraphNode is absent — including a typed nil
// such as (*DependencyNode)(nil), which is a non-nil interface value whose
// methods would panic. A failed constructor's zero return must surface as
// ErrNilNode, not a crash.
func isNilNode(node GraphNode) bool {
switch n := node.(type) {
case nil:
return true
case *ManifestNode:
return n == nil
case *ModuleNode:
return n == nil
case *DependencyNode:
return n == nil
default:
return false
}
}
// foldNodes unions one witness into the surviving record of the same
// identity. Kinds always match because IDs are kind-disjoint.
func foldNodes(surviving, witness GraphNode) {
switch survivor := surviving.(type) {
case *DependencyNode:
incoming, ok := witness.(*DependencyNode)
if !ok {
return
}
survivor.Relationship = MergeDependencyRelationship(survivor.Relationship, incoming.Relationship)
for _, scope := range incoming.Scopes {
survivor.AddScope(scope)
}
mergeNodeLocations(&survivor.Locations, incoming.Locations)
survivor.Origins = MergeOrigins(survivor.Origins, incoming.Origins)
mergeDependencySources(survivor, incoming)
// Every witness's assertions about one package survive the fold:
// security identifiers and integrity claims union, detection
// scalars and metadata fill gaps. Dropping them would lose CPEs or
// digests from a second SBOM witness on insertion order alone.
survivor.CPEs = mergeStringSet(survivor.CPEs, incoming.CPEs)
survivor.Digests = mergeDigestSet(survivor.Digests, incoming.Digests)
// License claims are a set for the same reason they are on Package: a
// declaration and a conclusion are two claims about one package, and
// two witnesses that read different sources both have something to
// say.
// DetectionLicenses on both sides, not the typed field alone: a
// witness built before the typed field existed carries its claims in
// the deprecated metadata stash, and metadata merging keeps the
// survivor's value -- so the incoming witness's licenses would be
// dropped before seeding ever saw them.
survivor.Licenses = MergeLicenses(DetectionLicenses(survivor), DetectionLicenses(incoming))
survivor.ExternalReferences = MergeExternalReferences(survivor.ExternalReferences, incoming.ExternalReferences)
// The component-level document assertions are scalars — one supplier,
// one homepage — so a later witness contributes only what the first
// did not know.
//
// Both sides are gated before the gap is measured, not after. A node
// built in process never passed a codec, so a survivor could hold an
// unpublishable value — a homepage carrying credentials — which is
// non-empty and therefore blocks a valid incoming one, and is then
// dropped at encode. The result would be that a witness with a good
// homepage lost it to a witness that never had one.
survivor.Description = NormalizeDescription(survivor.Description)
survivor.Homepage = NormalizeHomepage(survivor.Homepage)
survivor.Supplier = normalizedContact(survivor.Supplier)
survivor.Originator = normalizedContact(survivor.Originator)
if survivor.Description == "" {
survivor.Description = NormalizeDescription(incoming.Description)
}
if survivor.Homepage == "" {
survivor.Homepage = NormalizeHomepage(incoming.Homepage)
}
if survivor.Supplier == nil {
survivor.Supplier = normalizedContact(incoming.Supplier)
}
if survivor.Originator == nil {
survivor.Originator = normalizedContact(incoming.Originator)
}
if survivor.Copyright == "" {
survivor.Copyright = incoming.Copyright
}
if survivor.FoundBy == "" {
survivor.FoundBy = incoming.FoundBy
}
if survivor.ResolvedURL == "" {
survivor.ResolvedURL = incoming.ResolvedURL
}
if survivor.PackageRef == "" {
survivor.PackageRef = incoming.PackageRef
}
// Classification the identity cannot project also fills gaps: a
// bare-package-URL witness folded first would otherwise leave the
// node with an unknown package manager, which manager-specific
// consumers (remediation hints, most of all) key on.
if survivor.PackageManager == PackageManagerUnknown {
survivor.PackageManager = incoming.PackageManager
}
if survivor.Language == "" {
survivor.Language = incoming.Language
}
if survivor.Type == "" {
survivor.Type = incoming.Type
}
// Enrichment is an any-witness fact: one witness having been
// matched is true of the folded record.
survivor.Matched = survivor.Matched || incoming.Matched
survivor.Metadata = mergeMetadata(survivor.Metadata, incoming.Metadata)
case *ModuleNode:
incoming, ok := witness.(*ModuleNode)
if !ok {
return
}
// A module identified by path and name carries no version in its
// identity, so two witnesses of one module — one versionless —
// fold, and without this the survivor's empty version would let
// insertion order decide what gets published.
if survivor.Version == "" {
survivor.Version = incoming.Version
}
if survivor.Ecosystem == "" {
survivor.Ecosystem = incoming.Ecosystem
}
if survivor.PackageManager == PackageManagerUnknown {
survivor.PackageManager = incoming.PackageManager
}
if survivor.Language == "" {
survivor.Language = incoming.Language
}
mergeNodeLocations(&survivor.Locations, incoming.Locations)
survivor.Metadata = mergeMetadata(survivor.Metadata, incoming.Metadata)
case *ManifestNode:
incoming, ok := witness.(*ManifestNode)
if !ok {
return
}
// A manifest's classification lives only on the node, so an
// unclassified first witness must not block a later classified one
// — otherwise consolidation order decides whether the POM,
// lockfile, or workflow kind survives.
if survivor.FileKind == "" {
survivor.FileKind = incoming.FileKind
}
survivor.Metadata = mergeMetadata(survivor.Metadata, incoming.Metadata)
}
}
// mergeStringSet unions two string slices, preserving order and dropping
// duplicates.
func mergeStringSet(existing, additions []string) []string {
if len(additions) == 0 {
return existing
}
seen := make(map[string]struct{}, mergeCapacity(len(existing), len(additions)))
for _, value := range existing {
seen[value] = struct{}{}
}
for _, value := range additions {
if _, duplicate := seen[value]; duplicate {
continue
}
seen[value] = struct{}{}
existing = append(existing, value)
}
return existing
}
// mergeDigestSet unions two digest slices. Digests compare by whole value:
// algorithm, value, and subject together, since a digest of a different
// subject is a different claim.
// mergeDigestSet unions digests, normalizes their spellings, and drops any
// that cannot be published. It is the one place a digest slice is assembled,
// so every path — the graph fold, the wire codecs, package seeding, and
// Package.MergeFrom — inherits the same rule.
//
// The union is what keeps provenance: two records can carry genuinely
// different claims about one package, a hash of the published artifact from
// one source and a hash over the source tree from another, and Subject is
// what tells them apart. Keeping only the first slice would lose a claim to
// merge order alone.
//
// The drop matters as much as the union. Digest's codec zeroes a rejected value
// rather than failing the payload, but omitempty cannot omit a slice element,
// so a zeroed member survives as a literal "{}" in the encoded array -- an
// empty checksum record in a published document, which is worse than the
// rejected assertion it replaced. Filtering here, where digest slices are
// assembled, means every path that builds one is covered by the same rule.
func mergeDigestSet(existing, additions []Digest) []Digest {
merged := make([]Digest, 0, mergeCapacity(len(existing), len(additions)))
seen := make(map[Digest]struct{}, mergeCapacity(len(existing), len(additions)))
for _, group := range [][]Digest{existing, additions} {
for _, digest := range group {
normalized, ok := digest.Normalized()
if !ok {
continue
}
if _, duplicate := seen[normalized]; duplicate {
continue
}
seen[normalized] = struct{}{}
merged = append(merged, normalized)
}
}
if len(merged) == 0 {
return nil
}
// Sorted, so a set built from the same digests in different orders
// publishes the same document. Consolidation folds witnesses in whatever
// order they arrive, and these ride inside external references too, where
// sorting the references alone cannot fix a nested array's order.
sort.Slice(merged, func(i, j int) bool {
if merged[i].Algorithm != merged[j].Algorithm {
return merged[i].Algorithm < merged[j].Algorithm
}
if merged[i].Subject != merged[j].Subject {
return merged[i].Subject < merged[j].Subject
}
return merged[i].Value < merged[j].Value
})
return merged
}
// mergeMetadata fills the gaps in existing from additions. Keys the
// survivor already carries win, so a fold never rewrites an assertion the
// surviving record made.
func mergeMetadata(existing, additions map[string]any) map[string]any {
if len(additions) == 0 {
return existing
}
if existing == nil {
existing = make(map[string]any, len(additions))
}
for key, value := range additions {
if _, present := existing[key]; present {
continue
}
existing[key] = value
}
return existing
}
// mergeDependencySources folds registry-match eligibility toward eligible:
// when the surviving record is ineligible and the witness is eligible, the
// witness's source survives. Eligibility is computed per witness, so the
// Swift source-control special case and the unknown-source rule apply
// unchanged.
func mergeDependencySources(surviving, witness *DependencyNode) {
if surviving.RegistryMatchEligible() || !witness.RegistryMatchEligible() {
return
}
surviving.Source = witness.Source
}
// mergeNodeLocations appends the locations dst does not already carry.
func mergeNodeLocations(dst *[]PackageLocation, additions []PackageLocation) {
for _, location := range additions {
if !hasDependencyLocation(*dst, location) {
*dst = append(*dst, location)
}
}
}
// Node returns a node by ID.
func (g *Graph) Node(id string) (GraphNode, bool) {
idx, ok := g.indexByID[id]
if !ok {
return nil, false
}
return g.nodes[idx], ok
}
// DependencyNode returns the dependency node with the given ID, or false
// when the ID is absent or names a different kind.
func (g *Graph) DependencyNode(id string) (*DependencyNode, bool) {
node, ok := g.Node(id)
if !ok {
return nil, false
}
dep, ok := node.(*DependencyNode)
return dep, ok
}
// Nodes returns all nodes sorted by ID.
func (g *Graph) Nodes() []GraphNode {
indices := g.sortedIndices()
out := make([]GraphNode, 0, len(indices))
for _, idx := range indices {
out = append(out, g.nodes[idx])
}
return out
}
// DependencyNodes returns all dependency nodes sorted by ID — the iteration
// surface for matching, enrichment, and diffing, which are dependency-only.
func (g *Graph) DependencyNodes() []*DependencyNode {
out := make([]*DependencyNode, 0, g.size)
for _, idx := range g.sortedIndices() {
if dep, ok := g.nodes[idx].(*DependencyNode); ok {
out = append(out, dep)
}
}
return out
}
// ModuleNodes returns all module nodes sorted by ID.
func (g *Graph) ModuleNodes() []*ModuleNode {
out := make([]*ModuleNode, 0, g.size)
for _, idx := range g.sortedIndices() {
if module, ok := g.nodes[idx].(*ModuleNode); ok {
out = append(out, module)
}
}
return out
}
// ManifestNodes returns all manifest nodes sorted by ID.
func (g *Graph) ManifestNodes() []*ManifestNode {
out := make([]*ManifestNode, 0, g.size)
for _, idx := range g.sortedIndices() {
if manifest, ok := g.nodes[idx].(*ManifestNode); ok {
out = append(out, manifest)
}
}
return out
}
// AddEdge adds a dependency relationship fromID -> toID, meaning fromID
// depends on toID.
//
// The edge's kind is derived from the two nodes, so a caller that knows
// nothing about EdgeKind still produces correctly typed edges. Use
// AddTypedEdge to state a kind the structure does not imply.
func (g *Graph) AddEdge(fromID, toID string) error {
return g.AddTypedEdge(fromID, toID, EdgeKindUnknown)
}
// AddTypedEdge adds a relationship and states what it asserts. An unknown kind
// is derived from the nodes, which is what AddEdge passes.
//
// Adding an edge that already exists merges the kinds rather than ignoring the
// second call, so a stated kind is never lost to an earlier unstated one.
func (g *Graph) AddTypedEdge(fromID, toID string, kind EdgeKind) error {
if fromID == toID {
return ErrSelfDependency
}
fromIdx, err := g.requireIndex(fromID)
if err != nil {
return err
}
toIdx, err := g.requireIndex(toID)
if err != nil {
return err
}
if kind == EdgeKindUnknown {
kind = DeriveEdgeKind(g.nodes[fromIdx], g.nodes[toIdx])
}
if existing, ok := g.outgoing[fromIdx][toIdx]; ok {
merged := MergeEdgeKind(existing, kind)
g.outgoing[fromIdx][toIdx] = merged
g.incoming[toIdx][fromIdx] = merged
return nil
}
g.outgoing[fromIdx][toIdx] = kind
g.incoming[toIdx][fromIdx] = kind
return nil
}
// EdgeKindOf returns the kind recorded for an edge, or EdgeKindUnknown when
// there is no such edge.
func (g *Graph) EdgeKindOf(fromID, toID string) EdgeKind {
fromIdx, ok := g.indexByID[fromID]
if !ok {
return EdgeKindUnknown
}
toIdx, ok := g.indexByID[toID]
if !ok {
return EdgeKindUnknown
}
return g.outgoing[fromIdx][toIdx]
}
// WalkTypedEdges iterates every relationship with the kind it asserts.
// Returning false stops iteration.
//
// Reconstruction sites must use this, or CopyEdgesInto which is built on it,
// rather than WalkEdges: rebuilding a graph from (from, to) pairs alone drops
// every kind, and TestGraphReconstructionPreservesEdgeKind fails when it does.
func (g *Graph) WalkTypedEdges(fn func(from, to GraphNode, kind EdgeKind) bool) {
if fn == nil {
return
}
for fromIdx, relationships := range g.outgoing {
if !g.alive[fromIdx] || relationships == nil {
continue
}
for toIdx, kind := range relationships {
if !g.alive[toIdx] {
continue
}
if !fn(g.nodes[fromIdx], g.nodes[toIdx], kind) {
return
}
}
}
}
// CopyEdgesInto copies every edge of src into dst, keeping each edge's kind
// and mapping node IDs through rename. A nil rename copies IDs unchanged; a
// rename that returns "" drops the edge, which is how a filtered graph omits
// edges to nodes it did not keep.
//
// This is the one primitive for rebuilding a graph's edges. Every site that
// used to walk edges and call AddEdge -- the container merge, the JSON
// decoder, the scope filter -- is a place a new edge field would be dropped
// silently, and there were four of them. Routing them all through here means
// the next field added to an edge is carried by all four at once.
//
// An edge that becomes a self-edge after renaming is skipped, not an error:
// folding two nodes into one legitimately collapses the edge between them.
func CopyEdgesInto(dst, src *Graph, rename func(string) string) error {
if dst == nil || src == nil {
return nil
}
var err error
src.WalkTypedEdges(func(from, to GraphNode, kind EdgeKind) bool {
fromID, toID := from.NodeID(), to.NodeID()
if rename != nil {
fromID, toID = rename(fromID), rename(toID)
}
if fromID == "" || toID == "" || fromID == toID {
return true
}
if addErr := dst.AddTypedEdge(fromID, toID, kind); addErr != nil && !errors.Is(addErr, ErrSelfDependency) {
err = addErr
return false
}
return true
})
return err
}
// RemoveEdge removes a dependency relationship and reports whether it existed.
func (g *Graph) RemoveEdge(fromID, toID string) bool {
fromIdx, ok := g.indexByID[fromID]
if !ok {
return false
}
toIdx, ok := g.indexByID[toID]
if !ok {
return false
}
if _, ok = g.outgoing[fromIdx][toIdx]; !ok {
return false
}
delete(g.outgoing[fromIdx], toIdx)
delete(g.incoming[toIdx], fromIdx)
return true
}
// RemoveNode removes a node and all incident relationships.
func (g *Graph) RemoveNode(id string) bool {
idx, ok := g.indexByID[id]
if !ok {
return false
}
for depIdx := range g.outgoing[idx] {
delete(g.incoming[depIdx], idx)
}
for parentIdx := range g.incoming[idx] {
delete(g.outgoing[parentIdx], idx)
}
delete(g.indexByID, id)
g.nodes[idx] = nil
g.alive[idx] = false
g.outgoing[idx] = nil
g.incoming[idx] = nil
g.free = append(g.free, idx)
g.size--
return true
}
// DirectDependencies returns direct dependencies for a node, sorted by ID.
func (g *Graph) DirectDependencies(id string) ([]GraphNode, error) {
idx, err := g.requireIndex(id)
if err != nil {
return nil, err
}
return g.lookupSorted(g.outgoing[idx]), nil
}
// Dependents returns direct dependents for a node, sorted by ID.
func (g *Graph) Dependents(id string) ([]GraphNode, error) {
idx, err := g.requireIndex(id)
if err != nil {
return nil, err
}
return g.lookupSorted(g.incoming[idx]), nil
}
// Roots returns nodes with no incoming relationships.
func (g *Graph) Roots() []GraphNode {
out := make([]GraphNode, 0, g.size)
for _, idx := range g.sortedIndices() {
if len(g.incoming[idx]) == 0 {
out = append(out, g.nodes[idx])
}
}
return out
}
// Leaves returns nodes with no outgoing relationships.
func (g *Graph) Leaves() []GraphNode {
out := make([]GraphNode, 0, g.size)
for _, idx := range g.sortedIndices() {
if len(g.outgoing[idx]) == 0 {
out = append(out, g.nodes[idx])
}
}
return out
}
// CollectPathsTo returns deterministic root-to-target paths.
func (g *Graph) CollectPathsTo(targetID string) ([]Path, error) {
targetIdx, err := g.requireIndex(targetID)
if err != nil {
return nil, err
}
relevant := g.reverseReachable(targetIdx)
starts := g.relevantRoots(relevant)
if len(starts) == 0 {
starts = g.sortedRelevantIndices(relevant)
}
paths := make([]Path, 0)
for _, startIdx := range starts {
g.collectPathsTo(startIdx, targetIdx, relevant, nil, map[int]struct{}{}, &paths)
}
sort.Slice(paths, func(i, j int) bool {
return pathNodesKey(paths[i].Nodes) < pathNodesKey(paths[j].Nodes)
})
return paths, nil
}
// TopologicalSort returns a topological ordering for the acyclic portion of the
// graph. If cycles remain, the returned slice contains the ordered prefix and
// ErrCycleDetected.
func (g *Graph) TopologicalSort() ([]GraphNode, error) {
inDeg := make([]int, len(g.nodes))
ready := &idIndexHeap{g: g, items: make([]int, 0, g.size)}
for idx, node := range g.nodes {
if node == nil || !g.alive[idx] {
continue
}
inDeg[idx] = len(g.incoming[idx])
if inDeg[idx] == 0 {
heap.Push(ready, idx)
}
}
ordered := make([]GraphNode, 0, g.size)
for ready.Len() > 0 {
idx := heap.Pop(ready).(int)
ordered = append(ordered, g.nodes[idx])
for childIdx := range g.outgoing[idx] {
inDeg[childIdx]--
if inDeg[childIdx] == 0 {
heap.Push(ready, childIdx)
}
}
}
if len(ordered) != g.size {
return ordered, ErrCycleDetected
}
return ordered, nil
}
// Size returns the number of nodes in the graph.
func (g *Graph) Size() int {
return g.size
}
// WalkNodes iterates all live nodes. Returning false from fn stops iteration.
func (g *Graph) WalkNodes(fn func(GraphNode) bool) {
if fn == nil {
return
}
for idx, node := range g.nodes {
if node == nil || !g.alive[idx] {
continue
}
if !fn(node) {
return
}
}
}
// WalkDependencyNodes iterates all live dependency nodes. Returning false
// from fn stops iteration.
func (g *Graph) WalkDependencyNodes(fn func(*DependencyNode) bool) {
if fn == nil {
return
}
g.WalkNodes(func(node GraphNode) bool {
dep, ok := node.(*DependencyNode)
if !ok {
return true
}
return fn(dep)
})
}
// WalkEdges iterates all dependency relationships (from -> to). Returning false
// stops iteration.
func (g *Graph) WalkEdges(fn func(from, to GraphNode) bool) {
if fn == nil {
return
}
for fromIdx, relationships := range g.outgoing {
if !g.alive[fromIdx] || relationships == nil {
continue
}
for toIdx := range relationships {
if !g.alive[toIdx] {
continue
}
if !fn(g.nodes[fromIdx], g.nodes[toIdx]) {
return
}
}
}
}
// PrettyString returns a stable, human-readable adjacency list.
func (g *Graph) PrettyString() string {
if g.size == 0 {
return "(empty graph)"
}
nodes := g.Nodes()
var b strings.Builder
for i, node := range nodes {
deps, _ := g.DirectDependencies(node.NodeID())
b.WriteString(node.NodeID())
b.WriteString(" -> [")
for j, dep := range deps {
if j > 0 {
b.WriteString(", ")
}
b.WriteString(dep.NodeID())
}
b.WriteString("]")
if i < len(nodes)-1 {
b.WriteByte('\n')
}
}
return b.String()
}
// PrettyTree returns an ASCII tree view of dependencies from graph roots.
func (g *Graph) PrettyTree() string {
if g.size == 0 {
return "(empty graph)"
}
roots := g.Roots()
if len(roots) == 0 {
roots = g.Nodes()
}
expanded := make(map[int]struct{}, g.size)
var b strings.Builder
for _, root := range roots {
rootIdx := g.indexByID[root.NodeID()]
b.WriteString(nodeDisplayLabel(root))
b.WriteByte('\n')
expanded[rootIdx] = struct{}{}
onPath := map[int]struct{}{rootIdx: {}}
g.writeTree(&b, rootIdx, "", expanded, onPath)
}
return strings.TrimSuffix(b.String(), "\n")
}
// Compare returns added, removed, version-changed, and detail-changed
// dependencies between base and head. Only dependency nodes participate:
// manifest and module nodes are structural.
func Compare(base, head *Graph) Diff {
baseExact, headExact := indexDiffableNodes(base), indexDiffableNodes(head)
baseRelationships := dependencyRelationshipsForGraph(base)
headRelationships := dependencyRelationshipsForGraph(head)
baseRemainder := make(map[string]*DependencyNode)
headRemainder := make(map[string]*DependencyNode)
transitions := make([]DependencyDetailTransition, 0)
for id, node := range baseExact {
if headNode, ok := headExact[id]; ok {
if transition, changed := compareDependencyDetails(node, headNode, baseRelationships, headRelationships); changed {
transitions = append(transitions, transition)
}
continue
}
baseRemainder[id] = node
}
for id, node := range headExact {
if _, ok := baseExact[id]; ok {
continue
}
headRemainder[id] = node
}
baseByIdentity := groupNodesByIdentity(baseRemainder)
headByIdentity := groupNodesByIdentity(headRemainder)
identities := make(map[string]struct{}, mergeCapacity(len(baseByIdentity), len(headByIdentity)))
for key := range baseByIdentity {
identities[key] = struct{}{}
}
for key := range headByIdentity {
identities[key] = struct{}{}
}
diff := Diff{
Added: make([]*DependencyNode, 0),
Removed: make([]*DependencyNode, 0),
Updated: make([]VersionChange, 0),
Transitions: transitions,
}
for key := range identities {
baseNodes := baseByIdentity[key]
headNodes := headByIdentity[key]
sortNodesForDiff(baseNodes)
sortNodesForDiff(headNodes)
pairs := len(baseNodes)
if len(headNodes) < pairs {
pairs = len(headNodes)
}
for i := 0; i < pairs; i++ {
before := baseNodes[i]
after := headNodes[i]
diff.Updated = append(diff.Updated, VersionChange{Before: before, After: after})
if transition, changed := compareDependencyDetails(before, after, baseRelationships, headRelationships); changed {
diff.Transitions = append(diff.Transitions, transition)
}
}
if pairs < len(baseNodes) {
diff.Removed = append(diff.Removed, baseNodes[pairs:]...)
}
if pairs < len(headNodes) {
diff.Added = append(diff.Added, headNodes[pairs:]...)
}
}
sortNodesForDiff(diff.Added)
sortNodesForDiff(diff.Removed)
sort.Slice(diff.Updated, func(i, j int) bool {
left := diff.Updated[i]
right := diff.Updated[j]
if lk, rk := diffIdentityKey(left.Before), diffIdentityKey(right.Before); lk != rk {
return lk < rk
}
if left.Before.Version != right.Before.Version {
return left.Before.Version < right.Before.Version
}
if left.After.Version != right.After.Version {
return left.After.Version < right.After.Version
}
return left.Before.NodeID() < right.Before.NodeID()
})
SortDependencyDetailTransitions(diff.Transitions)
return diff
}
// CompareDependencyDetails returns a transition when relationship, source, or
// registry-matching eligibility differs between two dependency records. It is
// exported so trusted fuzzy identity reconciliation can use the same canonical
// classifier as Compare.
func CompareDependencyDetails(baseGraph, headGraph *Graph, before, after *DependencyNode) (DependencyDetailTransition, bool) {
return compareDependencyDetails(
before,
after,
dependencyRelationshipsForGraph(baseGraph),