beads/internal/httpapi/claim_next.go
Julian Knutsen 38c3564075
claimNext + batchClose + incremental labels: the three role-backed ops with no wire (ga-g3gg8) (#5510)
* Publish POST /v0/beads/issues:claimNext: take ready work atomically (ga-g3gg8)

A client of this surface that wants the next piece of work composes
`GET /v0/beads/ready` with `POST /v0/beads/issues/{id}:claim`. That
composition is a RACE, and it is the reason this operation exists rather than
a round trip saved: between the listing that offered a row and the claim that
asked for it, another agent claims it — so the second agent earns a 409 for a
row it was correctly offered, and a fleet polling one queue spends its
requests losing races instead of doing work.

`claimNextIssue` publishes issueops.ReadyClaimer, where selection, the
compare-and-set that wins the row, and the hydration of the row that was won
are ONE transaction. The row cannot move between being chosen and being
reported.

THE FILTER IS THE LISTING'S, and not a copy of it. The parameters are decoded
by readyFilters — the same function `listReadyWork` and `countReadyWork` share
— because a claim that answered a different question than `bd ready` shows
would hand an agent work the listing never offered it, and two predicates that
are allowed to differ eventually do. The actor is the only body member: it is
provenance that lands in a column, and this surface has always carried that in
a body, while re-spelling the filter as a body object would create exactly the
second expression the shared decoder exists to prevent.
TestClaimNextAdmitsExactlyTheListingsFilters holds the DOCUMENT to the same
identity, since only the handler is protected by sharing the function.

`limit` is refused BY VALUE rather than left to the unknown-parameter rule,
and the distinction is two different client recoveries. `unknown_parameter`
means "this server does not know that name — version skew, degrade or fall
back", which would be false: it is a name this server knows perfectly well on
the sibling listing. It will not ACT on it, which is `invalid_value`, and the
reason is the role's: a claim delivers the one row it wins however large the
pool it scanned, and the scan must stay unbounded or a window that happens to
be full of rows a racing agent already took reports nothing to claim.

`sort` IS published, unlike on `ready:count`, because order decides WHICH row
a claim writes to where it cannot change a cardinality — and it is sent
explicitly for handleReady's reason, which bites harder here: an empty policy
adopts storage's hybrid fallback, and here that changes the row that gets
written rather than the order rows are printed in.

NOTHING ELIGIBLE IS A 200 WITH `claimed` ABSENT. An empty ready front is the
steady state of a drained queue, not a failure, and a polling agent that had
to classify an error to discover it would be pattern-matching prose. There is
no boolean beside the member and no scan count: a second member carrying the
same fact is a second member that can disagree with the first. This is the one
place the operation differs from `issues/{id}:claim`, which 404s an id that
names nothing — that one was asked about a ROW, and this one was asked a
question whose honest answer can be "none".

It documents no 409 and no 404 at all, and both absences are contract. There
is no id to have missed, and a row a racing agent took is simply not in the
set this claim scanned.

The real-Dolt leg asserts the guarantee a fake cannot express: nine concurrent
claimants against six ready rows win six distinct rows and never the same one
twice. The assertion is on duplicates rather than on timing, so it is
deterministic however the goroutines interleave.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>

* Publish patch.add_labels and patch.remove_labels on updateIssue (ga-g3gg8)

The bead asked for "incremental label add/remove on the wire", noting that
labels are replace-only and that issueops.LabelPatch has Add and Remove. The
trace found the situation is narrower than that and more familiar: the role's
whole algebra IS already wire-expressible — as `labels.{replace,add,remove}`
on `issues:batchApply`'s update item, which has published `ApplyLabelPatch`
since it landed. What has no incremental spelling is `PATCH /v0/beads/issues/{id}`,
whose `patch.labels` is a bare array.

That is #5484's finding again, on the one member it did not close: two
operations for patching one issue, disagreeing about what patching one issue
means. This closes the gap from the same side, and this member is the last of
them.

`patch.labels` KEEPS ITS SHAPE, and that is a constraint rather than a
preference. Nesting it into an object the way `ApplyPatchBody` does would
RE-TYPE a published member, which is the one kind of change this document has
no additive route for — `## Profiles` names re-typing explicitly as not a
tightening, and the only remedies written down are a new optional member or
cutting /v1. So the increments arrive as two flat siblings, which is the shape
`notes` and `append_notes` already use for the same replace/increment pair on
this exact schema.

THEY ARE NOT MUTUALLY EXCLUSIVE WITH `labels`, and that is the difference from
that pair. The role defines an ORDER over all three — replace, then add, then
remove, so removal wins — so a request carrying all three has a defined result
and must reach the role whole. Notes have no such algebra, so there the two
members are a contradiction and are refused. The handler assembles one
LabelPatch in one loop for exactly this reason: a member decoded into its own
patch value would overwrite the others' fields and the last one decoded would
silently win.

The retired premise is worth stating, because it was written down and it was
half right. `patch.labels` said incremental edits were deferred because
"replacement is the only shape whose result the client already knows without a
read-back". That holds for a writer that knows it is alone and fails for every
other one: two agents each adding a tag to one row, each composing a
replacement from a read taken before the other wrote, silently drop each
other's label. `bd label add` and every agent that tags work concurrently are
that caller. The real-Dolt leg is written as exactly that scenario.

The length bound applies to all three members including `remove_labels`, where
a value the column could not hold could never have been stored: it is a rule
about what a label may BE, and the role refuses it there too and writes
nothing, so the edge refuses it where the 400 can name the member and the
index.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>

* Publish POST /v0/beads/issues:batchClose: close many, keep the survivors (ga-g3gg8)

`bd close a b c` is one transaction and one history entry. Over this surface it
has been N calls to `POST /v0/beads/issues/{id}:close`, which is N transactions
and N history entries, with no way for a caller to say it wanted them together.
The request is the transaction boundary, which is the whole reason
issueops.BatchCloser is a role rather than a loop.

IT IS THE ONE OPERATION HERE WHOSE 200 CARRIES REFUSALS, and that shape is the
ROLE's rather than an arrangement of it. An id the batch turns down is skipped
and the survivors commit, because an agent that finishes four of five steps and
mistypes the fifth should keep the four — so a per-item refusal is a RESULT of
the batch, not an error of it. `batchCreateIssues` is the deliberate opposite
and has said so in its own document since it landed: half a created plan cannot
be re-sent without duplicating the half that landed.

The division that falls out is the contract a client codes against, and it is
stated on both sides: a NON-2xx means the batch NEVER RAN, and a per-item
`code` means that item did not land while others may have.

`code` ON AN OUTCOME IS `Problem.code`'s VOCABULARY, restricted to `not_found`
and `not_closable`. A second vocabulary was the alternative and it was refused:
an item refusal and a request refusal are the same question asked at two
scopes, so a client made to learn two spellings would be classifying the SCOPE
rather than the condition. `open_children` keeps both of its readings, and both
are the single close's: present-and-a-count on a success (the number a forced
close bypassed, reported even for an idempotent re-close), and PRESENCE as the
discriminator between the two `not_closable` refusals on a failure, exactly as
on a problem document.

The projection fails CLOSED. An item error no arm recognizes becomes a refusal
carrying the generic code, never a success — because a success with no row is a
shape a client cannot tell from a real close, and a `default` that fell through
would produce exactly that.

NO COMPOSED CLAIM, and the omission is reasoned rather than partial. The role
can claim the next ready issue in the same transaction once the closes land;
publishing that member would need a second, BODY-shaped spelling of the ready
filter vocabulary that `GET /v0/beads/ready` and the `issues:claimNext` landing
beside this one both express as query parameters — and two spellings of one
predicate eventually disagree, which is the reason ReadyClaimer.Filter is the
listing's own request type. A client that wants both sends two requests and
loses the single transaction, which is a real loss and is named in the document
rather than papered over. It is additive later.

The per-item id is bounded HERE, which the single close gets from the
custom-method dispatcher and this operation has no dispatcher to get it from. It
is a 400 rather than a per-item `not_found`, because it is a statement about the
REQUEST and because reporting it as a miss would let a caller map this server's
notion of a well-formed id.

The real-Dolt leg asserts the claim the whole shape rests on: a batch whose
middle item names nothing still commits the two either side of it, each with its
OWN reason — read back through the CLI rather than off the response the batch
composed. A fake cannot state that, because it holds no rows to roll back.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>

* Scope the label members' no-op wording to the labels (ga-g3gg8)

`add_labels` and `remove_labels` each said a no-op edit "reports
`changed: false`". That is the RESPONSE's member and it describes the whole
patch, so it is only true of a request whose sole content was the no-op edit —
a request that also moved a title changed the row and reports true.

They now say what is true of the member: the edit changes no labels. The
response's reading is stated once beside it, as a fact about the patch.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>

* Fix two misspell findings inherited from the release merge (ga-lzcuv)

`main` is red on Lint as of 294af94be2, and both findings are prose from that
squash rather than from anything in this branch:

  internal/httpapi/problem.go:85  `archaeology` -> misspell wants `archeology`
  internal/httpapi/problem.go:591 `neighbour`   -> misspell wants `neighbor`

`.golangci.yml` sets `misspell.locale: US`, so both are real under this
repository's configuration. They are fixed here because this branch merges next
and would otherwise carry a red Lint of its own making no changes to earn.

`neighbour` takes the US spelling. `archaeology` is REWORDED to `excavation`
rather than respelled: `archeology` is the spelling the linter wants and the
one most readers would read as a typo, and the sentence loses nothing by not
having the word in it. Rewording is the only one of the two options that leaves
the comment saying what it meant without looking wrong.

Neither is reachable from the local pre-commit hook, which fails at
golangci-lint config load in this environment before it analyses a file.

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>
2026-08-09 16:02:52 -07:00

125 lines
5.4 KiB
Go

package httpapi
import (
"errors"
"net/http"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/issueops"
)
// claimNextRequestMembers is the document's member list for ClaimNextRequest.
// It carries the actor and nothing else — the FILTER is in the query string,
// for the reason the schema gives — and the schema is
// additionalProperties: false, so anything else is refused BY NAME.
var claimNextRequestMembers = []string{claimActorMember}
// handleClaimNext takes ONE ready issue and hands it back claimed.
//
// It exists to retire a RACE, not to save a round trip. A client composing
// GET /v0/beads/ready with POST /v0/beads/issues/{id}:claim reads a row that
// another agent claims before the second request arrives, so it earns a 409 for
// a row it was correctly offered — and a fleet polling one queue spends its
// requests losing those races. Selection, the compare-and-set and the hydration
// share one transaction here, so the row cannot move between being chosen and
// being reported.
//
// THE FILTER IS THE LISTING'S, decoded by readyFilters itself rather than by a
// copy that admits the same names. That is the same argument countReadyWork
// makes for sharing it: a claim answering a different question than `bd ready`
// shows would hand an agent work the listing never offered it.
//
// A COLLECTION-LEVEL CUSTOM METHOD, spelled the way issues:sweep is: the
// segment is a literal, so the router registers the documented path and no
// dispatcher exception is needed. It names no id because the caller names a
// QUESTION — which is also why it has no 404.
//
// Hooks do not fire and the per-command auto-commit machinery does not run,
// exactly as for the claim.
func (s *Server) handleClaimNext(w http.ResponseWriter, r *http.Request) {
q := newQuery(r.URL.Query())
req := issueops.ClaimNextRequest{Filter: readyFilters(q)}
// EXPLICIT, always, for handleReady's reason: the storage layer maps an
// empty sort policy to hybrid, and forwarding an absent `sort` as "" would
// silently adopt that fallback while the document still reads
// `default: priority`. It matters more here than on the listing — the sort
// decides WHICH row this operation writes to, not merely what order rows
// are printed in.
req.Filter.Sort = q.oneOf("sort", readySortDefault, "hybrid", "priority", "oldest")
// `limit` is REFUSED BY VALUE rather than left to the unknown-parameter
// rule, and the distinction is the difference between two client
// recoveries. `unknown_parameter` means "this server does not know that
// name — version skew, degrade or fall back", which would be a lie: the
// name is one this server knows perfectly well on the sibling listing.
// This operation will not ACT on it, which is `invalid_value`.
if q.has("limit") {
q.invalid("limit", "this operation takes no `limit`: it delivers the one row it wins, "+
"and its scan must stay unbounded or a window of rows a racing agent already took would report nothing to claim")
}
if !s.acceptQuery(w, r, q) {
return
}
actor, ok := s.claimNextActor(w, r)
if !ok {
return
}
req.Actor = actor
claimer, err := s.readyClaimer(r)
if err != nil {
s.failErr(w, r, err)
return
}
result, err := claimer.ClaimNext(r.Context(), req)
if err != nil {
s.failClaimNext(w, r, err)
return
}
// A nil row is a 200 with `claimed` ABSENT, which is the role's own answer
// rather than this handler's interpretation: an empty ready front is the
// steady state of a drained queue, and a polling agent that had to classify
// an error to discover it would be pattern-matching prose.
writeJSON(w, apigen.ClaimNextResponse{Claimed: result.Claimed})
}
// claimNextActor decodes the one body member. It is the close's bodyActor
// behind the claim's refuse-the-rest-by-name check, because this body has
// exactly one member and the document says so.
func (s *Server) claimNextActor(w http.ResponseWriter, r *http.Request) (string, bool) {
if !s.requireJSONContent(w, r) {
return "", false
}
members, res := decodeJSONObjectBody(w, r)
if res != nil {
s.fail(w, r, *res)
return "", false
}
if offender, unknown := unknownMember(members, claimNextRequestMembers); unknown {
s.failUnknownMember(w, r, offender, claimNextRequestMembers)
return "", false
}
return s.bodyActor(w, r, members)
}
// failClaimNext answers a failed claim.
//
// IT HAS NO 409 AND NO 404 ARM, and both absences are the operation's contract
// rather than an omission. There is no id to have missed, and a row another
// agent took is simply not in the set this claim scanned — the role walks past
// it. The whole refusal vocabulary beyond the edge is the role's ErrValidation,
// which reaches the wire as the 400 the document promises.
//
// The role's own validation is defensively unreachable: an empty actor is
// refused at the edge, and the two fields it refuses beyond that — Limit and
// Offset — have no wire spelling this handler will fill. It is mapped anyway,
// because the alternative if that stops being true is a 500 for a request the
// caller could have fixed.
func (s *Server) failClaimNext(w http.ResponseWriter, r *http.Request, err error) {
if !errors.Is(err, issueops.ErrValidation) {
s.failErr(w, r, err)
return
}
s.event("request_refused", "request_id", requestInfo(r.Context()).id, "error", err.Error())
s.fail(w, r, InvalidArgument("", ReasonInvalidValue,
"the request was refused by this workspace's own validation; nothing was written"))
}