carlos / platform Public

host: a wake's build-state record goes on the copy it last wrote (one round trip)

beforeExec's record was a GET and a conditional PUT on every wake, about
134 ms of a dev wake's exec gate. write's first try now goes on the copy
this agent last put at that key, conditioned on that copy's etag: the
PUT lands only on the very object the merge saw, so the merge decides
exactly what it would on a fresh read. A conflict, an error, or a merge
that refuses or has nothing to write on the copy is decided again on a
fresh read as before; the copy's try is extra, so the fresh reads keep all
their retries. An object that does not parse is still never written over.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev e709b4b2fc9877496c3c9c36498343229aaa9c5d parent a5f0509
2 files changed, +213 −9
  • internal/host/buildstate.go +87 −9
  • internal/host/buildstate_cas_test.go +126 −0
diff --git a/internal/host/buildstate.go b/internal/host/buildstate.go
index eab6ea3ea..a6676123f 100644
--- a/internal/host/buildstate.go
+++ b/internal/host/buildstate.go
@@ -59,6 +59,9 @@ type buildStates struct {
// resume is the first host the last refreshAll did not reach; the next
// one starts there (ruling R-REFRESH-ROTATE). Guarded by mu.
resume string
+ // written is each object write last put, by bucket and key, for the
+ // next write's conditional first try (writtenCopy). Guarded by mu.
+ written map[string]writtenCopy
}
// newBuildStates is nil, nil on a box with no replica bucket: it runs no
@@ -133,16 +136,23 @@ func cachedStores(regions map[string]string, open func(ctx context.Context, buck
// holder's Location in the claim bucket (an unreadable claim is an error,
// never the hibernate prefix); otherwise the hibernate bucket and prefix.
func (b *buildStates) locate(ctx context.Context, host string) (release.Store, string, error) {
+ _, s, prefix, err := b.locateIn(ctx, host)
+ return s, prefix, err
+}
+
+// locateIn is locate with the bucket it chose, which keys write's copy of
+// the object it last wrote.
+func (b *buildStates) locateIn(ctx context.Context, host string) (string, release.Store, string, error) {
bucket, prefix := b.hibBucket, ""
if l, ok := activator.BuildStateLocationFrom(ctx); ok {
bucket, prefix = l.Bucket, l.Prefix
} else if b.claims != nil {
obs, err := b.claims(ctx, host)
if err != nil {
- return nil, "", fmt.Errorf("read claim: %w", err)
+ return "", nil, "", fmt.Errorf("read claim: %w", err)
}
if obs.Absent || obs.Claim == nil || obs.Claim.Holder == nil || obs.Claim.Holder.Location == "" {
- return nil, "", fmt.Errorf("claim of %s has no holder location", host)
+ return "", nil, "", fmt.Errorf("claim of %s has no holder location", host)
}
bucket, prefix = b.claimBucket, obs.Claim.Holder.Location
} else {
@@ -151,9 +161,9 @@ func (b *buildStates) locate(ctx context.Context, host string) (release.Store, s
prefix = strings.TrimSuffix(prefix, "/")
s, err := b.storeFor(ctx, bucket)
if err != nil {
- return nil, "", err
+ return "", nil, "", err
}
- return s, prefix, nil
+ return bucket, s, prefix, nil
}
func (b *buildStates) hostLock(host string) *sync.Mutex {
@@ -452,17 +462,38 @@ func (b *buildStates) write(ctx context.Context, host string, merge func(cur *re
m := b.hostLock(host)
m.Lock()
defer m.Unlock()
- store, prefix, err := b.locate(ctx, host)
+ bucket, store, prefix, err := b.locateIn(ctx, host)
if err != nil {
return release.BuildState{}, err
}
key := release.BuildStateKey(prefix)
- for try := 0; try < updateTries; try++ {
- cur, etag, err := getState(ctx, store, key, host)
- if err != nil {
+ // The first try goes on the copy this agent last wrote, when it has
+ // one: a wake's record is then one conditional write, not a read and a
+ // write. The condition is that copy's etag, so the write lands only on
+ // the very object the merge saw, and the merge decides exactly what it
+ // would on a fresh read. Anything else (the object moved on, the merge
+ // refused or had nothing to write on a copy that may be stale) is
+ // decided again on a fresh read, as before.
+ cached, hasCopy := b.lastWritten(bucket, key)
+ tries := updateTries
+ if hasCopy {
+ tries++ // the copy's try is extra: the fresh reads keep all theirs
+ }
+ for try := 0; try < tries; try++ {
+ var (
+ cur *release.BuildState
+ etag string
+ )
+ fromCopy := hasCopy && try == 0
+ if fromCopy {
+ cur, etag = cached.state(), cached.etag
+ } else if cur, etag, err = getState(ctx, store, key, host); err != nil {
return release.BuildState{}, err
}
next, put, err := merge(cur)
+ if fromCopy && (err != nil || !put) {
+ continue
+ }
if err != nil {
return release.BuildState{}, err
}
@@ -481,11 +512,15 @@ func (b *buildStates) write(ctx context.Context, host string, merge func(cur *re
if b.beforePut != nil {
b.beforePut(ctx, store, key)
}
- if _, err := store.Put(ctx, key, raw, etag); errors.Is(err, release.ErrCASConflict) {
+ newEtag, err := store.Put(ctx, key, raw, etag)
+ if errors.Is(err, release.ErrCASConflict) {
+ b.forget(bucket, key)
continue
} else if err != nil {
+ b.forget(bucket, key)
return release.BuildState{}, err
}
+ b.remember(bucket, key, raw, newEtag)
// A process about to run against the database has (or is about to
// have) a replica; any other writer says.
hasRep := true
@@ -503,6 +538,49 @@ func (b *buildStates) write(ctx context.Context, host string, merge func(cur *re
return release.BuildState{}, fmt.Errorf("build state of %s: %d tries lost the race: %w", host, updateTries, release.ErrCASConflict)
}
+// writtenCopy is the object write last put at a key, and the etag that
+// write returned: the state the next write's conditional first try goes on.
+type writtenCopy struct {
+ raw []byte
+ etag string
+}
+
+// state decodes a fresh copy each time, so a merge can never change the
+// cached bytes.
+func (c writtenCopy) state() *release.BuildState {
+ var s release.BuildState
+ if json.Unmarshal(c.raw, &s) != nil {
+ return nil
+ }
+ return &s
+}
+
+func (b *buildStates) lastWritten(bucket, key string) (writtenCopy, bool) {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ c, ok := b.written[bucket+"\x00"+key]
+ return c, ok && c.etag != "" && c.state() != nil
+}
+
+func (b *buildStates) remember(bucket, key string, raw []byte, etag string) {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ if etag == "" {
+ delete(b.written, bucket+"\x00"+key)
+ return
+ }
+ if b.written == nil {
+ b.written = map[string]writtenCopy{}
+ }
+ b.written[bucket+"\x00"+key] = writtenCopy{raw: append([]byte(nil), raw...), etag: etag}
+}
+
+func (b *buildStates) forget(bucket, key string) {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ delete(b.written, bucket+"\x00"+key)
+}
+
// beforeExec is Service.BeforeExec (settings spec §4.2): before build runs
// against host's database, under its lease, the object names build as
// last_executed, carries root's resolution from the consumed file, and
diff --git a/internal/host/buildstate_cas_test.go b/internal/host/buildstate_cas_test.go
new file mode 100644
index 000000000..63961f410
--- /dev/null
+++ b/internal/host/buildstate_cas_test.go
@@ -0,0 +1,126 @@
+package host
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// bsGetCounter counts reads, so a test can see a write that needed none.
+type bsGetCounter struct {
+ release.Store
+ gets int
+}
+
+func (c *bsGetCounter) Get(ctx context.Context, key string) ([]byte, string, error) {
+ c.gets++
+ return c.Store.Get(ctx, key)
+}
+
+func countingBuildStates(t *testing.T) (*buildStates, *bsGetCounter) {
+ t.Helper()
+ b, s, _ := testBuildStates(t)
+ cs := &bsGetCounter{Store: s}
+ b.storeFor = storesOf(map[string]release.Store{"hib": cs})
+ return b, cs
+}
+
+// The state this agent last wrote is the one a conditional write can go
+// on: a wake's record is then one round trip, not a read and a write.
+func TestBuildStateWritesOnItsOwnLastCopyWithoutARead(t *testing.T) {
+ b, cs := countingBuildStates(t)
+ ctx := context.Background()
+ if err := put(t, b, ctx, "a.example.com", release.BuildState{LastExecuted: "v1", Completed: 1}); err != nil {
+ t.Fatal(err)
+ }
+ cs.gets = 0
+ got, err := b.update(ctx, "a.example.com", bump)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if cs.gets != 0 {
+ t.Errorf("the write read the object %d time(s); its own last copy was current", cs.gets)
+ }
+ if got.Completed != 2 || got.LastExecuted != "v1" {
+ t.Errorf("state = %+v, want the cached copy bumped", got)
+ }
+ cur, _, err := getState(ctx, cs.Store, "inst/a.example.com/build-state.json", "a.example.com")
+ if err != nil || cur == nil || cur.Completed != 2 {
+ t.Fatalf("object = %+v, %v", cur, err)
+ }
+}
+
+// Another writer moved the object on: the conditional write fails, and the
+// write reads it and merges on what is really there.
+func TestBuildStateCopyThatMovedOnIsReadAgain(t *testing.T) {
+ b, cs := countingBuildStates(t)
+ ctx := context.Background()
+ if err := put(t, b, ctx, "a.example.com", release.BuildState{LastExecuted: "v1", Completed: 1}); err != nil {
+ t.Fatal(err)
+ }
+ key := "inst/a.example.com/build-state.json"
+ if _, err := cs.Store.Put(ctx, key, []byte(`{"schema":1,"host":"a.example.com","last_executed":"v9","completed":5}`), mustEtag(t, cs.Store, key)); err != nil {
+ t.Fatal(err)
+ }
+ cs.gets = 0
+ got, err := b.update(ctx, "a.example.com", bump)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if cs.gets == 0 {
+ t.Error("the write did not read an object that had moved on")
+ }
+ if got.Completed != 6 || got.LastExecuted != "v9" {
+ t.Errorf("state = %+v, want the other writer's state bumped", got)
+ }
+}
+
+// A merge that refuses on the cached copy is asked again on a fresh read:
+// the copy may be stale, and a refusal on stale state would be wrong.
+func TestBuildStateRefusalOnTheCachedCopyIsCheckedAgainstAFreshRead(t *testing.T) {
+ b, cs := countingBuildStates(t)
+ ctx := context.Background()
+ if err := put(t, b, ctx, "a.example.com", release.BuildState{LastExecuted: "v1", Completed: 1}); err != nil {
+ t.Fatal(err)
+ }
+ key := "inst/a.example.com/build-state.json"
+ if _, err := cs.Store.Put(ctx, key, []byte(`{"schema":1,"host":"a.example.com","last_executed":"v1","completed":2}`), mustEtag(t, cs.Store, key)); err != nil {
+ t.Fatal(err)
+ }
+ errStale := errors.New("stale")
+ got, err := b.write(ctx, "a.example.com", func(cur *release.BuildState) (release.BuildState, bool, error) {
+ if cur != nil && cur.Completed == 1 {
+ return release.BuildState{}, false, errStale
+ }
+ return *cur, true, nil
+ }, nil)
+ if err != nil {
+ t.Fatalf("write = %v; the refusal came from the cached copy, not the object", err)
+ }
+ if got.Completed != 2 {
+ t.Errorf("state = %+v", got)
+ }
+}
+
+// An object that no longer parses is never written over (R-BS-CORRUPT),
+// cached copy or not: the conditional write fails and the read refuses.
+func TestBuildStateCachedCopyNeverWritesOverACorruptObject(t *testing.T) {
+ b, cs := countingBuildStates(t)
+ ctx := context.Background()
+ if err := put(t, b, ctx, "a.example.com", release.BuildState{LastExecuted: "v1"}); err != nil {
+ t.Fatal(err)
+ }
+ key := "inst/a.example.com/build-state.json"
+ if _, err := cs.Store.Put(ctx, key, []byte("{"), mustEtag(t, cs.Store, key)); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := b.update(ctx, "a.example.com", bump); err == nil {
+ t.Fatal("wrote over an object that does not parse")
+ }
+ raw, _, err := cs.Store.Get(ctx, key)
+ if err != nil || string(raw) != "{" {
+ t.Fatalf("object = %q, %v", raw, err)
+ }
+}