* Add issueops.MetadataCAS: compare-and-set over one metadata key
The one coordination primitive missing at every layer. Everything the
metadata plane holds is written through Lifecycle.Update, which has no way
to say "only if", so every caller that needs a guarded write composes a
transaction, a read and an update by hand — and each one has to get the
composition right. Gas City emulates it client-side with RunInTransaction +
GetIssue + UpdateIssue for exactly that reason, and the comment it left
behind names the gap: "the upstream storage layer exposes no
conditional-UPDATE ... WHERE primitive".
The role is a state transition stated as a pair. Expected is the key's value
before, Value is its value after, and nil on either side means the key is
ABSENT there: a conditional create is (nil -> value), a conditional delete
is (value -> nil), and a caller that can take a lease can return it to the
state its own acquire tests for. Equality is canonical, so a caller cannot
lose a swap to its own formatter; numbers compare as their source literal,
because decoding through float64 equates two int64s past 2^53 and that is
the silent false match a compare-and-set exists to prevent.
A MISMATCH IS AN ANSWER, not an error: Swapped false, Current carrying the
value that refused it, nil error. That is the one place this diverges from
PROPOSAL-cas-conditional-update.md, which specifies a typed error and a loud
non-zero exit for the assignee/status guards. Its argument is a CLI one — a
swallowed refusal in a shell script is the bug class it was written for —
and a non-zero exit is the front door's enforcement, which the HTTP handler
here still owes and pays. The role's designed caller is a retry loop, for
which a lost race is the ordinary path, and an error cannot hand back
Current without a bespoke type every caller must errors.As before it can
read the one field it needs.
All three legs share one body (internal/storage/issueops), so this is one
reading plus two wrapper checks rather than three backends agreeing. The
wrapper check earned its keep: the unit-of-work leg rolled an ephemeral swap
back, because the shared body reported "no durable tables changed" and that
leg's commit message is what commits the SQL transaction as well as what
versions it. MetadataCASWrite now carries the two facts separately.
The HTTP half lands with the role per the 2026-08-05 scope decision:
POST /v0/beads/issues/{id}:casMetadata, spec first. A lost race is a 200
carrying swapped:false, so the operation has no conflict code; an omitted
`expected`/`value` member means absent and a member holding null is a value,
which is why the handler reads raw members.
No bd command yet: the primary consumer is an embedder, and a CLI front door
is additive. No .golangci.yml entry, for the reason memoryops gives — the
body is an …InTx function no front door can reach.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Review: read Current from the row, and let a client read a present null
Two shape fixes, both of which would have been expensive to change after
anyone depended on them.
A *json.RawMessage wire member cannot READ a present null: encoding/json
nils the pointer before UnmarshalJSON runs, so a generated client decoding
{"swapped":false,"current":null} gets the same value it gets for an omitted
member — and on this operation those mean opposite things. A retry loop
against a null-valued key would read "absent", swap with expected omitted,
mismatch, and livelock on a stream of 200s. x-go-type-skip-optional-pointer
makes the member a bare json.RawMessage, which is an Unmarshaler and
receives the literal; the wire is unchanged in both directions, which is
exactly why nothing else catches the regression, so the decode is now
pinned. nullable: true beside it, for the validating gateway in front of
somebody's server.
The number rule was defended in three places as protecting int64s past 2^53
from a float64 round-trip. It protects nothing: the metadata column decodes
through float64 itself — measured, 9007199254740993 stores as ...992, 1.0 as
1, -0.0 as 0, 1e300 as three hundred and one digits. The false justification
is gone from all three sites and replaced with what the probe actually
showed, plus the guidance it implies: compose an Expected from a previous
Current, and prefer a string for a coordination token.
That guidance was not true yet, because Current was the REQUEST's bytes
rather than the row's — so "what you get is what a later read sees" was
false, and a loop feeding Current back compared its own spelling against the
substrate's forever. Current is now re-read inside the deciding transaction
on every path. One extra SELECT, one statable invariant.
Three contract cases, each watched to fail: Current is the column's bytes
and a Current-driven loop converges (mutant: answer from the plan);
the history entry names the request's actor, counted per actor because
created_at is second-granularity and an ORDER BY decided this case on a coin
toss when it was first written (mutant: stamp a constant); a wisp swap
writes no durable event row, which two layers had been holding by
coincidence with nothing asserting either.
Also: the serializer-omits-null footgun in the spec (an absent `value` is a
DELETE, and Jackson/Pydantic/omitempty all omit nulls by default),
canonicalizeForContract's own float64 blind spot named in the coverage
paragraph, and the leaf now says corrupt stored metadata is an untyped error
— a 500 — because the request was well formed and the issue exists.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Close the three capability holes CI found, and one my sweep could not
All three are the same shape: a surface that loses the new role silently,
and none of them is reachable from the package tests I ran locally.
internal/storage/uow's notifying wrapper is the important one. Its
recordingIssueUC inherited CompareAndSetMetadataKey from the embedded use
case, so a swap through a notifying unit of work recorded nothing and the
hook the DoltStorage chain fires for the same write was lost. Its
notifyingProvider did not answer MetadataCAS at all, so a caller's type
assertion simply stopped matching and the wrapper dropped the capability
along with its hooks. Both are now declared, and the recorder reads the
use case's own "a row write landed" rather than inferring it from the
request — which is strictly better than what the hook decorator can do, and
snapshots anyPlane because this role resolves a wisp id itself.
cmd/bd's serveIdentityStore is the second stub store to nil-panic on the
promoted accessor, after serveRolesStore in the same commit. And
serve_proxied_integration_test.go carries a SECOND hardcoded capabilities
golden, whose own comment says two literals that must match are one literal
— it was right, and it was still missed.
My local sweep ran the metadata-cas contract on all three legs but not the
whole internal/storage/uow package, which takes nine minutes; that is where
the parity guards live. Ran it whole this time.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs: name the step with no number — the surfaces that EMBED
A new accessor arrives on every embedder promoted rather than declared, so
the build stays green and the first symptom is a nil dereference in somebody
else's stub. Four such places caught this role after its own slice was
green: RoleFiresHooks, both halves of uow's notifying wrapper, and two
cmd/bd stub stores. Grep for the embed, not for the interface — and run
internal/storage/uow whole, because the parity guards live there and the
package takes nine minutes.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Review Sim <ci@beads.test>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
178 lines
7.2 KiB
Go
178 lines
7.2 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
|
|
"github.com/steveyegge/beads/internal/httpapi/apigen"
|
|
"github.com/steveyegge/beads/internal/storage"
|
|
"github.com/steveyegge/beads/issueops"
|
|
)
|
|
|
|
// metadataCASRequestMembers is the document's member list for
|
|
// CompareAndSetMetadataRequest, read as raw members for the reason
|
|
// closeRequestMembers is — and for one more that is this operation's alone:
|
|
// the two value members are optional and their OMISSION is meaningful, so the
|
|
// handler has to see presence rather than a decoded zero value.
|
|
var metadataCASRequestMembers = []string{"actor", "key", "expected", "value"}
|
|
|
|
// handleCompareAndSetMetadata conditionally sets one metadata key.
|
|
//
|
|
// It carries the claim's posture verbatim. The actor is caller-ASSERTED
|
|
// provenance for the audit trail and not authenticated identity; hooks do not
|
|
// fire and the per-command auto-commit machinery does not run. The only durable
|
|
// effect is the single storage commit the role makes inside its own
|
|
// transaction.
|
|
//
|
|
// A LOST RACE IS A 200. `swapped: false` with `current` carrying the value that
|
|
// refused the swap is the answer to the question that was asked, and the reason
|
|
// this operation has no 409: a conflict code would put the ordinary path of a
|
|
// retry loop into the error channel, and the value the loop needs next would
|
|
// have to travel in a problem extension member. The document says so for
|
|
// clients; this comment says so for the next handler author who reaches for
|
|
// ClassifyError here.
|
|
//
|
|
// Everything above the role is argument validation. What the values MEAN — the
|
|
// canonical equality rule, absence versus a stored null, which transitions
|
|
// write — belongs to issueops.MetadataCAS.
|
|
func (s *Server) handleCompareAndSetMetadata(w http.ResponseWriter, r *http.Request) {
|
|
// The custom-method dispatcher split the id off the segment and bounded it
|
|
// before this handler was chosen at all; see customMethodTarget.
|
|
id := r.PathValue(customMethodIDValue)
|
|
if !s.requireNoQuery(w, r) {
|
|
return
|
|
}
|
|
if !s.requireJSONContent(w, r) {
|
|
return
|
|
}
|
|
request, ok := s.compareAndSetMetadataRequest(w, r, id)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
cas, err := s.metadataCAS(r)
|
|
if err != nil {
|
|
s.failErr(w, r, err)
|
|
return
|
|
}
|
|
result, err := cas.CompareAndSetKey(r.Context(), request)
|
|
if err != nil {
|
|
s.failCompareAndSetMetadata(w, r, err)
|
|
return
|
|
}
|
|
writeJSON(w, apigen.CompareAndSetMetadataResponse{
|
|
Swapped: result.Swapped,
|
|
Current: metadataCASWireValue(result.Current),
|
|
})
|
|
}
|
|
|
|
// failCompareAndSetMetadata answers a failed swap, mapping the role's own
|
|
// validation refusal onto the 400 the document promises.
|
|
//
|
|
// It is failUpdate's sibling and follows its rule exactly: the role's
|
|
// ErrValidation is answered HERE rather than in ClassifyError, and neither
|
|
// branch QUOTES the role's message — a refusal from the metadata-key syntax or
|
|
// from the workspace's metadata schema arrives as prose about a key this
|
|
// surface has already reflected back, and 4xx details here describe the
|
|
// caller's own input rather than server internals. The real error goes to the
|
|
// log with the request id.
|
|
//
|
|
// The ErrNotFound check runs first because this operation addresses a resource
|
|
// by path, so an id that names nothing is a genuine 404.
|
|
//
|
|
// THERE IS NO CONFLICT BRANCH, and that is this operation's posture rather than
|
|
// an omission: a lost race never reaches here at all. It is a 200 carrying
|
|
// `swapped: false`.
|
|
func (s *Server) failCompareAndSetMetadata(w http.ResponseWriter, r *http.Request, err error) {
|
|
if errors.Is(err, storage.ErrNotFound) {
|
|
s.fail(w, r, NotFound())
|
|
return
|
|
}
|
|
if !errors.Is(err, storage.ErrValidation) {
|
|
s.failErr(w, r, err)
|
|
return
|
|
}
|
|
// The 4xx path does not log by default, so this is the one place the real
|
|
// refusal is recorded for the operator.
|
|
s.event("request_refused", "request_id", requestInfo(r.Context()).id, "error", err.Error())
|
|
s.fail(w, r, InvalidArgument("key", ReasonInvalidValue,
|
|
"the request was refused by this workspace's own metadata validation; nothing was written"))
|
|
}
|
|
|
|
// compareAndSetMetadataRequest decodes and validates the body, and reports
|
|
// whether the request may proceed.
|
|
func (s *Server) compareAndSetMetadataRequest(w http.ResponseWriter, r *http.Request, id string) (issueops.CompareAndSetKeyRequest, bool) {
|
|
members, res := decodeJSONObjectBody(w, r)
|
|
if res != nil {
|
|
s.fail(w, r, *res)
|
|
return issueops.CompareAndSetKeyRequest{}, false
|
|
}
|
|
if offender, unknown := unknownMember(members, metadataCASRequestMembers); unknown {
|
|
s.failUnknownMember(w, r, offender, metadataCASRequestMembers)
|
|
return issueops.CompareAndSetKeyRequest{}, false
|
|
}
|
|
|
|
actor, ok := s.bodyActor(w, r, members)
|
|
if !ok {
|
|
return issueops.CompareAndSetKeyRequest{}, false
|
|
}
|
|
// requiredEndpointMember is named for an edge endpoint and is exactly the
|
|
// bound this member needs: a required string, non-empty, within what
|
|
// storage holds, and free of control characters — which a metadata key must
|
|
// be for the same reason an id must, since it is printed by everything that
|
|
// renders a row. The role applies the key SYNTAX on top of it.
|
|
key, keyRes := requiredEndpointMember(members, "key")
|
|
if keyRes != nil {
|
|
s.fail(w, r, *keyRes)
|
|
return issueops.CompareAndSetKeyRequest{}, false
|
|
}
|
|
|
|
// The two value members are passed through UNPARSED. Their syntax is
|
|
// checked by the decode that produced these raw members, their SHAPE is
|
|
// whatever JSON the caller sent — the metadata plane holds any JSON value —
|
|
// and the role's own validation is the single definition of what it will
|
|
// accept. A second parse here would be a second definition.
|
|
return issueops.CompareAndSetKeyRequest{
|
|
Actor: actor,
|
|
IssueID: id,
|
|
Key: key,
|
|
Expected: metadataCASMember(members, "expected"),
|
|
Value: metadataCASMember(members, "value"),
|
|
}, true
|
|
}
|
|
|
|
// metadataCASMember reads one optional value member, preserving the difference
|
|
// between OMITTED and present. That difference is the whole request shape here:
|
|
// an omitted member means the key is absent on that side of the transition, and
|
|
// a member present holding `null` means it holds JSON null.
|
|
//
|
|
// It COPIES the raw bytes rather than aliasing the decoded body, so nothing
|
|
// downstream can be surprised by the request buffer's lifetime.
|
|
func metadataCASMember(members map[string]json.RawMessage, name string) *json.RawMessage {
|
|
raw, ok := members[name]
|
|
if !ok {
|
|
return nil
|
|
}
|
|
value := json.RawMessage(append([]byte(nil), raw...))
|
|
return &value
|
|
}
|
|
|
|
// metadataCASWireValue converts the role's optional current value to the wire's
|
|
// optional member. nil stays nil, so an absent key is an ABSENT member rather
|
|
// than a null one — the same distinction the request side makes, answered the
|
|
// same way.
|
|
//
|
|
// THE WIRE MEMBER IS NOT A POINTER, and that is load-bearing rather than tidy.
|
|
// apigen.MetadataValue is an alias of json.RawMessage, which is an Unmarshaler,
|
|
// so a client decoding a present `null` gets the literal stored; a
|
|
// *json.RawMessage would have been set to nil by encoding/json before the
|
|
// Unmarshaler ran, collapsing the two states this operation reports. See the
|
|
// schema's x-go-type-skip-optional-pointer note and
|
|
// TestCASMetadataResponseDecodesAPresentNull.
|
|
func metadataCASWireValue(current *json.RawMessage) apigen.MetadataValue {
|
|
if current == nil {
|
|
return nil
|
|
}
|
|
return *current
|
|
}
|