From e08f3a5d0bfa468c2e9d08404cde080ccdcd7e72 Mon Sep 17 00:00:00 2001 From: Aneurin Barker Snook Date: Tue, 1 Dec 2026 19:15:55 +0000 Subject: [PATCH] Make reading a header's opcodes safe for concurrent readers indexOf wrote the node's remembered index even when it was right, so Header.Get raced when a document was read from several goroutines. Co-Authored-By: Claude Sonnet 5.5 --- edit.go | 5 ++++- robust_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/edit.go b/edit.go index 164140d..d093797 100644 --- a/edit.go +++ b/edit.go @@ -24,7 +24,10 @@ func (h *Header) Name() string { return h.Node.Name } // so the search starts there and goes outwards. func (f *File) indexOf(n *Node) int { at := func(i int) bool { return i >= 0 && i < len(f.Nodes) && f.Nodes[i] == n } - for d := 0; ; d++ { + if at(n.idx) { + return n.idx + } + for d := 1; ; d++ { if at(n.idx + d) { n.idx += d return n.idx diff --git a/robust_test.go b/robust_test.go index 09a8330..56cdcd3 100644 --- a/robust_test.go +++ b/robust_test.go @@ -6,6 +6,7 @@ import ( "io" "reflect" "strings" + "sync" "testing" "time" ) @@ -360,3 +361,27 @@ func TestEqualsInValue(t *testing.T) { } } } + +// TestConcurrentReads checks that a document that hasn't been edited can be +// read by several goroutines at once. It is run with the race detector. +func TestConcurrentReads(t *testing.T) { + doc := mustParse(t, "#define $A 1\n volume=-3\n sample=a.wav lokey=c4\n sample=b.wav\n", nil) + var wg sync.WaitGroup + for i := 0; i < 8; i++ { + wg.Add(1) + go func() { + defer wg.Done() + doc.Validate() + inst := doc.Flatten().Instrument() + _ = doc.String() + for _, h := range doc.Headers() { + h.Get("sample") + h.Opcodes() + } + if _, err := inst.Patches(0, inst.Regions[0]); err != nil { + t.Error(err) + } + }() + } + wg.Wait() +}