beads/internal/storage/batch_apply.go
Julian Knutsen 533f95295a
feat(httpclient): BatchApplier over HTTP — handshake cap, dep_add lineage on the wire, gc mappings (S5) (#7265)
* feat(httpclient): carry DepAddItem.HasSpawner/ThreadID over the wire

The http leg's batchApply wire shape dropped a dep_add item's HasSpawner
and ThreadID fields -- an edit the caller believed landed. Extend the
wire body (ApplyDepAddItem.has_spawner/thread_id), gate sending either
field on a new additive behavior capability
(issues.batchApply.depAddLineage / CapBatchApplyDepAddLineage) so a
client refuses locally before dialing an older server instead of
silently dropping graph lineage, and wire the storage-layer spawner-id
stamping (StampWaitsForSpawnerID) through both the dolt and uow legs
that already had the fields but never stamped them. wire_revision and
min_client are unchanged; the golden digest and openapi spec are
regenerated.

Also fixes three generic bijection/vocabulary gates this change was
missing: write_ledger_test.go's applyBatch/item/dep_add carriage table,
and the literal behaviorCapabilities lists in
internal/httpapi/server_test.go and
internal/httpclient/wire/vocabulary_test.go.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(httpclient/wire): pin the item-count gate at 356 items

Add TestApplyBatchAt356ItemsWithoutTheCapabilityRefusesBeforeDialing,
exercising internal/storage/batchfixtures.Shape356's exact item count
-- the design's primary measured large-batch-apply shape -- rather than
only the floor+1/ceiling+1 boundaries the existing cases pin. The gate
is content-agnostic (it never looks past len(body.Items)), so a
synthetic plan here is behaviorally identical to a real Shape356 plan
for this one check; realistic-content coverage follows in the next
commit.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(httpclient): prove a 356-item Shape356 plan commits atomically or leaves zero rows

Add two tests against the real served stack using
batchfixtures.Shape356's realistic, heterogeneous content (102 creates,
136 blocks edges, 102 tracks-to-root edges, 16 assign updates):

- TestServedBatchApplyShape356CommitsAtomically applies the full plan
  once and verifies every create landed with a bound key, matching the
  issues table row-for-row.
- TestServedBatchApplyShape356PlusAStaleGuardLeavesZeroRows appends a
  357th item guarding the pre-existing root issue with a deliberately
  stale ExpectedVersion. Because the root is untouched by the other 356
  items, this exercises the real server-side precondition_failed round
  trip (rather than the static same-request-row ErrValidation rule),
  asserting errors.Is(err, issueops.ErrVersionMismatch) and that none of
  the 356 creates landed -- the "never chunk" ceiling: an all-or-nothing
  request that fails on its last item must leave nothing behind.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(httpclient): close S5 review HIGH findings (lineage gate, thread_id, gc mappings)

2026-10 Opus review on the S5 batch-apply slice found the wire change
correct but coverage missing:

- HIGH-1: refuseUnservedDepAddLineage (batchapplier.go) had no coverage
  at all -- deleting it passed every existing test. Add a test pinning
  that HasSpawner or ThreadID on a server without
  issues.batchApply.depAddLineage refuses *storage.ErrUnsupported
  before dialing, and that a plan touching neither field still dials.

- HIGH-2: thread_id was never asserted end to end. Add
  RunBatchApplyCarriesThreadIDOntoTheStoredEdge to the shared
  conformance package, wire it onto the dolt, embeddeddolt and uow
  legs, and add the http leg's own case
  (TestServedBatchApplyCarriesThreadIDOntoTheStoredEdge), which is the
  one case that proves the field survives both the client's encode and
  the server's decode at once.

- HIGH-3: DESIGN Sec 3.8 ("Guarded writes: no new roles") documents two
  gc mappings onto BatchApplier that had no coverage: an update carrying
  a metadata patch plus ExpectedVersion followed by a close in one
  request (CloseWithMetadataIfMatch, atomic -- a stale version leaves
  zero changes), and a keyed create/MetadataRefs/dep_add
  (parent-child included)/trailing-update plan (ApplyGraphPlan). Document
  both compositions on the BatchApplier interface and add http-leg tests
  for each.

Mutation-verified: removing the lineage gate call, dropping thread_id on
the client's encode, and dropping it on the server's decode each now
fail a test that previously passed unconditionally.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(httpclient): nil-guard snapshot consumers, fix spec wording, sync Bazel

2026-10 Opus review MED/LOW findings on the S5 batch-apply slice:

- LOW-6: Store.snapshot returns (nil, nil) when a Store has neither a
  wire nor a cached handshake. Store.Counter() does not call roleWire
  first (unlike Sweeper/BatchApplier), so this is reachable through the
  ordinary public accessor and a scoped count would panic on
  snap.Capabilities. Nil-guard every snapshot() consumer
  (batchapplier.go, counter.go, sweeper.go) so a nil snapshot is treated
  as "nothing advertised" and falls through to the capability refusal.
  Add TestCounterRefusesScopeGracefullyWithNoTransportAndNoSnapshot,
  mutation-verified to panic without the guard.

- LOW-7: the ApplyDepAddItem spec comment said an old server would
  "silently ignore" has_spawner/thread_id; it answers its own 400 for
  an unknown member. Fix the wording and regenerate apigen/types.gen.go.

- MED-4: internal/httpclient/BUILD.bazel was missing
  served_batch_apply_large_test.go, expected_revision_contract_test.go,
  served_dualwrite_history_test.go and the
  //internal/storage/batchfixtures dep. Sync with gazelle (confirmed
  idempotent) and go_srcs.py --check.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(storage): carry thread_id on a same-type dep re-add; bound batch thread_id

A same-type re-add of an existing dependency compared and rewrote only
metadata, so on both write legs (issueops.addDependencyInTx and the uow
dependency repository) a re-add naming a new ThreadID was read as
change-free and the thread was dropped, and a metadata-plus-thread re-add
stored the metadata without the thread. Both arms now read the stored
thread_id through one shared rule, issueops.ReAddedDependencyThread: a
named thread the row does not carry is a change (UPDATE, replacement-edge
journal entry, exactly one version, #5898 leg 2), and a re-add naming no
thread keeps the stored one, so callers that never carry a thread cannot
erase it. The journal's EventDep has no thread member, so a thread-only
re-add journals the same payload as the original add; the source's version
snapshot is what records the new thread, and the comments on both arms now
say so instead of promising a complete replacement edge.

planApplyBatchDepAdd bounds DepAddItem.ThreadID with CheckFieldLen, so an
over-long thread id is ErrValidation before any database work on every
leg, as the http leg's decode already refuses it, instead of an opaque
mid-transaction "string too long" on the local legs. Only the length bound
is shared: the http leg's control-character refusal stays http-only.

The HasSpawner/ThreadID docs now name the producer that actually sets
HasSpawner (an embedder lowering a graph plan, e.g. gc's ApplyGraphPlan
mapping) instead of bd create --graph, and drop the CHANGELOG reference
that had no entry behind it.

New conformance cases, wired on dolt, embeddeddolt, uow and served:
RunBatchApplyCarriesThreadIDOntoAnExistingEdge,
RunBatchApplyRefusesAThreadIDLongerThanItsColumn and
RunDependencyEditorSameTypeReAddWithChangedThreadMintsOneVersion.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci(shards): add the re-add thread test to the embedded storage shard manifest

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* ci: trigger the first PR CI run now that the base is main

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(httpclient): gate has_spawner to waits-for edges; refuse empty thread_id

Review iteration 1 fix-up for #7265 (synthesis F1, F2, F4, F5, F6, F7).

F2: the client's CapBatchApplyDepAddLineage gate refused HasSpawner on
every edge type, but the role reads the flag on a waits-for edge only
(StampWaitsForSpawnerID is a no-op off one). An embedder plan setting it
on, say, a blocks edge works against every existing server, yet this
client refused it during a mixed-version rollout. depAddNamesSpawner now
holds the role's own rule: the flag is gated and encoded on a waits-for
edge only, and dropped elsewhere, which loses nothing the role would
store. ThreadID stays gated on every edge type, since a thread is stored
on all of them. The "spawner flag on any other edge type" subtest is
restored to an unadvertising server and now also asserts the flag is
dropped from the body, and
TestApplyBatchRefusesUnservedDepAddLineageBeforeDialing gains a
ThreadID-on-blocks case. The W-DepAddItem.HasSpawner ledger row and the
regenerated engdocs/design/http-divergence-ledger.md say the same.

F5: the document gives thread_id minLength: 1, but the decoder read an
empty string as no thread. applyDepAddItem now refuses a present, empty
thread_id with 400 invalid_value naming items[i].dep_add.thread_id, as
it does an empty type; an absent one still names no thread. New
TestApplyBatchRefusesAnEmptyThreadID; the documented-body test now
forwards has_spawner and thread_id as well.

F1: bd create --graph does set HasSpawner (buildGraphApplyBatchRequest,
on the embedded and proxied legs, since #7209), so the DepAddItem doc
names both producers again and the conformance doc's CHANGELOG pointer
is restored; the [Unreleased] entry behind it is on the base.

F4: the CapBatchApplyDepAddLineage comment said an older server would
silently drop the members; it answers either one with
400 invalid_argument/unknown_parameter.

F6: the create-edge ledger comment said no operation publishes a thread
member; batch apply's dep_add item now does.

F7: TestServedBatchApplyGcApplyGraphPlan adds a waits-for item carrying
HasSpawner and ThreadID and reads the stored row back, pinning
metadata.spawner_id to the resolved spawner and the thread on the
served leg.

F3 (the journal's EventDep carries no thread member) is not addressed
here.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
2026-10-09 01:05:39 +00:00

398 lines
16 KiB
Go

package storage
import (
"encoding/json"
"fmt"
"strings"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// The DATABASE-FREE half of issueops.BatchApplier: what a batch request MEANS,
// which refs it can resolve, which guards it may carry, and how a waits-for
// edge's gate metadata is spelled. Every implementation of the role runs this,
// so those rules have ONE definition rather than one per backend — and they are
// pinned by unit tests in milliseconds, where a contract case would need a
// database to observe the same thing.
//
// IT IS HERE BECAUSE BOTH BODIES NEED IT, and they sit in different packages:
// the store-backed one in internal/storage/issueops and the unit-of-work one in
// internal/storage/uow, each of which already imports this package. This is
// NOT PlanCompareAndSetKey's reason — that plan type is here because
// internal/storage/domain has to name it in a repository signature, and nothing
// in domain names this one, because this role's unit-of-work leg has its own
// body and reaches domain through ordinary use cases. It is here beside
// PlanCompareAndSetKey, ValidateMetadataKey and the rest of this plane's
// meaning because that is where a reader looks for it.
//
// What is NOT here is anything that needs a row. Whether a key's create item
// lands on the durable or the ephemeral plane, whether an id exists, whether an
// edge closes a cycle — all of that belongs to the bodies, and each of the two
// runs it against its own transaction.
// ApplyBatchPlan is a validated apply-batch request whose waits-for edges carry
// normalized gate metadata. It is what an implementation works from, so no
// backend re-derives the ref rules and the caller's request is never written
// through.
//
// It shares the request's *issueops.Issue pointers rather than deep-copying
// them. The body clones each one before writing — every single-verb Execute…
// already snapshots its own request at entry — so the ID an implementation
// assigns still lands on the result and not on the caller's issue.
type ApplyBatchPlan struct {
// Actor, Provenance, ForceIDPrefix and SkipPerEdgeCycleCheck are the
// request's, checked.
Actor string
Provenance string
ForceIDPrefix bool
SkipPerEdgeCycleCheck bool
// Items are the request's items in declaration order, with each waits-for
// dep_add's Metadata replaced by its normalized form. The slice is fresh,
// so normalization does not write through to the caller's.
Items []issueops.ApplyItem
// KeyIndex maps each create item's Key to the index that declares it. The
// body resolves refs through it and the wire half reports an unknown key
// from it, so the two cannot disagree about what a key means.
KeyIndex map[string]int
}
// PlanApplyBatch validates an apply-batch request and normalizes its waits-for
// gate metadata. It is the whole of the role's request validation: every
// implementation calls it before touching a substrate, so a refused request
// costs no database work anywhere.
//
// THE ORDER OF THE CHECKS IS PART OF THE CONTRACT, because a request can be
// wrong in several ways at once and a caller fixing them one at a time needs
// the same answer every time. Request-level shape first, then per-item shape,
// then the ref graph, then the guards.
func PlanApplyBatch(in issueops.ApplyBatchRequest) (ApplyBatchPlan, error) {
if in.Actor == "" {
return ApplyBatchPlan{}, fmt.Errorf("%w: apply batch requires an actor", issueops.ErrValidation)
}
if len(in.Items) == 0 {
return ApplyBatchPlan{}, fmt.Errorf("%w: apply batch requires at least one item", issueops.ErrValidation)
}
if len(in.Items) > issueops.MaxApplyBatchItems {
return ApplyBatchPlan{}, fmt.Errorf("%w: apply batch accepts at most %d items, got %d",
issueops.ErrValidation, issueops.MaxApplyBatchItems, len(in.Items))
}
keyIndex, err := planApplyBatchKeys(in.Items)
if err != nil {
return ApplyBatchPlan{}, err
}
plan := ApplyBatchPlan{
Actor: in.Actor,
Provenance: in.Provenance,
ForceIDPrefix: in.ForceIDPrefix,
SkipPerEdgeCycleCheck: in.SkipPerEdgeCycleCheck,
Items: make([]issueops.ApplyItem, len(in.Items)),
KeyIndex: keyIndex,
}
copy(plan.Items, in.Items)
// touched records every row an earlier item MUTATED, addressed the way the
// request addresses it: by key for a row this request creates, by id for one
// it names. It is what makes the ExpectedVersion rule statically checkable.
touched := map[string]bool{}
for i := range plan.Items {
if err := planApplyBatchItem(&plan.Items[i], i, keyIndex, touched); err != nil {
return ApplyBatchPlan{}, err
}
}
return plan, nil
}
// planApplyBatchKeys checks every item's kind/payload agreement and collects
// the create keys. It runs as its own pass because a ref may name a key
// declared by a LATER item, which is a different diagnosis from a key nothing
// declares — and telling them apart means knowing every key before checking any
// ref.
func planApplyBatchKeys(items []issueops.ApplyItem) (map[string]int, error) {
keyIndex := make(map[string]int, len(items))
for i, item := range items {
payloads := 0
for _, present := range []bool{item.Create != nil, item.Update != nil, item.Close != nil, item.DepAdd != nil} {
if present {
payloads++
}
}
if payloads != 1 {
return nil, fmt.Errorf("%w: apply batch item %d must carry exactly one payload, got %d",
issueops.ErrValidation, i, payloads)
}
var matches bool
switch item.Kind {
case issueops.ItemCreate:
matches = item.Create != nil
case issueops.ItemUpdate:
matches = item.Update != nil
case issueops.ItemClose:
matches = item.Close != nil
case issueops.ItemDepAdd:
matches = item.DepAdd != nil
default:
return nil, fmt.Errorf("%w: apply batch item %d has unknown kind %q", issueops.ErrValidation, i, item.Kind)
}
if !matches {
return nil, fmt.Errorf("%w: apply batch item %d is kind %q but carries another kind's payload",
issueops.ErrValidation, i, item.Kind)
}
if item.Create == nil {
continue
}
if item.Create.Issue == nil {
return nil, fmt.Errorf("%w: apply batch item %d requires an issue", issueops.ErrValidation, i)
}
if len(item.Create.Issue.Comments) > 0 || len(item.Create.Issue.Dependencies) > 0 {
return nil, fmt.Errorf("%w: apply batch item %d must not carry comments or dependencies on the issue; edges are their own items",
issueops.ErrValidation, i)
}
if item.Create.Key == "" {
continue
}
if prior, dup := keyIndex[item.Create.Key]; dup {
return nil, fmt.Errorf("%w: apply batch item %d reuses key %q, already declared by item %d",
issueops.ErrValidation, i, item.Create.Key, prior)
}
keyIndex[item.Create.Key] = i
}
return keyIndex, nil
}
// planApplyBatchItem validates one item's refs, guards and edge metadata, and
// records what it touches for the items after it.
func planApplyBatchItem(item *issueops.ApplyItem, index int, keyIndex map[string]int, touched map[string]bool) error {
switch item.Kind {
case issueops.ItemCreate:
return planApplyBatchCreate(item.Create, index, keyIndex, touched)
case issueops.ItemUpdate:
return planApplyBatchUpdate(item.Update, index, keyIndex, touched)
case issueops.ItemClose:
return planApplyBatchClose(item.Close, index, keyIndex, touched)
case issueops.ItemDepAdd:
// The edge is COPIED before it is normalized. plan.Items is a fresh
// slice, but its payload members are the caller's pointers, so writing
// the normalized gate metadata in place would edit the request the
// caller still owns — the one mutation this plan can make, and the one
// the role promises never happens.
edge := *item.DepAdd
if err := planApplyBatchDepAdd(&edge, index, keyIndex); err != nil {
return err
}
item.DepAdd = &edge
return nil
}
return fmt.Errorf("%w: apply batch item %d has unknown kind %q", issueops.ErrValidation, index, item.Kind)
}
// planApplyBatchCreate checks a create's metadata refs and records the row it
// mints as touched.
//
// A METADATA REF MAY NAME ANY KEY, including this item's own and one declared
// later. Every id is minted before any splice runs, so the direction cannot
// matter — see issueops.CreateItem.MetadataRefs. What it may not do is name a
// key no item declares.
func planApplyBatchCreate(item *issueops.CreateItem, index int, keyIndex map[string]int, touched map[string]bool) error {
for metaKey, ref := range item.MetadataRefs {
if metaKey == "" {
return fmt.Errorf("%w: apply batch item %d has a metadata_ref with an empty key", issueops.ErrValidation, index)
}
if err := validateApplyRef(ref, index, "metadata_ref "+metaKey); err != nil {
return err
}
if ref.Key == "" {
continue
}
if _, ok := keyIndex[ref.Key]; !ok {
return &issueops.RefError{Index: index, Member: "metadata_ref " + metaKey, Key: ref.Key}
}
}
if item.Key != "" {
touched[applyTouchKeyRef(issueops.Ref{Key: item.Key})] = true
}
if item.Issue != nil && item.Issue.ID != "" {
touched[applyTouchKeyRef(issueops.Ref{ID: item.Issue.ID})] = true
}
return nil
}
// planApplyBatchUpdate checks an update's target and guards.
func planApplyBatchUpdate(item *issueops.UpdateItem, index int, keyIndex map[string]int, touched map[string]bool) error {
if err := validateApplyTargetRef(item.Target, index, "target", keyIndex); err != nil {
return err
}
if err := checkApplyExpectedVersion(item.ExpectedVersion, item.Target, index, touched); err != nil {
return err
}
touched[applyTouchKeyRef(item.Target)] = true
return nil
}
// planApplyBatchClose checks a close's target and guard.
func planApplyBatchClose(item *issueops.CloseItem, index int, keyIndex map[string]int, touched map[string]bool) error {
if err := validateApplyTargetRef(item.Target, index, "target", keyIndex); err != nil {
return err
}
if err := checkApplyExpectedVersion(item.ExpectedVersion, item.Target, index, touched); err != nil {
return err
}
touched[applyTouchKeyRef(item.Target)] = true
return nil
}
// planApplyBatchDepAdd checks an edge's endpoints, type and thread id and
// normalizes its gate metadata. The thread id gets its column's bound here, the
// one the http leg's decode already applies, so an over-long one is
// ErrValidation before any database work on every leg rather than a storage
// error mid-transaction on the local ones.
//
// IT RECORDS NOTHING AS TOUCHED, and that is a decision rather than an
// oversight. The ExpectedVersion rule above refuses a guard on a row this
// request has already REWRITTEN, and an edge write is a change to the graph
// rather than to either endpoint's row: the role promises nothing about whether
// it moves the source's version token. A later guard on that source is
// therefore left to the substrate, where a genuine mismatch is
// ErrVersionMismatch — an honest refusal — rather than being refused up front
// as a request a caller could not have composed.
func planApplyBatchDepAdd(item *issueops.DepAddItem, index int, keyIndex map[string]int) error {
if err := validateApplyTargetRef(item.Source, index, "source", keyIndex); err != nil {
return err
}
if err := validateApplyTargetRef(item.Target, index, "target", keyIndex); err != nil {
return err
}
if item.Source == item.Target {
return fmt.Errorf("%w: apply batch item %d: %s cannot depend on itself",
issueops.ErrSelfDependency, index, applyRefLabel(item.Source))
}
if !item.Type.IsValid() {
return fmt.Errorf("%w: apply batch item %d requires a dependency type (max %d chars)",
issueops.ErrValidation, index, types.MaxDependencyTypeLen)
}
if err := types.CheckFieldLen("dependency thread_id", item.ThreadID); err != nil {
return fmt.Errorf("%w: apply batch item %d: %v", issueops.ErrValidation, index, err)
}
metadata, err := normalizeApplyEdgeMetadata(item.Type, item.Metadata)
if err != nil {
return fmt.Errorf("%w: apply batch item %d: %v", issueops.ErrValidation, index, err)
}
item.Metadata = metadata
return nil
}
// checkApplyExpectedVersion refuses a version guard on a row an earlier item of
// this request already mutated.
//
// IT IS A REQUEST-SHAPE RULE, not a race. The token is server-minted and
// rewritten by the write, so mid-request there is no value a caller COULD send:
// the pre-request token is stale by construction, and a row this request just
// created never had one the caller could read. Refusing statically says so;
// letting it through would answer every such request with ErrVersionMismatch
// and leave the caller looking for a concurrent writer that does not exist.
//
// ExpectedStatus and ExpectedAssignee carry no such rule, and the difference is
// that a caller CAN know what its own earlier item set them to.
func checkApplyExpectedVersion(expected *int64, target issueops.Ref, index int, touched map[string]bool) error {
if expected == nil || !touched[applyTouchKeyRef(target)] {
return nil
}
return fmt.Errorf("%w: apply batch item %d guards on a row version, but an earlier item in this request already wrote %s; "+
"the version token is minted by the write and cannot be known mid-request",
issueops.ErrValidation, index, applyRefLabel(target))
}
// validateApplyTargetRef checks a ref used to ADDRESS a row: exactly one member
// set, and a key that reaches BACKWARD.
func validateApplyTargetRef(ref issueops.Ref, index int, member string, keyIndex map[string]int) error {
if err := validateApplyRef(ref, index, member); err != nil {
return err
}
if ref.Key == "" {
return nil
}
declaredAt, ok := keyIndex[ref.Key]
if !ok {
return &issueops.RefError{Index: index, Member: member, Key: ref.Key}
}
if declaredAt >= index {
return &issueops.RefError{Index: index, Member: member, Key: ref.Key, DeclaredLater: true}
}
return nil
}
// validateApplyRef checks the exactly-one rule every ref answers to.
func validateApplyRef(ref issueops.Ref, index int, member string) error {
switch {
case ref.Key == "" && ref.ID == "":
return fmt.Errorf("%w: apply batch item %d: %s must name a key or an id", issueops.ErrValidation, index, member)
case ref.Key != "" && ref.ID != "":
return fmt.Errorf("%w: apply batch item %d: %s names both key %q and id %q; exactly one",
issueops.ErrValidation, index, member, ref.Key, ref.ID)
}
return nil
}
// applyTouchKeyRef renders a ref as the address the touched set is keyed by.
// The two namespaces are kept apart so a key and an id that happen to read the
// same string are not confused for one row.
func applyTouchKeyRef(ref issueops.Ref) string {
if ref.Key != "" {
return "key:" + ref.Key
}
return "id:" + ref.ID
}
// applyRefLabel renders a ref for a message.
func applyRefLabel(ref issueops.Ref) string {
if ref.Key != "" {
return fmt.Sprintf("key %q", ref.Key)
}
return ref.ID
}
// normalizeApplyEdgeMetadata returns the metadata an edge is STORED with.
//
// A WAITS-FOR ROW MUST BE SELF-DESCRIBING. Readers that predate the gate's
// introduction do not default a missing one, so an absent, blank or `{}`
// metadata is written as {"gate":"all-children"} — the rule
// types.NewGraphEdgeDependency already applies on every other path that writes
// one, reached here so this role cannot drift from it. A metadata that names a
// gate keeps it, along with the spawner and also-blocks members a caller may
// carry; a gate that is neither known value is refused.
//
// Every other edge type's metadata is passed through unchanged, checked only
// for being well-formed JSON when it is present at all: the blob is
// type-specific and this role does not know the types.
func normalizeApplyEdgeMetadata(depType types.DependencyType, metadata string) (string, error) {
trimmed := strings.TrimSpace(metadata)
if depType != types.DepWaitsFor {
if trimmed == "" {
return "", nil
}
if !json.Valid([]byte(trimmed)) {
return "", fmt.Errorf("edge metadata is not well-formed JSON")
}
return metadata, nil
}
meta := types.WaitsForMeta{}
if trimmed != "" && trimmed != "{}" {
if err := json.Unmarshal([]byte(trimmed), &meta); err != nil {
return "", fmt.Errorf("waits-for metadata is not a well-formed gate object: %w", err)
}
}
if meta.Gate == "" {
meta.Gate = types.WaitsForAllChildren
}
if !types.IsValidWaitsForGate(meta.Gate) {
return "", fmt.Errorf("waits-for gate %q is neither %q nor %q",
meta.Gate, types.WaitsForAllChildren, types.WaitsForAnyChildren)
}
raw, err := json.Marshal(meta)
if err != nil {
return "", fmt.Errorf("serializing waits-for metadata: %w", err)
}
return string(raw), nil
}