The despatch service
built one list
of labels every parcel needed.
Read from config,
one append at a time.
Then, for each parcel,
it added that parcel's own label.
var common []string
for _, l := range cfg.Labels {
common = append(common, l)
}
for i := range parcels {
parcels[i].Labels = append(common, parcels[i].Extra)
}
For two years
the config had two labels.
Fragile. This way up.
Then someone added a third.
Keep dry.
The next morning
every parcel in the batch
carried the same extra label.
The one meant
for the last parcel.
Here is the mechanism.
A Go slice
is a small header:
a pointer to an array,
a length,
a capacity.
append writes
into the spare capacity
if there is any.
It only copies
to a new array
when there is no room.
Built one append at a time,
the array behind common
grew to 1, then 2, then 4.
Two labels,
capacity two.
No room,
so every append
made a fresh copy.
The bug was there.
It just could not fire.
Three labels,
capacity four.
One free slot.
So every parcel's append
wrote its label
into the same slot
of the same array.
Every parcel's slice
pointed at it.
The last write won,
for all of them.
No error.
No race detector warning.
The tests
used the two label config.
The fix is to stop sharing
the array:
parcels[i].Labels = append(slices.Clone(common), parcels[i].Extra)
slices.Clone
has been in the standard library
since Go 1.21.
Or cap the shared slice
so append must copy:
shared := common[:len(common):len(common)]
That third number
sets the capacity
equal to the length.
And add a test
that builds two results
from the same base
and checks
that they differ.
append can hand you back
the same memory
you gave it.
Whether it does
depends on room
you never see
in the code.
– Serguey Asael Shinder