Skip to content

Commit 253d197

Browse files
committed
Give every board object a stable identity, even without a native UUID/tstamp
1 parent 00c0b79 commit 253d197

10 files changed

Lines changed: 530 additions & 105 deletions

File tree

‎backend/internal/kicad/index.go‎

Lines changed: 114 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package kicad
22

3-
import "strings"
3+
import (
4+
"strconv"
5+
"strings"
6+
)
47

58
// Index maps a footprint's UUID (the wire identity -- see
69
// docs/architecture/session-and-protocol.md's "The object model: UUID is
@@ -10,26 +13,113 @@ import "strings"
1013
// legal).
1114
type Index map[string]Node
1215

13-
// BuildIndex walks root (a parsed kicad_pcb list) and indexes every
14-
// footprint by its identity value. Built once during ingest so mutation
15-
// lookup is O(1); ref is never used as a key, since reference designators
16-
// are not unique (REF**, duplicates are legal). Footprint-only: Phase 1's
17-
// MOVE/ROTATE/FLIP are only ever valid against a footprint, and existing
18-
// code (e.g. Flip's own corpus tests) assumes every entry in this index is
19-
// one. Phase 2's broader object lifecycle protocol (see
20-
// docs/architecture/session-and-protocol.md), which
21-
// needs to reach segment/via/etc. by UUID too, uses BuildFullIndex instead.
22-
func BuildIndex(root Node) Index {
23-
idx := make(Index)
16+
// topLevelPathPrefix marks a synthetic, position-derived identity (see
17+
// ResolveTopLevelIdentities) so it can never collide with a real
18+
// (uuid ...)/(tstamp ...) string, which never contains a NUL byte.
19+
const topLevelPathPrefix = "\x00path:"
20+
21+
// topLevelPathIdentity is the derived-path fallback for a root-level node
22+
// with no usable native identity: its 0-based ordinal position among ALL
23+
// of root's direct children (not just kind-matching ones, so the same
24+
// position means the same thing regardless of which caller -- BuildIndex,
25+
// BuildFullIndex, BuildSchematicIndex, internal/view -- is asking).
26+
func topLevelPathIdentity(pos int) string {
27+
return topLevelPathPrefix + strconv.Itoa(pos)
28+
}
29+
30+
// ResolveTopLevelIdentities computes, in one pass over root's direct
31+
// children, the final identity string for every child keep accepts --
32+
// the shared rule BuildIndex, BuildFullIndex and BuildSchematicIndex all
33+
// apply, and the one internal/view must also apply when it shows/sends a
34+
// node's id externally, so a value shown to a client and a value looked up
35+
// server-side always agree.
36+
//
37+
// The rule: a node's own (uuid ...)/(tstamp ...) value when it is present
38+
// AND unique among ALL of root's children (not merely unique among
39+
// keep-matching ones -- a real uuid is meant to be globally unique, not
40+
// unique-per-kind) -- otherwise a synthetic topLevelPathIdentity fallback.
41+
//
42+
// The fallback covers two real, corpus-confirmed cases, not one:
43+
//
44+
// - No native identity at all. docs/architecture.md Part III §3.3:
45+
// filmscanner.kicad_pcb (real, MIT-licensed, on the write allowlist)
46+
// has real footprint and gr_text nodes with neither field. Previously
47+
// these were silently omitted from every Index -- untargetable by
48+
// MOVE_COMPONENT/DELETE_OBJECT/EDIT_OBJECT and invisible to
49+
// internal/view -- not merely unresolvable by a stale key.
50+
// - A native identity that collides with a sibling's.
51+
// blemoisture.kicad_pcb (real, pre-KiCad-6 `(version 20160815)`
52+
// export) has three separate real (zone ...) nodes sharing the
53+
// literal legacy placeholder (tstamp 0) -- a real identity collision
54+
// in the wild, not synthetic test data; KiCad 6 introduced per-object
55+
// UUIDs specifically because this class of bug was possible in the
56+
// older tstamp scheme. Keying on "0" as-is would silently alias all
57+
// three to one Index slot (whichever was walked last); each now gets
58+
// its own derived key instead.
59+
//
60+
// Position is stable for the life of a parsed Document: root's children
61+
// are only ever appended to, never reordered or spliced
62+
// (docs/architecture.md §3.5), and a faithful structural copy
63+
// (kicad.Document.CopyFrom, used to snapshot overlay.Base -- see
64+
// internal/session/overlay_base.go) preserves child order for the same
65+
// underlying reason byte-exact serialization requires it to. So this key
66+
// means the same thing computed against either document, for any node
67+
// present in both -- the property internal/session/overlay_base.go's
68+
// baseSnapshot depends on for every OTHER node kind already.
69+
//
70+
// Returns both directions: byIdentity for BuildIndex-family callers
71+
// (string -> Node, the shape Index already is), byNode for callers like
72+
// internal/view that hold a Node and need to show/send its id (Node is a
73+
// small comparable value -- a document pointer and an arena index -- so
74+
// it's a valid map key).
75+
func ResolveTopLevelIdentities(root Node, keep func(Node) bool) (byIdentity map[string]Node, byNode map[Node]string) {
76+
type entry struct {
77+
node Node
78+
native string
79+
}
80+
var all []entry
81+
counts := map[string]int{}
2482
for c := range root.Children() {
25-
if c.Kind() != KindList || c.Head() != "footprint" {
83+
native := ""
84+
if c.Kind() == KindList {
85+
native = NodeIdentity(c)
86+
}
87+
if native != "" {
88+
counts[native]++
89+
}
90+
all = append(all, entry{node: c, native: native})
91+
}
92+
byIdentity = make(map[string]Node)
93+
byNode = make(map[Node]string)
94+
for pos, e := range all {
95+
if !keep(e.node) {
2696
continue
2797
}
28-
if id := NodeIdentity(c); id != "" {
29-
idx[id] = c
98+
id := e.native
99+
if id == "" || counts[id] > 1 {
100+
id = topLevelPathIdentity(pos)
30101
}
102+
byIdentity[id] = e.node
103+
byNode[e.node] = id
31104
}
32-
return idx
105+
return byIdentity, byNode
106+
}
107+
108+
// BuildIndex walks root (a parsed kicad_pcb list) and indexes every
109+
// footprint by its identity value (see ResolveTopLevelIdentities for the
110+
// native-value-or-derived-path rule). Built once during ingest so
111+
// mutation lookup is O(1); ref is never used as a key, since reference
112+
// designators are not unique (REF**, duplicates are legal). Footprint-only:
113+
// Phase 1's MOVE/ROTATE/FLIP are only ever valid against a footprint, and
114+
// existing code (e.g. Flip's own corpus tests) assumes every entry in this
115+
// index is one. Phase 2's broader object lifecycle protocol (see
116+
// docs/architecture/session-and-protocol.md), which
117+
// needs to reach segment/via/etc. by UUID too, uses BuildFullIndex instead.
118+
func BuildIndex(root Node) Index {
119+
byIdentity, _ := ResolveTopLevelIdentities(root, func(n Node) bool {
120+
return n.Kind() == KindList && n.Head() == "footprint"
121+
})
122+
return Index(byIdentity)
33123
}
34124

35125
// fullyIndexedTopLevelKinds are the top-level node types Phase 2's object
@@ -62,16 +152,10 @@ var fullyIndexedTopLevelKinds = map[string]bool{
62152
// (at ...) node too, so without that check a MOVE_COMPONENT sent against a
63153
// via's UUID would silently succeed at the wrong semantic).
64154
func BuildFullIndex(root Node) Index {
65-
idx := make(Index)
66-
for c := range root.Children() {
67-
if c.Kind() != KindList || !fullyIndexedTopLevelKinds[c.Head()] {
68-
continue
69-
}
70-
if id := NodeIdentity(c); id != "" {
71-
idx[id] = c
72-
}
73-
}
74-
return idx
155+
byIdentity, _ := ResolveTopLevelIdentities(root, func(n Node) bool {
156+
return n.Kind() == KindList && fullyIndexedTopLevelKinds[n.Head()]
157+
})
158+
return Index(byIdentity)
75159
}
76160

77161
// schematicIndexedTopLevelKinds are the top-level node types Phase 3's
@@ -99,16 +183,10 @@ var schematicIndexedTopLevelKinds = map[string]bool{
99183
// indexes every top-level node schsession.Session can create/delete/edit
100184
// by its identity value.
101185
func BuildSchematicIndex(root Node) Index {
102-
idx := make(Index)
103-
for c := range root.Children() {
104-
if c.Kind() != KindList || !schematicIndexedTopLevelKinds[c.Head()] {
105-
continue
106-
}
107-
if id := NodeIdentity(c); id != "" {
108-
idx[id] = c
109-
}
110-
}
111-
return idx
186+
byIdentity, _ := ResolveTopLevelIdentities(root, func(n Node) bool {
187+
return n.Kind() == KindList && schematicIndexedTopLevelKinds[n.Head()]
188+
})
189+
return Index(byIdentity)
112190
}
113191

114192
// NodeIdentity returns a top-level node's identity value (its (uuid ...) or

‎backend/internal/kicad/index_test.go‎

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"context"
55
"os"
66
"path/filepath"
7+
"strings"
78
"testing"
89
)
910

@@ -106,3 +107,132 @@ func TestFootprintLockedRealCorpus(t *testing.T) {
106107
}
107108
}
108109
}
110+
111+
// TestBuildFullIndexDerivedPathForMissingIdentity is the regression test
112+
// for docs/architecture.md Part III §3.3's previously-open question:
113+
// filmscanner.kicad_pcb (real, MIT-licensed, testdata/boards/SOURCES.md)
114+
// has real footprint and gr_text nodes with neither (uuid ...) nor
115+
// (tstamp ...). Before ResolveTopLevelIdentities's derived-path fallback,
116+
// BuildFullIndex silently omitted these nodes entirely -- untargetable by
117+
// MOVE_COMPONENT/DELETE_OBJECT/EDIT_OBJECT. Every one of them must now be
118+
// present in the index under some key.
119+
func TestBuildFullIndexDerivedPathForMissingIdentity(t *testing.T) {
120+
src, err := os.ReadFile(filepath.Join("../../testdata/boards", "filmscanner.kicad_pcb"))
121+
if err != nil {
122+
t.Skipf("corpus file not present: %v", err)
123+
}
124+
doc, err := ParseAsPCB(context.Background(), string(src))
125+
if err != nil {
126+
t.Fatal(err)
127+
}
128+
root := doc.Root()
129+
130+
var candidates []Node
131+
for c := range root.Children() {
132+
if c.Kind() != KindList {
133+
continue
134+
}
135+
switch c.Head() {
136+
case "footprint", "gr_text":
137+
candidates = append(candidates, c)
138+
}
139+
}
140+
if len(candidates) == 0 {
141+
t.Fatal("filmscanner.kicad_pcb has no footprint/gr_text nodes -- test found nothing to check")
142+
}
143+
144+
idx := BuildFullIndex(root)
145+
_, byNode := ResolveTopLevelIdentities(root, func(n Node) bool {
146+
return n.Kind() == KindList && fullyIndexedTopLevelKinds[n.Head()]
147+
})
148+
149+
seen := map[string]bool{}
150+
for _, c := range candidates {
151+
if NodeIdentity(c) != "" {
152+
t.Fatalf("test fixture assumption broken: a %q node in filmscanner.kicad_pcb now has a native identity", c.Head())
153+
}
154+
id, ok := byNode[c]
155+
if !ok || id == "" {
156+
t.Errorf("a real %q node with no native identity got no derived-path fallback", c.Head())
157+
continue
158+
}
159+
if !strings.HasPrefix(id, topLevelPathPrefix) {
160+
t.Errorf("derived id %q for a no-identity %q node doesn't carry the sentinel prefix", id, c.Head())
161+
}
162+
if seen[id] {
163+
t.Errorf("derived id %q assigned to more than one node", id)
164+
}
165+
seen[id] = true
166+
if got, ok := idx[id]; !ok || got != c {
167+
t.Errorf("BuildFullIndex[%q] does not resolve back to the node ResolveTopLevelIdentities assigned it", id)
168+
}
169+
}
170+
}
171+
172+
// TestBuildFullIndexDerivedPathForAmbiguousIdentity is the regression test
173+
// for a second, distinct real-world identity gap: blemoisture.kicad_pcb
174+
// (real, pre-KiCad-6 `(version 20160815)` export, testdata/boards/
175+
// SOURCES.md) has three separate real (zone ...) nodes sharing the
176+
// literal legacy placeholder (tstamp 0) -- a genuine identity collision,
177+
// not synthetic. Before the fallback, BuildFullIndex silently aliased all
178+
// three to whichever was walked last; now every zone in the file
179+
// (colliding or not) must resolve to its own distinct index entry.
180+
func TestBuildFullIndexDerivedPathForAmbiguousIdentity(t *testing.T) {
181+
src, err := os.ReadFile(filepath.Join("../../testdata/boards", "blemoisture.kicad_pcb"))
182+
if err != nil {
183+
t.Skipf("corpus file not present: %v", err)
184+
}
185+
doc, err := ParseAsPCB(context.Background(), string(src))
186+
if err != nil {
187+
t.Fatal(err)
188+
}
189+
root := doc.Root()
190+
191+
var zones []Node
192+
nativeCounts := map[string]int{}
193+
for c := range root.Children() {
194+
if c.Kind() != KindList || c.Head() != "zone" {
195+
continue
196+
}
197+
zones = append(zones, c)
198+
if id := NodeIdentity(c); id != "" {
199+
nativeCounts[id]++
200+
}
201+
}
202+
if len(zones) < 2 {
203+
t.Fatal("blemoisture.kicad_pcb doesn't have enough zone nodes to check a collision -- test found nothing")
204+
}
205+
hasCollision := false
206+
for _, n := range nativeCounts {
207+
if n > 1 {
208+
hasCollision = true
209+
}
210+
}
211+
if !hasCollision {
212+
t.Fatal("test fixture assumption broken: expected a real tstamp collision among blemoisture.kicad_pcb's zones, found none")
213+
}
214+
215+
idx := BuildFullIndex(root)
216+
_, byNode := ResolveTopLevelIdentities(root, func(n Node) bool {
217+
return n.Kind() == KindList && fullyIndexedTopLevelKinds[n.Head()]
218+
})
219+
220+
seen := map[string]bool{}
221+
for _, z := range zones {
222+
id, ok := byNode[z]
223+
if !ok || id == "" {
224+
t.Errorf("a real zone node got no resolved identity at all")
225+
continue
226+
}
227+
if seen[id] {
228+
t.Errorf("two distinct zone nodes resolved to the same identity %q -- the collision this test exists to catch", id)
229+
}
230+
seen[id] = true
231+
if got, ok := idx[id]; !ok || got != z {
232+
t.Errorf("BuildFullIndex[%q] does not resolve back to the zone ResolveTopLevelIdentities assigned it", id)
233+
}
234+
}
235+
if len(seen) != len(zones) {
236+
t.Errorf("got %d distinct resolved identities for %d real zone nodes", len(seen), len(zones))
237+
}
238+
}

‎backend/internal/overlay/doc.go‎

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -39,12 +39,17 @@
3939
// real, currently-supported board carries a native (uuid ...)/
4040
// (tstamp ...) identity. filmscanner.kicad_pcb (real, MIT-licensed,
4141
// version 20221018 -- on the write allowlist) has real footprint and
42-
// gr_text nodes with neither field. NodeIdentity has no derived-path
43-
// fallback for this case (the architecture doc's own anticipated "child-
44-
// index chain from root" option) -- this package cannot yet target such a
45-
// node at all, and neither can the already-shipped
46-
// MOVE_COMPONENT/DELETE_OBJECT/EDIT_OBJECT (kicad.BuildFullIndex simply
47-
// omits it). A real, pre-existing gap, not one this package introduces;
48-
// flagged as necessary follow-up scope for whoever builds Track 4.2 or
49-
// touches this corner of Phase 1/2, not solved here.
42+
// gr_text nodes with neither field; blemoisture.kicad_pcb (real,
43+
// pre-KiCad-6) has three real zone nodes sharing one colliding legacy
44+
// tstamp value. **Resolved**: kicad.ResolveTopLevelIdentities implements
45+
// the architecture doc's own anticipated "child-index chain from root"
46+
// fallback -- a node's ordinal position among root's children when its
47+
// native value is empty or shared with a sibling -- and
48+
// BuildIndex/BuildFullIndex/BuildSchematicIndex all use it now. This
49+
// package's own Serialize is unaffected: it never targets these nodes by
50+
// identity in the first place (see writeNode's use of kicad.NodeIdentity
51+
// directly), and internal/session/overlay_base.go's ambiguity check
52+
// (findAmbiguousIdentities) now treats "no native identity" the same
53+
// safe way it already treated a real collision -- rebase rather than
54+
// trust a shared/absent key.
5055
package overlay

0 commit comments

Comments
 (0)