diff --git a/.golangci.yml b/.golangci.yml index 867e76f87..677bd155b 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -96,6 +96,44 @@ linters: deny: - pkg: github.com/steveyegge/beads/internal/workapi desc: "internal/httpapi is transport only: a read handler asks the provider for issueops.Reader and passes the whole request - it never builds a filter - see internal/httpapi/reads.go" + # The OTHER way past the roles, and the one the rule above does not + # close. Denying internal/workapi stops a handler BUILDING a filter; it + # does nothing about a handler taking uw.IssueUseCase() and calling the + # use case straight, which needs no filter and no builder. That is not a + # hypothetical shortcut - it is exactly what the proxied CLI did for + # years, and unpicking it is what the role accessors exist for. A second + # front door that reached the domain directly would be the same two + # implementations again, arriving one handler at a time. + # + # Deny-by-default over the whole package, so a file added here tomorrow + # is covered the moment it exists. The two holes below are named, and + # each one is a VALUE the caller assembled, never a use case: + # + # server.go Config.Workspace is domain.ContextInfo, the startup + # snapshot the embedder hands in. The package resolves + # no workspace state of its own; this is the type of the + # thing it is given. + # handlers.go contextResponse projects that snapshot with + # domain.PublishedContext - the SAME projection `bd + # context` publishes, which is where the credential and + # host-path exclusions live. Reimplementing it here to + # satisfy a lint rule would be the field-by-field copy + # that projection exists to prevent. + # + # Neither file touches a use case, and both are small: the read handlers + # (reads.go), the one write (claim.go) and everything added later stay + # guarded. Tests are exempt for the reason the rule above exempts them - + # they stand up domain fakes to drive the handlers. + httpapi-domain-boundary: + list-mode: lax + files: + - "**/internal/httpapi/**" + - "!$test" + - "!**/internal/httpapi/server.go" + - "!**/internal/httpapi/handlers.go" + deny: + - pkg: github.com/steveyegge/beads/internal/storage/domain + desc: "internal/httpapi is transport only: a handler reaches storage through an issueops role accessor on the provider, never through the domain use cases - see internal/httpapi/claim.go" # store.IssueReader() is the door to the reader role, and a store wears # decorators (telemetry spans, hook firing) that each add their layer in # their OWN accessor. A command holding the storage.DoltStorage diff --git a/CHANGELOG.md b/CHANGELOG.md index a3e8bee22..766efa460 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -168,8 +168,197 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 a `scoped` boolean so a reclaim log distinguishes a scoped sweep from a global one. +- **A shared semantic contract for every issue role** (bd-yby99). Seven of the + eight role interfaces in `issueops` now have a backend-independent + conformance suite in `backend/conformance`, run against the Dolt server store, + the embedded Dolt store, and the unit-of-work provider. One hundred and + twenty-nine cases cover `Reader`, `Relations`, `Commenter`, + `DependencyEditor`, `ReadyClaimer`, `BatchCloser` and `Lifecycle` — the last + spanning Create, Update, Close and Reopen. The unit-of-work leg runs 127 of + them: the two staging cases assert which concrete Dolt tables a commit + staged, which that provider has no way to observe. Each case is written + against the promise + stated in the role's doc comment, cited by file and line, rather than against + any implementation's current behaviour, so the doc comment is the artefact + under test as much as the code is. + + Read the three legs for what they are. The Dolt and embedded-Dolt stores + share one validate/execute body for six of the roles and the entire + implementation for `Reader`, so a green run on all three is **two readings of + the contract plus a wrapper-and-engine check**, not three independent votes. + The unit-of-work provider is the only separately written body, and every + divergence found so far where one backend disagreed with another rather than + all three with the doc has surfaced there. + + Where an implementation contradicts its own doc comment the case still + asserts what the doc says, and the disagreeing backend is parked at its + wiring site with a greppable `KNOWN DIVERGENCE ` skip, so the agreeing + backends stay pinned. Thirty-one findings have come out of that, all + children of `bd-yby99`: seven divergences, where the implementations + disagreed, and twenty-four spec gaps, where the doc was silent rather than + wrong and the case carried an in-file `SPEC-GAP ` marker instead of an + invented assertion. + + **Every parked case now runs.** The three findings that had a backend parked + are adjudicated and fixed, so the five `KNOWN DIVERGENCE` skips are gone and + all three legs run their full set with zero skips: an invalid `ClaimNext` + sort policy now matches `ErrValidation` (`bd-yby99.18`), a reparent on the + unit-of-work provider now replaces *every* parent edge (`bd-yby99.26`), and a + dependency removal on that provider now reaches the ephemeral plane + (`bd-yby99.17`). Each has its own entry below; none was resolved by weakening + a case. + + Twenty-two of the spec gaps are adjudicated as well. In each the leaf doc + gained the promise it had been missing and the contract case was tightened to + assert it, in that order, because the doc is the spec and a case may never + assert more than the doc promises. Ten of the adjudications moved production + code rather than only the doc — `bd-ocrn7`, `.3`, `.4`, `.7`, `.8`, `.17`, + `.18`, `.19`, `.20` and `.26` — and each is a user-visible change with its own + entry below, not a quiet edit made to turn a case green. + + Three findings remain open, and none is parked — no case skips anywhere. + `bd-yby99.9` is the doc's own admitted silence, named in the leaf text so a + caller does not read the silence as a promise: the dependency-existence + refusals still carry no error identity. `bd-yby99.1` is with `bd-soezd` for + measurement rather than adjudication. `bd-yby99.30` records a CLI + retry-safety property the `bd-yby99.19` decision traded away (see below). + The empty-string label question (`bd-yby99.28`, `bd-yby99.29`) is closed, not + open: the entry is now dropped on every backend and `LabelPatch` says so. + Five duplicated per-backend test files + were deleted outright and a sixth trimmed, their scenarios folded into the + shared cases; the Dolt-only facts they also pinned — history-entry message + spellings, working-set cleanliness, the GH#2455 no-op removal sweep — stay + Dolt-only in persistence tests. + ### Changed +- **An empty-string label is dropped rather than stored** (bd-yby99.29). Adding + or replacing labels with an empty value wrote a `labels` row keyed on `''` on + the Dolt-backed stores and dropped it on the unit-of-work one, so the same + edit left different rows depending on which route served it. Dropping wins on + both routes now: an edit carrying only an empty value changes nothing and + reports no change, and an empty value alongside real ones drops only itself + rather than failing the edit. A row that renders as nothing and matches + nothing was never worth storing, and refusing the whole update would have let + one stray value sink an otherwise-good multi-label edit. An empty row already + stored is left alone by add and remove, and cleared by a replace that omits + it — ordinary set behaviour, not a migration, so nothing sweeps existing data. + +- **An invalid sort policy is now a typed validation refusal** (bd-yby99.18). + Asking for a sort the ready query does not have — `--sort newest`, or a + `ClaimNext` sort on a batch close — was refused with a bare error carrying no + sentinel, on all three backends. A caller doing `errors.Is(err, + issueops.ErrValidation)` to separate "you asked for something impossible" + from "the database is unwell" classified it as a backend failure, which is + the wrong half of the role's own error trichotomy. It now wraps + `ErrValidation`. **The message text is byte-identical** — the wrap uses + `%.0w` deliberately — so the HTTP surface that prefix-matches it to render a + 400 rather than a 500, and every script reading the printed line, are + unaffected. + +- **A batch close that changed nothing no longer claims work or records + history** (bd-yby99.19). `BatchCloser` couples `ClaimNext` to "at least one + item closed", and "closed" was being read as "the item returned no error" — + which an already-closed item does. A batch whose items were *all* already + closed therefore mutated nothing and still handed out a claim and wrote a + history entry. Landing now means **changed**: an all-idempotent batch earns + no claim and records no entry. A batch that closed even one item is + unaffected. + + This has a cost worth stating plainly, tracked as `bd-yby99.30`. An agent + that closed an issue, crashed before receiving its next work item, and + retried `bd close --claim-next` used to get work from the retry; it now + gets nothing, because the retry closes nothing. That retry-safety property + was deliberate, and the way to get it back without re-coupling a claim to a + no-op is for `cmd/bd` to call `ReadyClaimer.ClaimNext` itself when the batch + reports no change. That is a design call above the role seam and has not been + made. + +- **A batch's Dolt commit message no longer names wisp ids** (bd-yby99.20). A + batch may close ephemeral and durable items together, and the durable commit + message named every item that landed. Wisp tables are dolt-ignored, so that + message shipped a reference to work no other machine can resolve — the same + federation leak `Commenter` already guards against. The message is now + composed from durable landings alone and reports ephemeral ones as a count. + Closing a wisp still counts as work landing: a wisp-only batch still succeeds + and still earns its claim. + +- **Breaking: `bd list --ready` now refuses a filter it cannot honor instead + of silently ignoring it** (bd-yby99.8). The `--ready` arm reaches the + blocker-aware query through a narrower filter than the rest of `bd list` + uses, and everything that filter could not carry was dropped without a word: + `bd list --ready --id tst-d68` answered with every ready issue in the + workspace, not the one named. It now fails with a validation error naming the + fields it could not honor. + + The refused combinations are `--ready` together with any of `--id`, + `--title`, `--spec`, `--title-contains`, `--desc-contains`, + `--notes-contains`, `--external-contains`, `--external-ref`, any + `--created/--updated/--closed/--defer/--due` bound, `--deferred`, + `--overdue`, `--empty-description`, `--no-labels`, `--no-parent`, + `--pinned`, `--priority-min`, `--priority-max`, or an HTTP list cursor. A + script that passed one of these was already getting the wrong answer; it now + gets an error instead of silently wrong rows. Everything `--ready` does carry + is unchanged — `--type`, all the label flags, `--assignee`, `--no-assignee`, + `--priority`, `--parent`, `--mol-type`, `--wisp-type`, `--metadata-field`, + `--has-metadata-key`, `--exclude-type`, `--include-gates`, `--include-infra`, + `--limit`, `--offset`, `--max-rows`, `--sort` and `--reverse` — as is + `--no-pinned`, which the ready query already satisfies by construction. + + What `--ready` carries, what it refuses, and the two things the ready set + decides for itself (it never returns pinned issues, and it applies no template + predicate of its own) are now stated on `issueops.ListRequest.ReadyFlag` and + pinned by the Reader conformance contract at all three backends. + +- **`issueops.Reader` now refuses an `Offset` it cannot honor instead of + silently ignoring it** (bd-yby99.7). The store-backed reader — one body, + handed back by both the Dolt server store and the embedded store — renders + `LIMIT` without `OFFSET`, so a caller that paged with `Offset` got the + unpaged first page again and again with no error to notice: three matching + rows came back 3/3/3 at `Offset` 0/1/2. `Ready` and `List` now return a typed + `*issueops.ErrUnsupported` naming the operation and the backend. The + unit-of-work reader, which does render `OFFSET`, keeps honoring it, and both + behaviours are now pinned by one conformance case: an `Offset` is honored or + refused, never ignored. + + **No CLI behaviour changes.** `bd ready --offset`, `bd list --offset` and + `bd query --offset` already rejected a non-zero offset on the direct route + and already reached the unit-of-work path under `--proxied-server`, where + offset paging works and is unaffected. This closes the same hole one layer + down, for callers built on the library rather than on the CLI. + + `ErrUnsupported` moved into the public `issueops` package and is aliased back + from `internal/storage`, so a consumer holding only a role interface can + classify the refusal with `errors.As` without importing an internal package. + It is the same type throughout: `beads.ErrUnsupported` and + `storage.ErrUnsupported` are unchanged aliases and every existing `errors.As` + site keeps matching. The portable way to page a listing across backends is + the keyset position (`ListRequest.AfterCreatedAt`/`AfterID`), which every + implementation honors and which is stable under concurrent writes; ready work + carries no keyset and therefore has no portable paging. + +- **Breaking: a dependency type is now bounded at 32 characters, not 50** + (bd-yby99.3). The `type` column on both `dependencies` and + `wisp_dependencies` is `VARCHAR(32)` and no migration widens either, so the + validator's old 50-character bound accepted a range of types — 33 to 50 + characters — that no row could ever carry. Depending on the caller, such a + type either failed at the database with a raw truncation error or was + silently cut short. `types.DependencyType.IsValid` now bounds at the new + exported `types.MaxDependencyTypeLen`, so the refusal arrives from one place, + ahead of every backend, with a typed validation error. + + This narrows what bd accepts on twelve paths, among them `bd create --deps`, + `bd dep add --type`, `bd link --type`, `bd batch`, `bd graph apply` and + markdown import. In practice nothing in the wild should notice: every + well-known type is far shorter (the longest, `conditional-blocks`, is 18 + characters), and `bd create --deps` accepts only well-known types anyway. The + user-visible error text changed too — messages that read `max 50 chars` or + `at most 50 characters` now name 32 — so a script matching on that literal + string needs updating. One rough edge is unchanged and worth knowing about: + `bd create`'s interactive form warns and drops an invalid dependency rather + than failing, so a 33-to-50-character type there now silently loses the edge + instead of creating an unstorable one. + - **Breaking: `bd update --status ` now enforces close policy.** Moving an issue into `closed` (or any configured done-category status) via `bd update`, `bd batch update`, or the issueops facade now refuses when the @@ -206,6 +395,197 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 is what the already-published v0 claim response and `bd update --claim --json` both report today. +- **`issueops.ReopenRequest` gained a `Provenance` field, and `bd reopen` now + names the issue in its Dolt commit message on the direct path.** `Provenance` + is the same optional label `UpdateRequest` already carries: it names the + surface a mutation came from, it never changes *whether* a history entry is + recorded, and empty still selects the implementation's default. It exists on + this request because the defaults do not agree — the store-backed backends + write `bd: reopen issue` and the unit-of-work backend writes `reopen issue`, + neither naming the issue. A caller that spells a label now gets one entry + whichever backend served it. The visible change is in `bd dolt log` only: a + direct `bd reopen bd-1` reads `bd: reopen bd-1` where it read + `bd: reopen issue`, or `reopen issue` on the unit-of-work backend. + + `UpdateRequest` and `ReopenRequest` are the only two requests that carry the + label, and deliberately so. `CreateRequest` gains nothing — no surface has + ever named the created issue, so the field would have no caller. Neither do + `CloseRequest`, `CloseBatchRequest`, `ClaimNextRequest`, `AddCommentRequest`, + `AddDependenciesRequest` or `RemoveDependencyRequest`: each of those roles + composes its entry from what the call actually did, so a caller-supplied + label could only restate it or contradict it. For the batch close and the + claim one is not even expressible — those messages name what LANDED and which + id the claim WON, neither of which is knowable before the call. For the + dependency verbs the entry follows the edges: one edge names both endpoints, + several name only their count, and — see the source-routing note below — a + request made entirely of wisp-sourced edges records no entry at all, leaving + a label nothing to name. + +- **Public `beads.Storage` interface gained required `DependencyEditor()`, + `Commenter()` and `IssueRelations()` methods.** Three more roles alongside + `IssueLifecycle()`, `IssueReader()`, `ReadyClaimer()` and `BatchCloser()`, + reached the same way and layered by each decorator in its own accessor. + Consumers that only *call* the interface are unaffected; any external type + that *implements* it (a custom store, mock, or proxy) must add all three to + compile, and a decorator must implement the two write roles by recursing into + the store it wraps rather than delegating blindly. + + `DependencyEditor() (issueops.DependencyEditor, error)` edits the dependency + graph. `AddDependencies` asserts a set of edges as ONE durable act — one + transaction, at most one history entry — and is ALL-OR-NOTHING: any refused + edge (self-dependency, cycle, type conflict, hierarchy conflict, unknown + endpoint) refuses the whole request and writes nothing. Edges asserted + together describe a graph, and half a graph is a graph nobody asked for. + `RemoveDependency` is idempotent: a missing edge is `Removed: false` with a + nil error and no history entry, not `ErrNotFound`. + + The dependency-type constants `issueops.DepBlocks`, `DepParentChild`, + `DepRelated`, `DepDiscoveredFrom`, `DepRepliesTo` and `DepWaitsFor` ship with + it. They are **documented common values of an OPEN, workspace-configurable + set** — not a closed enum, not exhaustive, and not validated against: nothing + refuses a type merely because it is absent from the list, and a workspace's + own type is a first-class value everywhere a `DependencyType` is accepted. + They exist because `internal/types` is unimportable outside the module, so + without them an external embedder can hold a `DependencyType` but has no + spell-checked way to name one — the same reason the error sentinels are + re-exported. + + `Commenter() (issueops.Commenter, error)` appends one comment as one atomic + mutation. A blank `Text` is `ErrValidation`, as is an empty `IssueID`; the + issue-then-wisp fallback happens inside, as it does for `Reader.Get`; a + non-empty id naming neither plane is `ErrNotFound` — an unaddressed request + is invalid, not a thread that went missing, so the two are worth telling + apart. `issueops.Comment` (an alias for the canonical comment model) + is the result type. A comment on an ephemeral row records **no** durable + history entry — the wisp tables are dolt-ignored so ephemeral work never + ships, and an entry naming a wisp thread is exactly the artifact that + ignoring them prevents; the comment still lands on the ephemeral thread and + reads back from it. + + `IssueRelations() (issueops.Relations, error)` reads an issue's neighbors. + `Related` requires an explicit `RelationOut` or `RelationIn` — **the zero + direction is `ErrValidation`, with no implicit "both"**, because a silent + default hands a caller the inverse graph with nothing to notice. An unusable + `Types` entry is `ErrValidation` rather than a filter that matches nothing, + and an anchor missing from both planes is `ErrNotFound` rather than an empty + list. The result order is pinned: ascending by the neighbor's id, with the + edge type breaking a tie. + + `bd dep add`, `bd dep remove`, `bd dep list`, `bd comment` and + `bd comments add` are on these roles on BOTH routes — the direct one reaches + them through the store's own accessor exactly as the proxied one reaches them + through the provider's. Four behaviors changed on the + proxied route: `bd dep list` now answers in the pinned order rather than in + the order the two dependency tables happened to be read; a `bd dep list` + naming an issue that does not exist now reports that instead of printing an + empty neighbor list, matching what the direct route has always done; a + `bd dep remove` that finds no edge now records no Dolt commit at all, where + it used to name one; and a single-line `bd dep add --file` writes + `bd: dep add ` rather than `dependency: add 1 edges`. + + Four more changed on the direct route as it joined them. `bd dep list` there + now answers in the same pinned order. Dolt commit messages for the explicit + dep verbs are now the role's — `bd: dep add ` and + `bd: dep remove ` — where the direct path used to write + `dependency: add -> ` / `dependency: remove -> ` in + server mode and a generic `bd: dep add (auto-commit) by [...]` in + embedded mode. A `bd dep add --file` edge refused by storage no longer + carries a `line N:` prefix, because the role's request is all-or-nothing and + names no edge index — parse and id-resolution errors still name their line. + And a `bd dep add --file` in embedded `batch`/`off` auto-commit mode now + defers its version commit to the next explicit commit point instead of always + writing one, which is what every other write verb already did. + + `bd comment`'s direct route changed one thing with it, on the embedded + backend only: a comment's Dolt commit is now the role's `bd: comment ` + authored by `beads`, where the CLI auto-commit wrote + `bd: comment (auto-commit) by []` authored by `root`. That is + the spelling the Dolt server backend already wrote, and it is one commit per + comment either way. Comment LISTING (`bd comments `) is on neither role + and unchanged on both routes: reading a thread is a paging question with a + cursor of its own, which `issueops.Commenter` deliberately excludes. + + `DependencyEditor.AddDependencies` routes each edge by its SOURCE, the rule + the stores' own dependency verb has always applied and the one `bd dep + remove` and `bd dep list` already read: a wisp-sourced edge goes to + `wisp_dependencies` with its event in `wisp_events`, an issue-sourced one to + `dependencies` and `events`. Routing by source rather than pinning it to the + issues plane is what keeps `bd dep add ` working: a wisp + has no row in the issues plane, so a pinned source has nothing to hang an + edge off, and the two routes would not even have failed alike — the direct + one on its source-existence check, the proxied one on an `fk_dep_issue` + foreign key violation. ONE REQUEST MAY MIX THE TWO: it is still one + transaction, the parent-child-first ordering and the whole-graph cycle gate + both span the two tables (a cross-plane cycle is still refused), and a + refusal rolls back both planes. Only the durable half is versioned, so a + request made entirely of wisp-sourced edges records no history entry and + leaves the working set clean — asserted end to end against a real embedded + store by `TestEmbeddedDepAddWispSource`, which runs `bd dep add + ` at the front door. `bd link` on the proxied server routes the same + way, matching its direct twin. Behind the role there is no plane-pinned bulk + variant left to reach for by mistake: the internal domain layer's three bulk + add verbs are now the one source-routed `AddDependencies`, so every bulk + caller — role, `bd link`, unit of work — gets this rule and cannot opt out + of it. + +- **Public `beads.Storage` interface gained required `ReadyClaimer()` and + `BatchCloser()` methods.** Two more roles alongside `IssueLifecycle()` and + `IssueReader()`, reached the same way and layered by each decorator in its + own accessor. Consumers that only *call* the interface are unaffected; any + external type that *implements* it (a custom store, mock, or proxy) must add + both methods to compile, and a decorator must implement them by recursing + into the store it wraps rather than delegating blindly. + + `ReadyClaimer() (issueops.ReadyClaimer, error)` takes ready work atomically: + `ClaimNext` selects, wins the compare-and-set and hydrates the row it won, + all in one transaction. Its filter is `issueops.ReadyRequest` — the same type + `Reader.Ready` takes — so the claim's predicate cannot drift from the set + `bd ready` shows; `Limit` and `Offset` on it are `ErrValidation`, because the + claim scan clears them and accepting a field only to drop it is worse than + refusing it. An empty ready front is a nil result with a nil error, not an + error class to classify. + + `BatchCloser() (issueops.BatchCloser, error)` closes many issues as one + durable act: `CloseBatch` commits every item that lands in ONE transaction + with at most one history entry. The request is the transaction boundary — + nothing on the contract exposes begin or commit. It is deliberately not + all-or-nothing: a refused id is skipped and the survivors commit together, so + `CloseBatchResult.Outcomes` carries one entry per requested item in request + order, each with a typed `errors.Is`-able refusal that never aborts the rest. + An optional `ClaimNext` runs after the closes, in the same transaction, only + when at least one item closed. + + `bd ready --claim` and `bd close` are on these roles on BOTH routes. Three + behaviors changed on the proxied route: the proxied claim's Dolt commit + message is now `bd: claim ready `, the + spelling the other two backends already wrote (it was + `bd: ready --claim `); molecule auto-close, `--suggest-next` and + `--continue` now run after the close transaction rather than inside it, which + is where the direct route has always run them — a plain `bd close a b c` is + still exactly one Dolt commit, while a close that actually auto-closes a + molecule or advances a step now produces two; and `bd close --claim-next` + walks the ready order and takes the first row it can win, where it used to + read the single top ready row and warn if that row had already been taken — + a race with another agent now claims the next candidate instead of claiming + nothing. + + `bd close`'s direct route closed N ids as N transactions with N Dolt commits + until it joined them, so five things changed as it did. `bd close a b c` now + writes ONE commit named `bd: close a, b, c` instead of three named + `bd: close issue` — one request per STORE, since a transaction cannot span + the second repo a prefix-routed id reaches. `--claim-next` runs inside the + closes' transaction and only when something landed, walks the ready order the + way the proxied route already did, and its `--json` `claimed` value is now the + post-claim row (in_progress, assigned) rather than the pre-claim row the old + two-step read. Molecule auto-close runs after ALL the closes land rather than + between them — the root still closes exactly once; only which id's slot prints + the `Auto-closed completed molecule` line can move. The open-children refusal + moved from a cmd/bd pre-flight read into the close's own transaction, closing + a read-then-write window that made `bd close ` depend on + argument order; its message is unchanged. And an unsatisfied gate on an issue + that ALSO has open children now reports the gate rather than the children, + because the gate check stayed in the pre-flight — both were already refusals. + - **Public `beads.Storage` interface gained a required `IssueReader()` method** (bd-serve reader role). `IssueReader() (issueops.Reader, error)` is the read counterpart of `IssueLifecycle()`: one accessor returning a role that answers @@ -280,6 +660,69 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **`bd update --parent` on a proxied server no longer leaves a stale parent** + (bd-yby99.26). A parent id is a *set* assignment: setting it replaces every + parent edge the child has, and clearing it removes them all. The unit-of-work + route stopped after the first edge it found. A child with two parents + reparented to a third kept one of the originals, and clearing the parent left + the rest in place — in both cases reported as a success. Two parents on one + child is not the common shape, but the failure was silent and the resulting + graph is wrong for every reader that walks parent edges. The Dolt backends + already applied the set rule; this brings the third route into line. + +- **`bd dep remove` on a wisp-sourced edge now removes it** (bd-yby99.17). On + the proxied server the removal was pinned to the durable plane: an edge whose + *source* is a wisp was looked for in `dependencies`, not found, and reported + as `Removed: false` with a nil error while the row stayed in + `wisp_dependencies`. The command exited zero having changed nothing. A + removal cannot put an edge anywhere, so it now reads the source's plane and + deletes from there, and the delete's own result is the found/not-found + verdict. Removing an edge that genuinely does not exist is still a nil-error + no-op, as before. + +- **A dependency on an issue in another repository no longer fails with a raw + foreign-key error** (bd-ocrn7). beads addresses a foreign repo's work by + prefix — `otherrig-9001` from a rig whose own prefix is `bd-` — and the + database holds such a target in `depends_on_external`, a column with no + foreign key, precisely because the row cannot exist locally. The domain + route classified the target by looking only for the literal `external:` + prefix, decided `otherrig-9001` was local, wrote it to + `depends_on_issue_id`, and the foreign key rejected the insert with + `Error 1452`. No edge was written and the error named a constraint rather + than the problem. + + Both routes now classify through one named rule, + `issueops.IsExternalDepTarget`: a target is external if it is spelled + `external:...` **or** its prefix differs from the source's. That is what the + Dolt backends have always done, so this brings the third route into line + rather than inventing a policy. The foreign key itself is untouched, and a + genuinely local, genuinely missing target is still refused as before. One + consequence beyond the failing case: a cross-prefix target that *does* + happen to exist in the local issues table now also lands in the external + column on this route, which means derived blocking no longer reads that edge + — again matching what the Dolt backends already produced. + +- **A ready claim that wins an ephemeral row no longer reports a spurious + "could not be verified" error** (bd-yby99.4). In server mode, `bd` re-reads a + claim it just made to confirm the write landed, because an exit code is not + truth against a degraded server. That re-read always looked in the `issues` + table. But a ready claim can win a wisp when the request's filter admits + ephemeral rows (`bd ready --claim --include-ephemeral`), and the claim is + written to the `wisps` table by design — so the verify hunted for the row in + a table that never held it and turned a perfectly good claim into + `reported success but could not be verified (server degraded?)`. The + verification is now plane-aware rather than skipped: a wisp claim is checked + against the `wisps` row, so no check was traded away for the fix. + + The `ClaimNext` contract is now explicit that the ready set is whatever the + filter admits — an ephemeral row the filter pulls in is genuinely claimable, + and claiming it moves that row rather than promoting it to a durable issue. + Two properties follow that callers should plan around: such a claim records + **no** durable history entry, because ephemeral rows are not versioned, so + reconstructing who took what from history alone will not show it; and it + takes no lease, so `bd heartbeat` refuses it and `bd reclaim` will not + recover it if the agent holding it dies. + - **`bd dolt push` and `bd sync` no longer adopt a Dolt remote derived from git origin without consent** (#5068). On a rig with no Dolt remote configured, both commands silently derived one from `git remote get-url diff --git a/backend/conformance/batch_closer_contract.go b/backend/conformance/batch_closer_contract.go new file mode 100644 index 000000000..ad6223576 --- /dev/null +++ b/backend/conformance/batch_closer_contract.go @@ -0,0 +1,1322 @@ +package conformance + +import ( + "context" + "errors" + "reflect" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// This file holds the contract every implementation of publicops.BatchCloser +// must satisfy. There are three of them — the direct store, the embedded store +// and the unit-of-work backend — and the first two share one validate/execute +// body (internal/storage/issueops.ValidateCloseBatchRequest and +// ExecuteCloseBatch) that the third does not, so wiring all three catches +// wrapper and engine divergence on those two and body divergence only on uow. +// +// THE LEAF DOC COMMENT IS THE SPEC. Every case below asserts what +// issueops/batchcloser.go promises, not what an implementation currently does. +// A backend that disagrees is parked at its own WIRING site with +// skipKnownDivergence so the agreeing backends stay pinned; the shared Run +// functions here never bend to accommodate one implementation. +// +// What it pins, clause by clause: +// - Outcomes mirror Items index for index in request order, refusals +// included, each echoing its own IssueID (batchcloser.go:96-99, 142-143, +// 75-77). +// - A per-item refusal is a RESULT of the batch, not an error of it, and the +// survivors commit (batchcloser.go:87-91, 111-117); Issue is nil exactly when +// Err is set (batchcloser.go:78-80); the per-item Reason and the +// request-wide Session land on the rows they were asked for +// (batchcloser.go:5-8, 41-42). +// - A non-nil error and populated Outcomes are mutually exclusive +// (batchcloser.go:119-126). +// - An idempotent re-close is a per-item success with Changed false, and +// still reports OpenChildren (batchcloser.go:81-86); a duplicated id is one +// of those at its own index, and the first occurrence's reason is what the +// row keeps (batchcloser.go:28-33). +// - Force is request-wide and bypasses only blocker and open-child policy; +// the per-item precondition its clause also names is a category the request +// type keeps EMPTY (batchcloser.go:43-53). +// - ClaimNext runs after the closes, inside the same transaction, and only +// when at least one item closed (batchcloser.go:55-70, 100-103, 143-146). +// - LANDED means CHANGED: an all-idempotent batch earns no claim and records +// no history entry (batchcloser.go:60-64, 119-122). +// - A wisp is an admissible item and its close counts toward the claim +// coupling (batchcloser.go:35-39), but the durable history entry a mixed +// batch records never names it (batchcloser.go:128-135). +// - What LANDS is atomic: one transaction, at most one history entry, none +// when nothing landed (batchcloser.go:119-122). +// - The method's own error is reserved for validation, cancellation and +// infrastructure — the failures that mean the batch NEVER RAN, so no +// outcomes and no durable trace (batchcloser.go:119-126). +// - The caller's request is never mutated (batchcloser.go:137-140). + +// BatchCloserFixture supplies adapter-specific storage access for the +// batch-close assertions. +type BatchCloserFixture struct { + // IssuePrefix namespaces the ids and labels each assertion seeds, so + // several of them can share one database. The claim cases lean on it + // harder than the others: they select their candidate through a label + // derived from this prefix, because a ready front shared with a sibling + // case would otherwise decide which row a claim wins. + IssuePrefix string + Closer publicops.BatchCloser + // CreateIssue seeds a durable issue in the issues plane, labels included. + CreateIssue func(context.Context, *types.Issue, string) error + // AddDependency seeds one edge. The contract uses it for the two refusal + // shapes a close has: a live blocker and an open child. + AddDependency func(context.Context, *types.Dependency, string) error + // CreateWisp seeds an ephemeral issue in the wisps plane, for the three + // ephemeral rules the leaf doc states: a wisp is an admissible item and + // closing one counts toward "at least one item closed" + // (batchcloser.go:35-39), and the durable history entry never names it + // (batchcloser.go:128-135). + CreateWisp func(context.Context, *types.Issue, string) error + // + // AddComment seeds one comment on an issue, for the single clause that + // needs one: the outcome snapshot OMITS comments (batchcloser.go:78-80), + // which cannot be told from an issue that simply has none. + // + // It is not part of the shared per-backend role fixture kit — that kit + // exposes no comment hook — so each wiring supplies it locally. Folding it + // into the kit is an S0 follow-up. + AddComment func(ctx context.Context, issueID, actor, text string) error + QueryScalar func(context.Context, string, []any, ...any) error + // CountHistory reports the branch's history-entry count, for the + // entry-per-call clause. Nil means this backend cannot observe history, + // and the two history cases then skip loudly rather than pass quietly. + CountHistory func(context.Context) (int, error) +} + +// RunBatchCloserOutcomesMirrorItemsIndexForIndex pins the index correspondence +// (batchcloser.go:96-99, method doc 142-143) and the id echo (75-77). +// +// The request order is deliberately neither id order nor +// successes-then-refusals, and the refusal sits in the middle, so an +// implementation that sorted, appended, or dropped the refused item lands its +// outcomes at the wrong indices and fails here rather than in a caller that +// prints one issue's verdict under another issue's name. +func RunBatchCloserOutcomesMirrorItemsIndexForIndex(t *testing.T, ctx context.Context, fixture BatchCloserFixture) { + t.Helper() + third := fixture.IssuePrefix + "-mirror-c" + first := fixture.IssuePrefix + "-mirror-a" + second := fixture.IssuePrefix + "-mirror-b" + missing := fixture.IssuePrefix + "-mirror-absent" + seedBatchCloserIssue(t, ctx, fixture, third) + seedBatchCloserIssue(t, ctx, fixture, first) + seedBatchCloserIssue(t, ctx, fixture, second) + + items := []publicops.BatchCloseItem{ + {IssueID: third}, + {IssueID: missing}, + {IssueID: first}, + {IssueID: second}, + } + result, err := fixture.Closer.CloseBatch(ctx, publicops.CloseBatchRequest{Actor: "closer", Items: items}) + if err != nil { + t.Fatalf("CloseBatch with one refused item returned an error of the batch: %v", err) + } + if len(result.Outcomes) != len(items) { + t.Fatalf("outcomes = %d for %d items (%v), want one per item in request order", + len(result.Outcomes), len(items), batchCloserOutcomeIDs(result.Outcomes)) + } + for i, item := range items { + if result.Outcomes[i].IssueID != item.IssueID { + t.Errorf("outcome %d echoes %q, want %q; whole echo was %v", + i, result.Outcomes[i].IssueID, item.IssueID, batchCloserOutcomeIDs(result.Outcomes)) + } + } + if result.Outcomes[1].Err == nil { + t.Errorf("outcome 1 (%s, never seeded) has no error — the refusal was not reported at its own index", missing) + } + for _, i := range []int{0, 2, 3} { + if result.Outcomes[i].Err != nil { + t.Errorf("outcome %d (%s) = %v, want a success beside the refusal", i, items[i].IssueID, result.Outcomes[i].Err) + } + } + // The first of the three nil-ClaimedNext conditions (batchcloser.go:100-103): + // this request asked for no claim at all. + if result.ClaimedNext != nil { + t.Errorf("ClaimedNext = %s for a request with a nil ClaimNext, want nil", result.ClaimedNext.ID) + } +} + +// RunBatchCloserPerItemRefusalIsAResultAndSurvivorsCommit is the central case: +// a batch of [closeable, missing, blocked, open-children, closeable] returns a +// NIL error, one typed refusal per bad item, and durably closes both good ones +// (batchcloser.go:87-91, 111-117). +// +// It also pins the two per-item fields nothing else can (batchcloser.go:5-8, +// 41-42): the two survivors carry DISTINCT reasons and one shared session, and +// both are read back off the rows. An implementation that recorded Items[0]'s +// reason against every issue, or dropped reasons entirely, passes every other +// case in this file. +func RunBatchCloserPerItemRefusalIsAResultAndSurvivorsCommit(t *testing.T, ctx context.Context, fixture BatchCloserFixture) { + t.Helper() + alpha := fixture.IssuePrefix + "-refusal-alpha" + beta := fixture.IssuePrefix + "-refusal-beta" + missing := fixture.IssuePrefix + "-refusal-absent" + blocked := fixture.IssuePrefix + "-refusal-blocked" + blocker := fixture.IssuePrefix + "-refusal-blocker" + parent := fixture.IssuePrefix + "-refusal-parent" + child := fixture.IssuePrefix + "-refusal-child" + seedBatchCloserIssue(t, ctx, fixture, alpha) + seedBatchCloserIssue(t, ctx, fixture, beta) + seedBatchCloserIssue(t, ctx, fixture, blocked) + seedBatchCloserIssue(t, ctx, fixture, blocker) + seedBatchCloserIssue(t, ctx, fixture, parent) + seedBatchCloserIssue(t, ctx, fixture, child) + seedBatchCloserEdge(t, ctx, fixture, blocked, blocker, types.DepBlocks) + seedBatchCloserEdge(t, ctx, fixture, child, parent, types.DepParentChild) + + const session = "refusal-session" + const alphaReason = "alpha finished" + const betaReason = "beta finished" + items := []publicops.BatchCloseItem{ + {IssueID: alpha, Reason: alphaReason}, + {IssueID: missing, Reason: "never seeded"}, + {IssueID: blocked, Reason: "still blocked"}, + {IssueID: parent, Reason: "still has a child"}, + {IssueID: beta, Reason: betaReason}, + } + result, err := fixture.Closer.CloseBatch(ctx, publicops.CloseBatchRequest{ + Actor: "closer", + Items: items, + Session: session, + }) + if err != nil { + t.Fatalf("CloseBatch returned an error of the batch: %v — a per-item refusal is a result, not an error", err) + } + if len(result.Outcomes) != len(items) { + t.Fatalf("outcomes = %d for %d items, want one per item", len(result.Outcomes), len(items)) + } + for i, item := range items { + if result.Outcomes[i].IssueID != item.IssueID { + t.Fatalf("outcome %d echoes %q, want %q", i, result.Outcomes[i].IssueID, item.IssueID) + } + } + + for _, survivor := range []struct { + index int + id string + reason string + }{{0, alpha, alphaReason}, {4, beta, betaReason}} { + outcome := result.Outcomes[survivor.index] + if outcome.Err != nil { + t.Errorf("outcome %d (%s) = %v, want a success: the survivors of a mixed batch commit", survivor.index, survivor.id, outcome.Err) + continue + } + if outcome.Issue == nil { + t.Errorf("outcome %d (%s) has a nil Issue with a nil Err — Issue is nil exactly when Err is set", survivor.index, survivor.id) + continue + } + if !outcome.Changed { + t.Errorf("outcome %d (%s) Changed = false on a first close, want true", survivor.index, survivor.id) + } + if outcome.Issue.Status != types.StatusClosed { + t.Errorf("outcome %d (%s) snapshot status = %q, want %q", survivor.index, survivor.id, outcome.Issue.Status, types.StatusClosed) + } + if outcome.Issue.CloseReason != survivor.reason { + t.Errorf("outcome %d (%s) snapshot CloseReason = %q, want %q — reasons are per item, not per request", + survivor.index, survivor.id, outcome.Issue.CloseReason, survivor.reason) + } + if outcome.Issue.ClosedBySession != session { + t.Errorf("outcome %d (%s) snapshot ClosedBySession = %q, want %q — the session is recorded against every item", + survivor.index, survivor.id, outcome.Issue.ClosedBySession, session) + } + assertBatchCloserClosedRow(t, ctx, fixture, survivor.id, survivor.reason, session) + } + + if !errors.Is(result.Outcomes[1].Err, publicops.ErrNotFound) { + t.Errorf("outcome 1 (%s) = %v, want ErrNotFound", missing, result.Outcomes[1].Err) + } + if !errors.Is(result.Outcomes[2].Err, publicops.ErrCloseBlocked) { + t.Errorf("outcome 2 (%s, blocked by open %s) = %v, want ErrCloseBlocked", blocked, blocker, result.Outcomes[2].Err) + } + var openChildren *publicops.CloseOpenChildrenError + if !errors.As(result.Outcomes[3].Err, &openChildren) { + t.Errorf("outcome 3 (%s, one open child) = %v, want *CloseOpenChildrenError", parent, result.Outcomes[3].Err) + } else { + if openChildren.OpenChildren != 1 { + t.Errorf("open-children refusal for %s carries OpenChildren = %d, want 1", parent, openChildren.OpenChildren) + } + if openChildren.IssueID != parent { + t.Errorf("open-children refusal names %q, want %q", openChildren.IssueID, parent) + } + } + for _, refused := range []int{1, 2, 3} { + if result.Outcomes[refused].Issue != nil { + t.Errorf("outcome %d (%s) carries an Issue beside its Err — Issue is nil exactly when Err is set", + refused, result.Outcomes[refused].IssueID) + } + } + assertBatchCloserStatus(t, ctx, fixture, blocked, types.StatusOpen) + assertBatchCloserStatus(t, ctx, fixture, parent, types.StatusOpen) +} + +// RunBatchCloserOutcomeSnapshotIsTheDocumentedShape pins batchcloser.go:78-80, +// which the bead's case list did not cover: the post-close snapshot carries +// LABELS and DEPENDENCY RECORDS, and COMMENTS ARE OMITTED from it, exactly as +// they are for CloseResult. +// +// Both halves are load-bearing for a caller that prints the outcome instead of +// re-reading the issue. The omission half needs an issue that actually has a +// comment, or it is a claim about an empty thread rather than about the shape. +func RunBatchCloserOutcomeSnapshotIsTheDocumentedShape(t *testing.T, ctx context.Context, fixture BatchCloserFixture) { + t.Helper() + if fixture.AddComment == nil { + t.Fatal("fixture has no AddComment: the comments-omitted half of batchcloser.go:78-80 cannot be told apart from an empty thread") + } + closeable := fixture.IssuePrefix + "-shape-closeable" + target := fixture.IssuePrefix + "-shape-target" + label := batchCloserCaseLabel(fixture, "shape") + seedBatchCloserIssue(t, ctx, fixture, closeable, label) + seedBatchCloserIssue(t, ctx, fixture, target) + // A related edge rather than a blocking one: the snapshot's dependency + // records are the subject here, and a live blocker would refuse the close. + seedBatchCloserEdge(t, ctx, fixture, closeable, target, types.DepRelated) + if err := fixture.AddComment(ctx, closeable, "seed", "a comment the snapshot must omit"); err != nil { + t.Fatalf("seed comment on %s: %v", closeable, err) + } + + result, err := fixture.Closer.CloseBatch(ctx, publicops.CloseBatchRequest{ + Actor: "closer", + Items: []publicops.BatchCloseItem{{IssueID: closeable}}, + }) + if err != nil { + t.Fatalf("CloseBatch: %v", err) + } + outcome := result.Outcomes[0] + if outcome.Err != nil { + t.Fatalf("outcome 0 (%s) = %v, want a success", closeable, outcome.Err) + } + if outcome.Issue == nil { + t.Fatalf("outcome 0 (%s) has a nil Issue with a nil Err", closeable) + } + if len(outcome.Issue.Labels) != 1 || outcome.Issue.Labels[0] != label { + t.Errorf("snapshot labels = %v, want exactly [%s] — the snapshot carries labels", outcome.Issue.Labels, label) + } + if len(outcome.Issue.Dependencies) != 1 { + t.Errorf("snapshot dependency records = %d, want 1 — the snapshot carries dependency records", len(outcome.Issue.Dependencies)) + } else if outcome.Issue.Dependencies[0].DependsOnID != target { + t.Errorf("snapshot dependency record points at %q, want %q", outcome.Issue.Dependencies[0].DependsOnID, target) + } + if len(outcome.Issue.Comments) != 0 { + t.Errorf("snapshot carries %d comments, want none: comments are omitted, as they are for CloseResult", len(outcome.Issue.Comments)) + } +} + +// RunBatchCloserRequestValidationReturnsZeroResultAndChangesNothing pins the +// mutual exclusion of a non-nil error and populated Outcomes +// (batchcloser.go:119-126) across the whole validation vocabulary +// ValidateCloseBatchRequest single-sources +// (internal/storage/issueops/close_batch.go:30-34, which delegates the claim's +// unset-Limit-and-Offset rule to ValidateClaimNextRequest rather than +// restating it). +// +// Every request here names a real, closeable issue, so "no state change" is a +// claim with teeth: a backend that validated after running the closes would +// leave the survivor closed. +func RunBatchCloserRequestValidationReturnsZeroResultAndChangesNothing(t *testing.T, ctx context.Context, fixture BatchCloserFixture) { + t.Helper() + survivor := fixture.IssuePrefix + "-validation-survivor" + seedBatchCloserIssue(t, ctx, fixture, survivor) + limit := 5 + + for _, test := range []struct { + name string + request publicops.CloseBatchRequest + }{ + {"empty items", publicops.CloseBatchRequest{Actor: "closer"}}, + {"empty actor", publicops.CloseBatchRequest{Items: []publicops.BatchCloseItem{{IssueID: survivor}}}}, + {"item with an empty issue id", publicops.CloseBatchRequest{ + Actor: "closer", + Items: []publicops.BatchCloseItem{{IssueID: survivor}, {IssueID: ""}}, + }}, + {"claim carrying a limit", publicops.CloseBatchRequest{ + Actor: "closer", + Items: []publicops.BatchCloseItem{{IssueID: survivor}}, + ClaimNext: &publicops.ReadyRequest{Limit: &limit}, + }}, + {"claim carrying an offset", publicops.CloseBatchRequest{ + Actor: "closer", + Items: []publicops.BatchCloseItem{{IssueID: survivor}}, + ClaimNext: &publicops.ReadyRequest{Offset: 3}, + }}, + } { + result, err := fixture.Closer.CloseBatch(ctx, test.request) + if !errors.Is(err, publicops.ErrValidation) { + t.Errorf("CloseBatch(%s) error = %v, want ErrValidation", test.name, err) + } + if result.Outcomes != nil { + t.Errorf("CloseBatch(%s) returned %d outcomes beside an error — the two are mutually exclusive", + test.name, len(result.Outcomes)) + } + if result.ClaimedNext != nil { + t.Errorf("CloseBatch(%s) returned a claim beside an error — the batch never ran", test.name) + } + assertBatchCloserStatus(t, ctx, fixture, survivor, types.StatusOpen) + } +} + +// RunBatchCloserClaimFilterValueFailureIsARequestValidationFailure pins the +// clause ValidateCloseBatchRequest does NOT single-source: a ClaimNext whose +// filter carries a deterministically bad VALUE rather than a forbidden field. +// +// batchcloser.go:119-126 gives the method's own error exactly three meanings — +// request validation, cancellation and infrastructure — and an invalid sort +// policy is neither of the last two. batchcloser.go:137-140 then says what a +// deterministic request-validation failure looks like: it matches ErrValidation +// and leaves persistent state unchanged. The unset-Limit-and-Offset rule +// already reaches that shape through ValidateClaimNextRequest; this case asks +// the same of the filter's own vocabulary (batchcloser.go:66-69, by reference +// to readyclaimer.go:11-23 and reader.go:78-83, which name the three legal +// policies). +// +// The item is real and closeable, so "changes nothing" has teeth: a backend +// that translated the filter after running the closes would leave it closed. +func RunBatchCloserClaimFilterValueFailureIsARequestValidationFailure(t *testing.T, ctx context.Context, fixture BatchCloserFixture) { + t.Helper() + closeable := fixture.IssuePrefix + "-badsort-closeable" + candidate := fixture.IssuePrefix + "-badsort-candidate" + label := batchCloserCaseLabel(fixture, "badsort") + seedBatchCloserIssue(t, ctx, fixture, closeable) + // A row the claim would have won had the filter been legal, so a backend + // that ran the claim anyway is caught by the assignee read rather than only + // by the nil ClaimedNext it also owes. + seedBatchCloserIssue(t, ctx, fixture, candidate, label) + + result, err := fixture.Closer.CloseBatch(ctx, publicops.CloseBatchRequest{ + Actor: "closer", + Items: []publicops.BatchCloseItem{{IssueID: closeable}}, + ClaimNext: &publicops.ReadyRequest{ + Labels: []string{label}, + Sort: "bogus", + }, + }) + if !errors.Is(err, publicops.ErrValidation) { + t.Errorf("CloseBatch with ClaimNext.Sort = %q error = %v, want ErrValidation: the method's own error is request validation, cancellation or infrastructure, and a bad sort policy is the first", + "bogus", err) + } + if result.Outcomes != nil { + t.Errorf("CloseBatch with an invalid sort returned %d outcomes beside its error — the two are mutually exclusive", len(result.Outcomes)) + } + if result.ClaimedNext != nil { + t.Errorf("CloseBatch with an invalid sort returned a claim beside its error — the batch never ran") + } + assertBatchCloserStatus(t, ctx, fixture, closeable, types.StatusOpen) + if got := batchCloserAssignee(t, ctx, fixture, candidate); got != "" { + t.Errorf("durable assignee of the eligible %s = %q, want it untouched: a refused request changes nothing", candidate, got) + } +} + +// RunBatchCloserBackendFailureReturnsNoOutcomes pins the other half of +// batchcloser.go:119-126: a failure that means the batch NEVER RAN reports no +// outcomes and leaves no durable trace, so a caller that sees an error never +// has to wonder which prefix of its list got through. +// +// The failure is induced with an already-canceled context, the house +// precedent for "make the backend fail without destroying the fixture" +// (conformance/reader_contract.go:761-763): every backend has to begin a +// transaction before it can close anything, so the failure lands underneath the +// batch rather than inside one item. What is asserted is the RESULT shape and +// the untouched row — the error's spelling is each backend's own, and the +// in-transaction claim-failure path this stands in for cannot be reached from +// these fixtures at all (every deterministic claim failure is rejected before +// the transaction). +func RunBatchCloserBackendFailureReturnsNoOutcomes(t *testing.T, ctx context.Context, fixture BatchCloserFixture) { + t.Helper() + closeable := fixture.IssuePrefix + "-deadctx-closeable" + seedBatchCloserIssue(t, ctx, fixture, closeable) + + dead, cancel := context.WithCancel(ctx) + cancel() + result, err := fixture.Closer.CloseBatch(dead, publicops.CloseBatchRequest{ + Actor: "closer", + Items: []publicops.BatchCloseItem{{IssueID: closeable}}, + }) + if err == nil { + t.Fatalf("CloseBatch on a dead context returned %d outcomes and no error — the failure was not induced, so this case proves nothing", + len(result.Outcomes)) + } + if result.Outcomes != nil { + t.Errorf("CloseBatch that failed returned %d outcomes beside its error (%v) — a non-nil error and populated Outcomes are mutually exclusive", + len(result.Outcomes), err) + } + if result.ClaimedNext != nil { + t.Errorf("CloseBatch that failed returned a claim beside its error (%v)", err) + } + // Read back on the LIVE context: the assertion is about the row, not about + // the dead context's reach. + assertBatchCloserStatus(t, ctx, fixture, closeable, types.StatusOpen) +} + +// RunBatchCloserIdempotentRecloseIsAPerItemSuccess pins batchcloser.go:81-86. +// A re-close is not a refusal — an agent that retries a batch after a partial +// failure must not have the already-done items reported as errors — and +// OpenChildren is still observed on the second pass, which is what lets a +// forced re-close report the same warning the first one did. +// +// The claim and history consequences of an ALL-idempotent batch are pinned by +// RunBatchCloserAllIdempotentBatchLandsNothing, which is where "landed means +// Changed" (batchcloser.go:55-64, 119-122) is asserted. +// +// This is the ACROSS-request re-close; the WITHIN-request one, [a, a], is +// RunBatchCloserDuplicateItemRecloseAtItsOwnIndex. +func RunBatchCloserIdempotentRecloseIsAPerItemSuccess(t *testing.T, ctx context.Context, fixture BatchCloserFixture) { + t.Helper() + plain := fixture.IssuePrefix + "-reclose-plain" + parent := fixture.IssuePrefix + "-reclose-parent" + child := fixture.IssuePrefix + "-reclose-child" + seedBatchCloserIssue(t, ctx, fixture, plain) + seedBatchCloserIssue(t, ctx, fixture, parent) + seedBatchCloserIssue(t, ctx, fixture, child) + seedBatchCloserEdge(t, ctx, fixture, child, parent, types.DepParentChild) + + // Force, because an open child refuses an unforced close of a CLOSED target + // just as it refuses an open one; the reported count is the point here. + request := publicops.CloseBatchRequest{ + Actor: "closer", + Items: []publicops.BatchCloseItem{{IssueID: plain}, {IssueID: parent}}, + Force: true, + } + first, err := fixture.Closer.CloseBatch(ctx, request) + if err != nil { + t.Fatalf("first CloseBatch: %v", err) + } + for i, outcome := range first.Outcomes { + if outcome.Err != nil { + t.Fatalf("first close outcome %d (%s) = %v, want a success", i, outcome.IssueID, outcome.Err) + } + if !outcome.Changed { + t.Errorf("first close outcome %d (%s) Changed = false, want true", i, outcome.IssueID) + } + } + if first.Outcomes[1].OpenChildren != 1 { + t.Errorf("forced close of %s reports OpenChildren = %d, want 1", parent, first.Outcomes[1].OpenChildren) + } + + second, err := fixture.Closer.CloseBatch(ctx, request) + if err != nil { + t.Fatalf("re-close CloseBatch returned an error of the batch: %v — an idempotent re-close is a success", err) + } + for i, outcome := range second.Outcomes { + if outcome.Err != nil { + t.Errorf("re-close outcome %d (%s) = %v, want a per-item success", i, outcome.IssueID, outcome.Err) + continue + } + if outcome.Issue == nil { + t.Errorf("re-close outcome %d (%s) has a nil Issue with a nil Err", i, outcome.IssueID) + } + if outcome.Changed { + t.Errorf("re-close outcome %d (%s) Changed = true, want false: nothing was mutated", i, outcome.IssueID) + } + } + if second.Outcomes[1].OpenChildren != 1 { + t.Errorf("forced re-close of %s reports OpenChildren = %d, want 1 — it is reported even for an idempotent re-close", + parent, second.Outcomes[1].OpenChildren) + } +} + +// RunBatchCloserAllIdempotentBatchLandsNothing pins the two consequences of +// "CHANGED IS THE TEST" (batchcloser.go:55-64, 119-122): a batch whose items were +// all already closed mutated nothing, so it earns NO claim and records NO +// history entry. +// +// The claim half is the one with teeth. The candidate is ready, carries the +// case's label and would be won by an identical request that closed something — +// RunBatchCloserClaimNextHydratesWhenSomethingClosed is that request — so only +// the coupling keeps it unassigned, and an implementation that counted a nil +// per-item Err as a landing hands out a claim the caller never earned. +func RunBatchCloserAllIdempotentBatchLandsNothing(t *testing.T, ctx context.Context, fixture BatchCloserFixture) { + t.Helper() + requireBatchCloserHistory(t, fixture) + closeable := fixture.IssuePrefix + "-allidem-closeable" + candidate := fixture.IssuePrefix + "-allidem-candidate" + label := batchCloserCaseLabel(fixture, "allidem") + seedBatchCloserIssue(t, ctx, fixture, closeable) + seedBatchCloserIssue(t, ctx, fixture, candidate, label) + + first, err := fixture.Closer.CloseBatch(ctx, publicops.CloseBatchRequest{ + Actor: "closer", + Items: []publicops.BatchCloseItem{{IssueID: closeable}}, + }) + if err != nil { + t.Fatalf("first CloseBatch: %v", err) + } + if first.Outcomes[0].Err != nil { + t.Fatalf("first close of %s = %v, want it to land — the re-close below has nothing to be idempotent about otherwise", + closeable, first.Outcomes[0].Err) + } + + before, err := fixture.CountHistory(ctx) + if err != nil { + t.Fatalf("CountHistory before the re-close: %v", err) + } + second, err := fixture.Closer.CloseBatch(ctx, publicops.CloseBatchRequest{ + Actor: "claimer", + Items: []publicops.BatchCloseItem{{IssueID: closeable}}, + ClaimNext: batchCloserClaimFor(label), + }) + if err != nil { + t.Fatalf("all-idempotent CloseBatch returned an error of the batch: %v — a re-close is a per-item success", err) + } + if second.Outcomes[0].Err != nil { + t.Fatalf("re-close outcome 0 (%s) = %v, want a per-item success", closeable, second.Outcomes[0].Err) + } + if second.Outcomes[0].Changed { + t.Fatalf("re-close outcome 0 (%s) Changed = true, want false — this case is about a batch that mutated nothing", closeable) + } + if second.ClaimedNext != nil { + t.Errorf("ClaimedNext = %s after a batch whose only item was already closed, want nil: landed means Changed, and a claim handed out by a request that closed nothing is one the caller never earned", + second.ClaimedNext.ID) + } + if got := batchCloserAssignee(t, ctx, fixture, candidate); got != "" { + t.Errorf("durable assignee of the eligible %s = %q, want it untouched", candidate, got) + } + after, err := fixture.CountHistory(ctx) + if err != nil { + t.Fatalf("CountHistory after the re-close: %v", err) + } + if after != before { + t.Errorf("history entries went %d -> %d across a batch whose items were all already closed, want no change: none at all when nothing landed", + before, after) + } +} + +// RunBatchCloserDuplicateItemRecloseAtItsOwnIndex pins what the SECOND +// occurrence of a duplicated id reports (batchcloser.go:28-33): the index +// correspondence is promised for every item, so [a, a] gets two outcomes, and +// the second is the intra-batch re-close the first made — a per-item success +// with Changed false. `bd close a b a` is a plausible typo and it is not a +// refusal. +// +// The two occurrences carry DISTINCT reasons, which is the half a caller can +// observe on the row: the first occurrence's reason is what the close wrote, +// and the second changed nothing, so it wrote nothing. +func RunBatchCloserDuplicateItemRecloseAtItsOwnIndex(t *testing.T, ctx context.Context, fixture BatchCloserFixture) { + t.Helper() + requireBatchCloserHistory(t, fixture) + duplicated := fixture.IssuePrefix + "-dup-target" + seedBatchCloserIssue(t, ctx, fixture, duplicated) + + const session = "dup-session" + const firstReason = "the occurrence that closed it" + const secondReason = "the occurrence that found it closed" + before, err := fixture.CountHistory(ctx) + if err != nil { + t.Fatalf("CountHistory before: %v", err) + } + result, err := fixture.Closer.CloseBatch(ctx, publicops.CloseBatchRequest{ + Actor: "closer", + Session: session, + Items: []publicops.BatchCloseItem{ + {IssueID: duplicated, Reason: firstReason}, + {IssueID: duplicated, Reason: secondReason}, + }, + }) + if err != nil { + t.Fatalf("CloseBatch naming the same id twice returned an error of the batch: %v — a duplicate is not a request-validation failure", err) + } + if len(result.Outcomes) != 2 { + t.Fatalf("outcomes = %d for 2 items (%v), want one per item: every item appears in Outcomes at the same index", + len(result.Outcomes), batchCloserOutcomeIDs(result.Outcomes)) + } + for i, outcome := range result.Outcomes { + if outcome.IssueID != duplicated { + t.Fatalf("outcome %d echoes %q, want %q", i, outcome.IssueID, duplicated) + } + if outcome.Err != nil { + t.Fatalf("outcome %d (%s) = %v, want a per-item success at both indices", i, duplicated, outcome.Err) + } + } + if !result.Outcomes[0].Changed { + t.Errorf("outcome 0 (%s) Changed = false, want true — the first occurrence is the one that closed it", duplicated) + } + if result.Outcomes[1].Changed { + t.Errorf("outcome 1 (%s) Changed = true, want false — the second occurrence is an idempotent re-close of the first", duplicated) + } + assertBatchCloserClosedRow(t, ctx, fixture, duplicated, firstReason, session) + after, err := fixture.CountHistory(ctx) + if err != nil { + t.Fatalf("CountHistory after: %v", err) + } + if after != before+1 { + t.Errorf("history entries went %d -> %d across a batch naming one id twice, want exactly one more", before, after) + } +} + +// RunBatchCloserWispItemClosesAndEarnsTheClaim pins the two admissibility +// halves of the ephemeral rules (batchcloser.go:35-39): a WISP id is an +// admissible batch item, and closing one is real work landing, so it counts +// toward "at least one item closed" and the request earns its claim. +// +// The batch closes NOTHING durable, which is what makes the claim half a claim +// about the wisp rather than about a durable sibling carrying it. +func RunBatchCloserWispItemClosesAndEarnsTheClaim(t *testing.T, ctx context.Context, fixture BatchCloserFixture) { + t.Helper() + requireBatchCloserWisps(t, fixture) + wisp := fixture.IssuePrefix + "-wispclaim-wisp" + candidate := fixture.IssuePrefix + "-wispclaim-candidate" + label := batchCloserCaseLabel(fixture, "wispclaim") + seedBatchCloserWisp(t, ctx, fixture, wisp) + seedBatchCloserIssue(t, ctx, fixture, candidate, label) + + result, err := fixture.Closer.CloseBatch(ctx, publicops.CloseBatchRequest{ + Actor: "claimer", + Items: []publicops.BatchCloseItem{{IssueID: wisp}}, + ClaimNext: batchCloserClaimFor(label), + }) + if err != nil { + t.Fatalf("CloseBatch of a wisp returned an error of the batch: %v — a wisp id is an admissible item", err) + } + if result.Outcomes[0].Err != nil { + t.Fatalf("outcome 0 (%s, a wisp) = %v, want a success", wisp, result.Outcomes[0].Err) + } + if !result.Outcomes[0].Changed { + t.Errorf("outcome 0 (%s) Changed = false on a first close, want true", wisp) + } + assertBatchCloserWispStatus(t, ctx, fixture, wisp, types.StatusClosed) + if result.ClaimedNext == nil { + t.Fatalf("ClaimedNext is nil after a batch that closed the wisp %s with %s ready under label %q — closing a wisp is real work landing", + wisp, candidate, label) + } + if result.ClaimedNext.ID != candidate { + t.Errorf("ClaimedNext = %s, want the only row under label %q, %s", result.ClaimedNext.ID, label, candidate) + } + if got := batchCloserAssignee(t, ctx, fixture, candidate); got != "claimer" { + t.Errorf("durable assignee of %s = %q, want %q — the claim committed", candidate, got, "claimer") + } +} + +// RunBatchCloserDurableHistoryNeverNamesAWisp pins the third ephemeral rule +// (batchcloser.go:128-135), and it is the one with a federation consequence: a +// mixed batch records ONE durable entry, and that entry names the durable id +// alone. +// +// The wisp tables are dolt-ignored so ephemeral work never ships; an entry +// naming a wisp is exactly the sync artifact ignoring them exists to prevent. +// Asserting that the durable id IS newly named keeps the wisp assertion from +// passing vacuously against a batch that recorded nothing at all. +// +// Both id counts are DELTAS, because seeding an issue records an entry naming +// it too — the totals answer "who has ever been named", and the question here +// is what THIS batch shipped. +func RunBatchCloserDurableHistoryNeverNamesAWisp(t *testing.T, ctx context.Context, fixture BatchCloserFixture) { + t.Helper() + requireBatchCloserWisps(t, fixture) + requireBatchCloserHistory(t, fixture) + durable := fixture.IssuePrefix + "-wisphistory-durable" + wisp := fixture.IssuePrefix + "-wisphistory-wisp" + seedBatchCloserIssue(t, ctx, fixture, durable) + seedBatchCloserWisp(t, ctx, fixture, wisp) + + before, err := fixture.CountHistory(ctx) + if err != nil { + t.Fatalf("CountHistory before: %v", err) + } + namingDurableBefore := batchCloserHistoryEntriesNaming(t, ctx, fixture, durable) + namingWispBefore := batchCloserHistoryEntriesNaming(t, ctx, fixture, wisp) + result, err := fixture.Closer.CloseBatch(ctx, publicops.CloseBatchRequest{ + Actor: "closer", + Items: []publicops.BatchCloseItem{{IssueID: durable}, {IssueID: wisp}}, + }) + if err != nil { + t.Fatalf("mixed-plane CloseBatch: %v", err) + } + for i, outcome := range result.Outcomes { + if outcome.Err != nil { + t.Fatalf("outcome %d (%s) = %v, want both planes to land", i, outcome.IssueID, outcome.Err) + } + } + after, err := fixture.CountHistory(ctx) + if err != nil { + t.Fatalf("CountHistory after: %v", err) + } + if after != before+1 { + t.Fatalf("history entries went %d -> %d across a mixed-plane batch, want exactly one more", before, after) + } + if got := batchCloserHistoryEntriesNaming(t, ctx, fixture, durable); got != namingDurableBefore+1 { + t.Errorf("entries naming the durable %s went %d -> %d, want exactly one more — the wisp assertion below is vacuous otherwise", + durable, namingDurableBefore, got) + } + if got := batchCloserHistoryEntriesNaming(t, ctx, fixture, wisp); got != namingWispBefore { + t.Errorf("entries naming the wisp %s went %d -> %d, want no change: the wisp tables are dolt-ignored so ephemeral work never ships, and an entry naming one is the sync artifact ignoring them exists to prevent", + wisp, namingWispBefore, got) + } +} + +// RunBatchCloserForceBypassesOnlyClosePolicy pins batchcloser.go:43-46. Force +// is request-wide, so both policy refusals of the mixed batch land; it is not +// a blanket override, so the id that does not exist still refuses and an invalid +// request is still invalid. +// +// The same clause says force would not bypass a per-item LIFECYCLE +// PRECONDITION either, and the doc says that category is EMPTY today. That is +// the one half no request can exercise, so it is asserted against the request +// TYPE instead — see assertBatchCloserCarriesNoPrecondition below. +func RunBatchCloserForceBypassesOnlyClosePolicy(t *testing.T, ctx context.Context, fixture BatchCloserFixture) { + t.Helper() + assertBatchCloserCarriesNoPrecondition(t) + blocked := fixture.IssuePrefix + "-force-blocked" + blocker := fixture.IssuePrefix + "-force-blocker" + parent := fixture.IssuePrefix + "-force-parent" + child := fixture.IssuePrefix + "-force-child" + missing := fixture.IssuePrefix + "-force-absent" + seedBatchCloserIssue(t, ctx, fixture, blocked) + seedBatchCloserIssue(t, ctx, fixture, blocker) + seedBatchCloserIssue(t, ctx, fixture, parent) + seedBatchCloserIssue(t, ctx, fixture, child) + seedBatchCloserEdge(t, ctx, fixture, blocked, blocker, types.DepBlocks) + seedBatchCloserEdge(t, ctx, fixture, child, parent, types.DepParentChild) + + result, err := fixture.Closer.CloseBatch(ctx, publicops.CloseBatchRequest{ + Actor: "closer", + Items: []publicops.BatchCloseItem{{IssueID: blocked}, {IssueID: missing}, {IssueID: parent}}, + Force: true, + }) + if err != nil { + t.Fatalf("forced CloseBatch: %v", err) + } + if len(result.Outcomes) != 3 { + t.Fatalf("outcomes = %d, want 3", len(result.Outcomes)) + } + if result.Outcomes[0].Err != nil { + t.Errorf("forced close of the blocked %s = %v, want it to land: force bypasses blocker policy", blocked, result.Outcomes[0].Err) + } + if !errors.Is(result.Outcomes[1].Err, publicops.ErrNotFound) { + t.Errorf("forced close of the absent %s = %v, want ErrNotFound: force bypasses policy, not existence", missing, result.Outcomes[1].Err) + } + if result.Outcomes[2].Err != nil { + t.Errorf("forced close of the parent %s = %v, want it to land: force bypasses open-child policy", parent, result.Outcomes[2].Err) + } else if result.Outcomes[2].OpenChildren != 1 { + t.Errorf("forced close of %s reports OpenChildren = %d, want 1", parent, result.Outcomes[2].OpenChildren) + } + assertBatchCloserStatus(t, ctx, fixture, blocked, types.StatusClosed) + assertBatchCloserStatus(t, ctx, fixture, parent, types.StatusClosed) + assertBatchCloserStatus(t, ctx, fixture, child, types.StatusOpen) + + // The other half of the clause: force never bypasses validation. + invalid, err := fixture.Closer.CloseBatch(ctx, publicops.CloseBatchRequest{ + Actor: "closer", + Items: []publicops.BatchCloseItem{{IssueID: blocker}, {IssueID: ""}}, + Force: true, + }) + if !errors.Is(err, publicops.ErrValidation) { + t.Errorf("forced CloseBatch with an empty item id = %v, want ErrValidation", err) + } + if invalid.Outcomes != nil { + t.Errorf("forced CloseBatch with an empty item id returned %d outcomes beside its error", len(invalid.Outcomes)) + } + assertBatchCloserStatus(t, ctx, fixture, blocker, types.StatusOpen) +} + +// RunBatchCloserClaimNextHydratesWhenSomethingClosed is case (a) of the claim +// coupling (batchcloser.go:55-58, 100-103): a request that closed something and +// asked for a claim gets one. +// +// It does not re-pin what a claim DOES to the row it wins beyond the +// assignment — that is ReadyClaimer's own contract, referenced rather than +// restated at batchcloser.go:66-69, and restating it here is how the two come +// apart. +func RunBatchCloserClaimNextHydratesWhenSomethingClosed(t *testing.T, ctx context.Context, fixture BatchCloserFixture) { + t.Helper() + closeable := fixture.IssuePrefix + "-claimhit-closeable" + candidate := fixture.IssuePrefix + "-claimhit-candidate" + dependent := fixture.IssuePrefix + "-claimhit-dependent" + label := batchCloserCaseLabel(fixture, "claimhit") + seedBatchCloserIssue(t, ctx, fixture, closeable) + seedBatchCloserIssue(t, ctx, fixture, candidate, label) + // One issue blocked BY the candidate, so "hydrated with its cardinalities" + // is a claim about a nonzero number rather than about a zero value. The + // dependent carries no label and is blocked, so it is never a rival for + // the claim. + seedBatchCloserIssue(t, ctx, fixture, dependent) + seedBatchCloserEdge(t, ctx, fixture, dependent, candidate, types.DepBlocks) + + result, err := fixture.Closer.CloseBatch(ctx, publicops.CloseBatchRequest{ + Actor: "claimer", + Items: []publicops.BatchCloseItem{{IssueID: closeable}}, + ClaimNext: batchCloserClaimFor(label), + }) + if err != nil { + t.Fatalf("CloseBatch with a claim: %v", err) + } + if result.Outcomes[0].Err != nil { + t.Fatalf("the close the claim is earned by refused: %v", result.Outcomes[0].Err) + } + if result.ClaimedNext == nil { + t.Fatalf("ClaimedNext is nil after a batch that closed %s with %s ready under label %q", closeable, candidate, label) + } + if result.ClaimedNext.Issue == nil { + t.Fatalf("ClaimedNext carries a nil Issue") + } + if result.ClaimedNext.ID != candidate { + t.Errorf("ClaimedNext = %s, want the only row under label %q, %s", result.ClaimedNext.ID, label, candidate) + } + if result.ClaimedNext.Assignee != "claimer" { + t.Errorf("ClaimedNext assignee = %q, want the batch's actor %q", result.ClaimedNext.Assignee, "claimer") + } + if result.ClaimedNext.DependentCount != 1 { + t.Errorf("ClaimedNext DependentCount = %d, want 1 — the row is hydrated with its cardinalities, not returned bare", + result.ClaimedNext.DependentCount) + } + if got := batchCloserAssignee(t, ctx, fixture, candidate); got != "claimer" { + t.Errorf("durable assignee of %s = %q, want %q — the claim committed with the closes", candidate, got, "claimer") + } +} + +// RunBatchCloserClaimNextIsNilWhenNothingClosed is case (b), and it is the one +// the doc argues for in prose (batchcloser.go:55-58): a claim handed out by a +// request that closed nothing would be a claim the caller never earned. The +// candidate is ready and matches the filter, so only the coupling keeps it +// unclaimed. +func RunBatchCloserClaimNextIsNilWhenNothingClosed(t *testing.T, ctx context.Context, fixture BatchCloserFixture) { + t.Helper() + missing := fixture.IssuePrefix + "-claimnone-absent" + candidate := fixture.IssuePrefix + "-claimnone-candidate" + label := batchCloserCaseLabel(fixture, "claimnone") + seedBatchCloserIssue(t, ctx, fixture, candidate, label) + + result, err := fixture.Closer.CloseBatch(ctx, publicops.CloseBatchRequest{ + Actor: "claimer", + Items: []publicops.BatchCloseItem{{IssueID: missing}}, + ClaimNext: batchCloserClaimFor(label), + }) + if err != nil { + t.Fatalf("CloseBatch whose only item refused returned an error of the batch: %v", err) + } + if !errors.Is(result.Outcomes[0].Err, publicops.ErrNotFound) { + t.Fatalf("outcome 0 (%s) = %v, want ErrNotFound", missing, result.Outcomes[0].Err) + } + if result.ClaimedNext != nil { + t.Errorf("ClaimedNext = %s after a batch that closed nothing, want nil", result.ClaimedNext.ID) + } + if got := batchCloserAssignee(t, ctx, fixture, candidate); got != "" { + t.Errorf("durable assignee of the eligible %s = %q, want it untouched", candidate, got) + } +} + +// RunBatchCloserClaimNextIsNilWhenTheFrontIsEmpty is case (c) +// (batchcloser.go:100-103, by reference to readyclaimer.go:32-36): an empty +// front is a normal outcome, not an error, so the closes still land and the +// batch still succeeds. Nothing carries the case's label, so the front the +// claim looks at is empty by construction rather than by luck. +func RunBatchCloserClaimNextIsNilWhenTheFrontIsEmpty(t *testing.T, ctx context.Context, fixture BatchCloserFixture) { + t.Helper() + closeable := fixture.IssuePrefix + "-claimempty-closeable" + label := batchCloserCaseLabel(fixture, "claimempty") + seedBatchCloserIssue(t, ctx, fixture, closeable) + + result, err := fixture.Closer.CloseBatch(ctx, publicops.CloseBatchRequest{ + Actor: "claimer", + Items: []publicops.BatchCloseItem{{IssueID: closeable}}, + ClaimNext: batchCloserClaimFor(label), + }) + if err != nil { + t.Fatalf("CloseBatch whose claim found nothing returned an error: %v — an empty front is a normal outcome", err) + } + if result.Outcomes[0].Err != nil { + t.Errorf("outcome 0 (%s) = %v, want the close to land regardless of the claim", closeable, result.Outcomes[0].Err) + } + if !result.Outcomes[0].Changed { + t.Errorf("outcome 0 (%s) Changed = false, want true", closeable) + } + if result.ClaimedNext != nil { + t.Errorf("ClaimedNext = %s with nothing eligible under label %q, want nil", result.ClaimedNext.ID, label) + } + assertBatchCloserStatus(t, ctx, fixture, closeable, types.StatusClosed) +} + +// RunBatchCloserClaimNextSeesAnUnblockingFromItsOwnBatch is case (d), and the +// only case that can tell "runs after the closes inside the same transaction" +// (batchcloser.go:143-146) from "runs in the same call": the candidate's ONLY +// blocker is an item of the batch, so it is claimable by this request's claim +// and by nothing that ran before it. +// +// The control batch is what makes that a proof rather than a coincidence. It +// closes an unrelated issue with the identical claim, and must come back +// empty; only when the blocker itself is in the batch does the same claim win +// the row. An implementation that ran its claim against a snapshot taken +// before the closes passes the control and fails the real one. +func RunBatchCloserClaimNextSeesAnUnblockingFromItsOwnBatch(t *testing.T, ctx context.Context, fixture BatchCloserFixture) { + t.Helper() + blocker := fixture.IssuePrefix + "-claimunblock-blocker" + candidate := fixture.IssuePrefix + "-claimunblock-candidate" + unrelated := fixture.IssuePrefix + "-claimunblock-unrelated" + label := batchCloserCaseLabel(fixture, "claimunblock") + seedBatchCloserIssue(t, ctx, fixture, blocker) + seedBatchCloserIssue(t, ctx, fixture, unrelated) + seedBatchCloserIssue(t, ctx, fixture, candidate, label) + seedBatchCloserEdge(t, ctx, fixture, candidate, blocker, types.DepBlocks) + + if blocked := batchCloserIsBlocked(t, ctx, fixture, candidate); blocked != 1 { + t.Fatalf("is_blocked of %s = %d before the batch, want 1 — the seed did not block the candidate, so this case would pass vacuously", + candidate, blocked) + } + + control, err := fixture.Closer.CloseBatch(ctx, publicops.CloseBatchRequest{ + Actor: "claimer", + Items: []publicops.BatchCloseItem{{IssueID: unrelated}}, + ClaimNext: batchCloserClaimFor(label), + }) + if err != nil { + t.Fatalf("control CloseBatch: %v", err) + } + if control.ClaimedNext != nil { + t.Fatalf("control batch claimed %s while its blocker %s was still open — the candidate was not actually blocked", + control.ClaimedNext.ID, blocker) + } + + result, err := fixture.Closer.CloseBatch(ctx, publicops.CloseBatchRequest{ + Actor: "claimer", + Items: []publicops.BatchCloseItem{{IssueID: blocker}}, + ClaimNext: batchCloserClaimFor(label), + }) + if err != nil { + t.Fatalf("CloseBatch closing the blocker with a claim: %v", err) + } + if result.Outcomes[0].Err != nil { + t.Fatalf("closing the blocker %s refused: %v", blocker, result.Outcomes[0].Err) + } + if result.ClaimedNext == nil { + t.Fatalf("ClaimedNext is nil after the same request closed %s, the candidate's only blocker — the claim did not run after the closes", + blocker) + } + if result.ClaimedNext.ID != candidate { + t.Errorf("ClaimedNext = %s, want %s", result.ClaimedNext.ID, candidate) + } + if got := batchCloserAssignee(t, ctx, fixture, candidate); got != "claimer" { + t.Errorf("durable assignee of %s = %q, want %q — the unblocking and the claim committed together", candidate, got, "claimer") + } +} + +// RunBatchCloserRecordsOneHistoryEntryForWhatLanded pins the first half of +// batchcloser.go:119-122. N closes are ONE transaction and ONE entry, which is +// the entire reason a batch exists rather than a loop over Lifecycle.Close. +func RunBatchCloserRecordsOneHistoryEntryForWhatLanded(t *testing.T, ctx context.Context, fixture BatchCloserFixture) { + t.Helper() + requireBatchCloserHistory(t, fixture) + first := fixture.IssuePrefix + "-history-a" + second := fixture.IssuePrefix + "-history-b" + seedBatchCloserIssue(t, ctx, fixture, first) + seedBatchCloserIssue(t, ctx, fixture, second) + + before, err := fixture.CountHistory(ctx) + if err != nil { + t.Fatalf("CountHistory before: %v", err) + } + result, err := fixture.Closer.CloseBatch(ctx, publicops.CloseBatchRequest{ + Actor: "closer", + Items: []publicops.BatchCloseItem{{IssueID: first}, {IssueID: second}}, + }) + if err != nil { + t.Fatalf("CloseBatch: %v", err) + } + for i, outcome := range result.Outcomes { + if outcome.Err != nil { + t.Fatalf("outcome %d (%s) = %v, want both to land", i, outcome.IssueID, outcome.Err) + } + } + after, err := fixture.CountHistory(ctx) + if err != nil { + t.Fatalf("CountHistory after: %v", err) + } + if after != before+1 { + t.Errorf("history entries went %d -> %d across a batch closing two issues, want exactly one more: what lands is one transaction and at most one entry", + before, after) + } +} + +// RunBatchCloserAllRefusedBatchRecordsNoHistory pins the second half of +// batchcloser.go:119-122: none at all when nothing landed. A batch of typos must +// not leave a commit behind. +func RunBatchCloserAllRefusedBatchRecordsNoHistory(t *testing.T, ctx context.Context, fixture BatchCloserFixture) { + t.Helper() + requireBatchCloserHistory(t, fixture) + missing := fixture.IssuePrefix + "-nohistory-absent" + blocked := fixture.IssuePrefix + "-nohistory-blocked" + blocker := fixture.IssuePrefix + "-nohistory-blocker" + seedBatchCloserIssue(t, ctx, fixture, blocked) + seedBatchCloserIssue(t, ctx, fixture, blocker) + seedBatchCloserEdge(t, ctx, fixture, blocked, blocker, types.DepBlocks) + + before, err := fixture.CountHistory(ctx) + if err != nil { + t.Fatalf("CountHistory before: %v", err) + } + result, err := fixture.Closer.CloseBatch(ctx, publicops.CloseBatchRequest{ + Actor: "closer", + Items: []publicops.BatchCloseItem{{IssueID: missing}, {IssueID: blocked}}, + }) + if err != nil { + t.Fatalf("all-refused CloseBatch returned an error of the batch: %v", err) + } + for i, outcome := range result.Outcomes { + if outcome.Err == nil { + t.Fatalf("outcome %d (%s) landed, want every item refused for this case to mean anything", i, outcome.IssueID) + } + } + after, err := fixture.CountHistory(ctx) + if err != nil { + t.Fatalf("CountHistory after: %v", err) + } + if after != before { + t.Errorf("history entries went %d -> %d across a batch that landed nothing, want no change", before, after) + } + assertBatchCloserStatus(t, ctx, fixture, blocked, types.StatusOpen) +} + +// RunBatchCloserDoesNotMutateTheCallerRequest pins batchcloser.go:137-140. +// Validation and normalization apply to attempt-local clones, so the caller's +// struct — its Items slice and the ReadyRequest its ClaimNext points at, both +// carrying values normalization would visibly rewrite — is byte-identical +// afterwards, and the pointer itself is not swapped. +func RunBatchCloserDoesNotMutateTheCallerRequest(t *testing.T, ctx context.Context, fixture BatchCloserFixture) { + t.Helper() + closeable := fixture.IssuePrefix + "-snapshot-closeable" + candidate := fixture.IssuePrefix + "-snapshot-candidate" + label := batchCloserCaseLabel(fixture, "snapshot") + seedBatchCloserIssue(t, ctx, fixture, closeable) + seedBatchCloserIssue(t, ctx, fixture, candidate, label) + + // Two independently built copies of the same request: the slices and the + // ClaimNext pointee are distinct allocations, so an in-place normalization + // shows up as a difference rather than mutating both sides of the compare. + // The label sets are deliberately padded and duplicated, which is exactly + // what workapi.BuildReadyFilter's normalization rewrites. + build := func() publicops.CloseBatchRequest { + priority := 2 + return publicops.CloseBatchRequest{ + Actor: "closer", + Session: "snapshot-session", + Items: []publicops.BatchCloseItem{ + {IssueID: closeable, Reason: "snapshot reason"}, + }, + ClaimNext: &publicops.ReadyRequest{ + Labels: []string{" " + label + " ", label}, + ExcludeLabels: []string{" " + label + "-excluded "}, + ExcludeTypes: []string{" chore , chore "}, + Priority: &priority, + Sort: "priority", + }, + } + } + request := build() + want := build() + claim := request.ClaimNext + + result, err := fixture.Closer.CloseBatch(ctx, request) + if err != nil { + t.Fatalf("CloseBatch: %v", err) + } + // The close has to LAND, or the claim never runs and the normalization + // this case is watching for never happens. + if result.Outcomes[0].Err != nil { + t.Fatalf("outcome 0 (%s) = %v; the claim path only runs when something closed", closeable, result.Outcomes[0].Err) + } + if request.ClaimNext != claim { + t.Errorf("CloseBatch replaced the caller's ClaimNext pointer") + } + if !reflect.DeepEqual(request, want) { + t.Errorf("CloseBatch mutated the caller's request:\n got %+v\nwant %+v\n got claim %+v\nwant claim %+v", + request, want, request.ClaimNext, want.ClaimNext) + } +} + +// assertBatchCloserCarriesNoPrecondition holds the emptiness the force clause +// depends on (batchcloser.go:43-53): neither the request nor an item carries a +// per-item precondition, so "force never bypasses a lifecycle precondition" +// governs nothing a caller can send. +// +// A promise with no reachable member is one a future reader will try to test +// and cannot, so the claim is made falsifiable HERE rather than left as prose. +// Expected* is the house spelling for a precondition — Lifecycle's +// ExpectedVersion, Update's ExpectedAssignee and ExpectedStatus — so the day a +// batch grows one, this fails and the doc's "the category is empty" has to be +// replaced by a case that forces one and watches it hold. +func assertBatchCloserCarriesNoPrecondition(t *testing.T) { + t.Helper() + for _, subject := range []struct { + name string + typ reflect.Type + }{ + {"CloseBatchRequest", reflect.TypeOf(publicops.CloseBatchRequest{})}, + {"BatchCloseItem", reflect.TypeOf(publicops.BatchCloseItem{})}, + } { + for i := 0; i < subject.typ.NumField(); i++ { + if field := subject.typ.Field(i).Name; strings.HasPrefix(field, "Expected") { + t.Errorf("%s carries the precondition field %s, but batchcloser.go says a batch has none — force's lifecycle clause now governs something, and needs a case that exercises it", + subject.name, field) + } + } + } +} + +func seedBatchCloserIssue(t *testing.T, ctx context.Context, fixture BatchCloserFixture, id string, labels ...string) { + t.Helper() + issue := &types.Issue{ + ID: id, + Title: id, + Status: types.StatusOpen, + Priority: 2, + IssueType: types.TypeTask, + Labels: labels, + } + if err := fixture.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatalf("seed issue %s: %v", id, err) + } +} + +func seedBatchCloserWisp(t *testing.T, ctx context.Context, fixture BatchCloserFixture, id string, labels ...string) { + t.Helper() + if err := fixture.CreateWisp(ctx, &types.Issue{ + ID: id, + Title: id, + Status: types.StatusOpen, + Priority: 2, + IssueType: types.TypeTask, + Labels: labels, + Ephemeral: true, + }, "seed"); err != nil { + t.Fatalf("seed wisp %s: %v", id, err) + } +} + +func seedBatchCloserEdge(t *testing.T, ctx context.Context, fixture BatchCloserFixture, source, target string, depType types.DependencyType) { + t.Helper() + if err := fixture.AddDependency(ctx, &types.Dependency{ + IssueID: source, + DependsOnID: target, + Type: depType, + }, "seed"); err != nil { + t.Fatalf("seed %s edge %s -> %s: %v", depType, source, target, err) + } +} + +// batchCloserCaseLabel is how a claim case names its own candidate set. One +// database serves a whole role suite on at least one backend, so a claim +// filtered by anything less specific would race the ready front against a +// sibling case's seeds. +func batchCloserCaseLabel(fixture BatchCloserFixture, name string) string { + return strings.ToLower(fixture.IssuePrefix + "-" + name) +} + +// batchCloserClaimFor builds the claim a coupling case carries. Sort is +// explicit because reader.go:79-83 says no surface may rely on the empty-sort +// fallback. +func batchCloserClaimFor(label string) *publicops.ReadyRequest { + return &publicops.ReadyRequest{Labels: []string{label}, Sort: "priority"} +} + +func assertBatchCloserStatus(t *testing.T, ctx context.Context, fixture BatchCloserFixture, id string, want types.Status) { + t.Helper() + var got string + if err := fixture.QueryScalar(ctx, "SELECT status FROM issues WHERE id = ?", []any{id}, &got); err != nil { + t.Fatalf("read status of %s: %v", id, err) + } + if types.Status(got) != want { + t.Errorf("durable status of %s = %q, want %q", id, got, want) + } +} + +// assertBatchCloserClosedRow reads the close back off the row rather than out +// of the result, because a result snapshot composed in memory can report a +// reason the transaction never wrote. +func assertBatchCloserClosedRow(t *testing.T, ctx context.Context, fixture BatchCloserFixture, id, wantReason, wantSession string) { + t.Helper() + var status, reason, session string + if err := fixture.QueryScalar(ctx, + "SELECT status, COALESCE(close_reason, ''), COALESCE(closed_by_session, '') FROM issues WHERE id = ?", + []any{id}, &status, &reason, &session); err != nil { + t.Fatalf("read the closed row %s: %v", id, err) + } + if types.Status(status) != types.StatusClosed { + t.Errorf("durable status of %s = %q, want %q", id, status, types.StatusClosed) + } + if reason != wantReason { + t.Errorf("durable close_reason of %s = %q, want %q — the reason is recorded against that issue alone", id, reason, wantReason) + } + if session != wantSession { + t.Errorf("durable closed_by_session of %s = %q, want %q", id, session, wantSession) + } +} + +// assertBatchCloserWispStatus is assertBatchCloserStatus against the ephemeral +// plane. A wisp close that wrote nothing anywhere would still report a per-item +// success, so the row is read back off the table that actually holds it. +func assertBatchCloserWispStatus(t *testing.T, ctx context.Context, fixture BatchCloserFixture, id string, want types.Status) { + t.Helper() + var got string + if err := fixture.QueryScalar(ctx, "SELECT status FROM wisps WHERE id = ?", []any{id}, &got); err != nil { + t.Fatalf("read status of the wisp %s: %v", id, err) + } + if types.Status(got) != want { + t.Errorf("ephemeral status of %s = %q, want %q", id, got, want) + } +} + +// batchCloserHistoryEntriesNaming counts the branch's history entries whose +// message mentions id anywhere. The contract asserts on the MESSAGE rather than +// on a count alone because "an entry naming a wisp" is a claim about what +// shipped, and only the message carries an id at all. +func batchCloserHistoryEntriesNaming(t *testing.T, ctx context.Context, fixture BatchCloserFixture, id string) int { + t.Helper() + var entries int + if err := fixture.QueryScalar(ctx, + "SELECT COUNT(*) FROM dolt_log WHERE message LIKE ?", []any{"%" + id + "%"}, &entries); err != nil { + t.Fatalf("count history entries naming %s: %v", id, err) + } + return entries +} + +func batchCloserAssignee(t *testing.T, ctx context.Context, fixture BatchCloserFixture, id string) string { + t.Helper() + var assignee string + if err := fixture.QueryScalar(ctx, "SELECT COALESCE(assignee, '') FROM issues WHERE id = ?", []any{id}, &assignee); err != nil { + t.Fatalf("read assignee of %s: %v", id, err) + } + return assignee +} + +func batchCloserIsBlocked(t *testing.T, ctx context.Context, fixture BatchCloserFixture, id string) int { + t.Helper() + var blocked int + if err := fixture.QueryScalar(ctx, "SELECT is_blocked FROM issues WHERE id = ?", []any{id}, &blocked); err != nil { + t.Fatalf("read is_blocked of %s: %v", id, err) + } + return blocked +} + +func batchCloserOutcomeIDs(outcomes []publicops.CloseOutcome) []string { + ids := make([]string, 0, len(outcomes)) + for _, outcome := range outcomes { + ids = append(ids, outcome.IssueID) + } + return ids +} + +// requireBatchCloserHistory skips LOUDLY rather than passing quietly when a +// backend's fixture cannot observe history at all, which is the difference +// between "this clause is unpinned here" and "this clause holds here". +func requireBatchCloserHistory(t *testing.T, fixture BatchCloserFixture) { + t.Helper() + if fixture.CountHistory == nil { + t.Skipf("fixture has no CountHistory: this backend cannot observe history, so batchcloser.go:119-122 is UNPINNED here") + } +} + +// requireBatchCloserWisps is requireBatchCloserHistory for the ephemeral plane: +// a backend that cannot seed a wisp leaves the three ephemeral rules unpinned, +// and says so rather than passing. +func requireBatchCloserWisps(t *testing.T, fixture BatchCloserFixture) { + t.Helper() + if fixture.CreateWisp == nil { + t.Skipf("fixture has no CreateWisp: this backend cannot seed the ephemeral plane, so the ephemeral rules are UNPINNED here") + } +} diff --git a/backend/conformance/commenter_contract.go b/backend/conformance/commenter_contract.go new file mode 100644 index 000000000..5efef3c60 --- /dev/null +++ b/backend/conformance/commenter_contract.go @@ -0,0 +1,561 @@ +package conformance + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// This file holds the contract every implementation of publicops.Commenter +// must satisfy. Each case asserts what issueops/commenter.go PROMISES, cited +// by line, rather than what any one backend happens to do today; a backend +// that disagrees is parked at its own wiring site with skipKnownDivergence so +// the case still runs on the ones that agree. +// +// There are three wirings — the server-backed store, the embedded store and +// the unit-of-work provider — but only TWO bodies. dolt and embeddeddolt share +// storageissueops.ValidateAddCommentRequest and ExecuteAddComment and differ +// only in the transaction wrapper and the engine underneath, so the third +// wiring catches wrapper and engine divergence, not body divergence. A case +// passing on all three is two independent votes plus a wrapper check, not +// three. +// +// What is deliberately NOT here, and where it lives instead: +// - the commit-message spelling ("bd: comment "), which is a persistence +// detail single-sourced in storageissueops.AddCommentCommitMessage and +// pinned once, at dolt, in dolt/commenter_persistence_test.go; +// - the dolt_status pending-row sweep, which needs a planted dirty working +// set and has no caller-visible meaning on the unit-of-work route. + +// CommenterFixture supplies adapter-specific storage access for the +// add-comment assertions. Every field is named and typed exactly like the +// per-backend roleFixtureKit hook it is filled from, so a wiring is kit plus +// accessor plus prefix with no adapter in between. +type CommenterFixture struct { + // IssuePrefix namespaces the ids each assertion seeds, so several of them + // can share one database. + IssuePrefix string + Commenter publicops.Commenter + // CreateIssue seeds a durable issue in the issues plane. + CreateIssue func(context.Context, *types.Issue, string) error + // CreateWisp seeds an ephemeral issue in the wisps plane. It is a separate + // field rather than an Ephemeral flag on CreateIssue because the three + // adapters reach the two planes through different verbs. + CreateWisp func(context.Context, *types.Issue, string) error + QueryScalar func(context.Context, string, []any, ...any) error + // CountHistory reports how many history entries the fixture's branch has. + // A nil hook means "this backend cannot observe history", and the cases + // that need it SKIP with that reason rather than pass quietly. + CountHistory func(context.Context) (int, error) +} + +// RunCommenterStoresTextVerbatim pins commenter.go:31-34: blankness is decided +// on a trimmed copy and nothing trims the value that lands in the row. The +// text therefore begins with a newline and two spaces — content a trim would +// eat — and the assertion reads the stored column, not the returned struct, +// because a body that trimmed on the way in and echoed the caller's string +// back out would pass a result-only check. +func RunCommenterStoresTextVerbatim(t *testing.T, ctx context.Context, fixture CommenterFixture) { + t.Helper() + anchor := fixture.IssuePrefix + "-verbatim" + seedCommenterIssue(t, ctx, fixture, anchor) + + const text = "\n still a comment" + result, err := fixture.Commenter.AddComment(ctx, publicops.AddCommentRequest{ + Author: "author", + IssueID: anchor, + Text: text, + }) + if err != nil { + t.Fatalf("AddComment with leading whitespace: %v", err) + } + requireCommenterResult(t, result) + + stored := readCommenterRow(t, ctx, fixture, "comments", result.Comment.ID) + if stored.Text != text { + t.Errorf("stored text = %q, want %q verbatim", stored.Text, text) + } + if result.Comment.Text != text { + t.Errorf("returned text = %q, want %q verbatim", result.Comment.Text, text) + } +} + +// RunCommenterResultMirrorsTheStoredRow pins commenter.go:39-43: the result +// carries the id and created_at the row actually got, at the column's +// precision, so it is usable directly as a comment-page cursor. +// +// The precision half is the one a wall-clock implementation fails: created_at +// is DATETIME(0), so a returned CreatedAt carrying sub-second parts sorts +// after the same-second rows stored at the truncated second and a cursor walk +// resumed from it skips them. +// +// The author is checked against the REQUEST's literal as well as against the +// result (commenter.go:14-19): a comment is signed, and the name that lands in +// the row is the one the caller published under. Comparing stored against +// result alone would pass an implementation that canonicalized or defaulted +// the author consistently on both sides — the row would then be signed by +// somebody the caller never named. +func RunCommenterResultMirrorsTheStoredRow(t *testing.T, ctx context.Context, fixture CommenterFixture) { + t.Helper() + anchor := fixture.IssuePrefix + "-mirror" + seedCommenterIssue(t, ctx, fixture, anchor) + + const author = "mirror-author" + result, err := fixture.Commenter.AddComment(ctx, publicops.AddCommentRequest{ + Author: author, + IssueID: anchor, + Text: "the result describes the row", + }) + if err != nil { + t.Fatalf("AddComment: %v", err) + } + requireCommenterResult(t, result) + assertCommenterRowCount(t, ctx, fixture, "comments", anchor, 1) + + stored := readCommenterRow(t, ctx, fixture, "comments", result.Comment.ID) + if stored.IssueID != result.Comment.IssueID { + t.Errorf("stored issue_id = %q, result says %q", stored.IssueID, result.Comment.IssueID) + } + if stored.Author != result.Comment.Author { + t.Errorf("stored author = %q, result says %q", stored.Author, result.Comment.Author) + } + if stored.Author != author { + t.Errorf("stored author = %q, want the request's %q: a comment is signed, and the name in the row is the one it was published under", + stored.Author, author) + } + if stored.Text != result.Comment.Text { + t.Errorf("stored text = %q, result says %q", stored.Text, result.Comment.Text) + } + if !stored.CreatedAt.Equal(result.Comment.CreatedAt) { + t.Errorf("stored created_at = %s, result says %s: the result must carry the STORED value", + stored.CreatedAt.UTC(), result.Comment.CreatedAt.UTC()) + } + if truncated := result.Comment.CreatedAt.Truncate(time.Second); !result.Comment.CreatedAt.Equal(truncated) { + t.Errorf("returned created_at = %s carries sub-second parts the DATETIME(0) column cannot hold, so it is not cursor-safe", + result.Comment.CreatedAt.UTC()) + } +} + +// RunCommenterCommentOnAWispLandsOnTheWispThread pins commenter.go:20-29: the +// issue-to-wisp fallback happens INSIDE, so a caller never has to know which +// plane the thread lives on. Pinning the durable table at zero is the half +// that catches a resolve that fell through to `comments` while the wisp read +// still passed, because a comments row keyed by an id the issues plane does +// not have is invisible to every thread read of the wisp. +// +// The history assertion is an EQUALITY, not the at-most-one bound the durable +// path carries: commenter.go:72-79 promises an ephemeral comment records no +// durable history entry at all. The bound would let a regression that records +// exactly one entry pass on every backend, and that regression is the one that +// breaks federation — the wisp tables are dolt-ignored so ephemeral work never +// ships, and an entry naming a wisp thread ships. +// +// The anchor here lives on exactly one plane, and every anchor a CALLER can +// create does: no local write path reaches dual residency, which is why +// commenter.go and the GetRequest.ID doc it defers to state no plane order for +// the two bodies to disagree about. The refusals that close each local write +// path are enumerated there. +// +// Replication is the residual path and is deliberately not asserted here: a +// dual-resident id arriving by pull is a corrupt store — the merge-based +// lookups behind ready and search hard-error for all of it — so there is no +// well-defined answer for a case to pin, and staging it would mean writing +// rows this library refuses to write (bd-yby99.22). +func RunCommenterCommentOnAWispLandsOnTheWispThread(t *testing.T, ctx context.Context, fixture CommenterFixture) { + t.Helper() + wisp := fixture.IssuePrefix + "-wisp" + seedCommenterWisp(t, ctx, fixture, wisp) + before := commenterHistoryCount(t, ctx, fixture) + + result, err := fixture.Commenter.AddComment(ctx, publicops.AddCommentRequest{ + Author: "author", + IssueID: wisp, + Text: "on the ephemeral plane", + }) + if err != nil { + t.Fatalf("AddComment on a wisp: %v", err) + } + requireCommenterResult(t, result) + + assertCommenterRowCount(t, ctx, fixture, "wisp_comments", wisp, 1) + assertCommenterRowCount(t, ctx, fixture, "comments", wisp, 0) + stored := readCommenterRow(t, ctx, fixture, "wisp_comments", result.Comment.ID) + if stored.Text != "on the ephemeral plane" { + t.Errorf("stored wisp comment text = %q, want the comment that was written", stored.Text) + } + + // No durable trace of an ephemeral comment. The events side is asserted + // only on the DURABLE table, as a plane leak rather than as a promise about + // events: no implementation records a comment event on either plane today + // and no doc promises one either way, so pinning wisp_events at zero would + // freeze an unpromised absence. + assertCommenterRowCount(t, ctx, fixture, "events", wisp, 0) + if after := commenterHistoryCount(t, ctx, fixture); after != before { + t.Errorf("history entries went %d -> %d for a comment on an ephemeral row, want no change: an entry naming a wisp thread is a sync artifact the dolt-ignored wisp tables exist to prevent", before, after) + } +} + +// RunCommenterRefusesAnIDOnNeitherPlane pins commenter.go:68-69: a NON-EMPTY +// id that names neither an issue nor a wisp is ErrNotFound, matchable with +// errors.Is rather than by reading prose, and nothing lands on either plane. +func RunCommenterRefusesAnIDOnNeitherPlane(t *testing.T, ctx context.Context, fixture CommenterFixture) { + t.Helper() + absent := fixture.IssuePrefix + "-absent" + before := commenterHistoryCount(t, ctx, fixture) + + _, err := fixture.Commenter.AddComment(ctx, publicops.AddCommentRequest{ + Author: "author", + IssueID: absent, + Text: "into the void", + }) + if !errors.Is(err, publicops.ErrNotFound) { + t.Fatalf("AddComment on an unknown id error = %v, want ErrNotFound", err) + } + assertCommenterRowCount(t, ctx, fixture, "comments", absent, 0) + assertCommenterRowCount(t, ctx, fixture, "wisp_comments", absent, 0) + if after := commenterHistoryCount(t, ctx, fixture); after != before { + t.Errorf("history entries went %d -> %d across a refused call, want no change", before, after) + } +} + +// RunCommenterRefusesAnEmptyIssueID pins commenter.go:20 and :67-68: IssueID +// must not be empty, and an unaddressed comment is ErrValidation rather than +// ErrNotFound. The two are not interchangeable to a caller — ErrNotFound reads +// as "that thread is gone", which invites a retry against a different id, +// where ErrValidation says the request itself was never addressed to anything +// and no id will fix it. +// +// The sentinel is named rather than left as "either of two" because the +// ErrNotFound clause is now scoped to a NON-EMPTY id (:62-63), so the empty +// string falls to validation and nowhere else. The refusal is also TYPED, +// matchable with errors.Is rather than by reading prose (:63-64), and nothing +// lands on either plane. +func RunCommenterRefusesAnEmptyIssueID(t *testing.T, ctx context.Context, fixture CommenterFixture) { + t.Helper() + _, err := fixture.Commenter.AddComment(ctx, publicops.AddCommentRequest{ + Author: "author", + IssueID: "", + Text: "unaddressed", + }) + if err == nil { + t.Fatal("AddComment with an empty issue id succeeded, want a typed refusal") + } + if !errors.Is(err, publicops.ErrValidation) { + t.Fatalf("AddComment with an empty issue id error = %v, want ErrValidation: an unaddressed request is invalid, not a thread that went missing", err) + } + assertCommenterRowCount(t, ctx, fixture, "comments", "", 0) + assertCommenterRowCount(t, ctx, fixture, "wisp_comments", "", 0) +} + +// RunCommenterDoesNotResolvePrefixes pins the other half of commenter.go:20-29: +// IssueID is the EXACT canonical id and there is no fuzzy or prefix +// resolution here. A strict prefix of a real issue is therefore ErrNotFound, +// not a comment on the issue it nearly names — a comment is signed and +// published under someone's name, so landing it on the wrong thread is worse +// than refusing. +func RunCommenterDoesNotResolvePrefixes(t *testing.T, ctx context.Context, fixture CommenterFixture) { + t.Helper() + full := fixture.IssuePrefix + "-exactid" + partial := fixture.IssuePrefix + "-exact" + seedCommenterIssue(t, ctx, fixture, full) + + _, err := fixture.Commenter.AddComment(ctx, publicops.AddCommentRequest{ + Author: "author", + IssueID: partial, + Text: "addressed to a prefix", + }) + if !errors.Is(err, publicops.ErrNotFound) { + t.Fatalf("AddComment on the strict prefix %q of %q: error = %v, want ErrNotFound", partial, full, err) + } + assertCommenterRowCount(t, ctx, fixture, "comments", full, 0) + assertCommenterRowCount(t, ctx, fixture, "comments", partial, 0) +} + +// RunCommenterRecordsAtMostOneHistoryEntry pins commenter.go:66-67: one +// comment is ONE atomic mutation with at most one history entry. The upper +// bound is what the doc promises, so that is what is asserted; the "one +// mutation" half is the exact-one row count, which catches a body that +// appended the comment twice while the history bound still held. +func RunCommenterRecordsAtMostOneHistoryEntry(t *testing.T, ctx context.Context, fixture CommenterFixture) { + t.Helper() + anchor := fixture.IssuePrefix + "-history" + seedCommenterIssue(t, ctx, fixture, anchor) + before := commenterHistoryCount(t, ctx, fixture) + + if _, err := fixture.Commenter.AddComment(ctx, publicops.AddCommentRequest{ + Author: "author", + IssueID: anchor, + Text: "one mutation", + }); err != nil { + t.Fatalf("AddComment: %v", err) + } + + after := commenterHistoryCount(t, ctx, fixture) + if after < before || after > before+1 { + t.Errorf("history entries went %d -> %d across one AddComment, want at most one more", before, after) + } + assertCommenterRowCount(t, ctx, fixture, "comments", anchor, 1) +} + +// RunCommenterLeavesTheAnchorIssueUntouched pins commenter.go:51-54, the clause +// that makes Commenter a role rather than a Lifecycle verb: a comment appends a +// row to a thread the issue owns and leaves every field of the issue untouched. +// +// It is the promise a caller leans on when it comments on work it is not +// otherwise touching. An implementation that bumped the anchor's updated_at +// would reorder every "recently updated" listing and re-dirty the row for every +// federation sync, and nothing else in this file would notice: the thread would +// still hold exactly one comment. +// +// updated_at is the load-bearing column, and not only because it is one field +// among many. The issues table declares it ON UPDATE CURRENT_TIMESTAMP +// (schema/migrations/0001_create_issues.up.sql), so any UPDATE that changes any +// column at all moves it. Reading it therefore stands in for a whole-row check +// that this seam has no way to spell exhaustively; the named columns beside it +// are the ones a comment path could plausibly reach on purpose. +func RunCommenterLeavesTheAnchorIssueUntouched(t *testing.T, ctx context.Context, fixture CommenterFixture) { + t.Helper() + anchor := fixture.IssuePrefix + "-untouched" + seedCommenterIssue(t, ctx, fixture, anchor) + + before := readCommenterAnchorRow(t, ctx, fixture, anchor) + // A second comment on the same anchor, because "appends to the thread" is + // what the issue row must survive, and the second append is the one that + // would tempt a body into touching a comment count on the issue. + for i, text := range []string{"first append", "second append"} { + if _, err := fixture.Commenter.AddComment(ctx, publicops.AddCommentRequest{ + Author: "author", + IssueID: anchor, + Text: text, + }); err != nil { + t.Fatalf("AddComment %d on %s: %v", i, anchor, err) + } + } + after := readCommenterAnchorRow(t, ctx, fixture, anchor) + + if !after.UpdatedAt.Equal(before.UpdatedAt) { + t.Errorf("anchor %s updated_at moved %s -> %s across two comments: the column is ON UPDATE CURRENT_TIMESTAMP, so something wrote to the issue row", + anchor, before.UpdatedAt.UTC(), after.UpdatedAt.UTC()) + } + if after.Status != before.Status { + t.Errorf("anchor %s status went %q -> %q across a comment", anchor, before.Status, after.Status) + } + if after.Assignee != before.Assignee { + t.Errorf("anchor %s assignee went %q -> %q across a comment", anchor, before.Assignee, after.Assignee) + } + if after.Fingerprint != before.Fingerprint { + t.Errorf("anchor %s changed across a comment:\nbefore %s\n after %s\na comment leaves every field of the issue untouched", + anchor, before.Fingerprint, after.Fingerprint) + } + // The append itself has to have happened, or every equality above is a + // statement about a call that did nothing. + assertCommenterRowCount(t, ctx, fixture, "comments", anchor, 2) +} + +// RunCommenterRefusesBlankText pins commenter.go:31-34 and :67 from the other +// side: a comment of nothing but whitespace carries no information, so it is +// ErrValidation, and per commenter.go:61-64 a deterministic request-validation +// failure leaves persistent state unchanged. +func RunCommenterRefusesBlankText(t *testing.T, ctx context.Context, fixture CommenterFixture) { + t.Helper() + anchor := fixture.IssuePrefix + "-blank" + seedCommenterIssue(t, ctx, fixture, anchor) + before := commenterHistoryCount(t, ctx, fixture) + + _, err := fixture.Commenter.AddComment(ctx, publicops.AddCommentRequest{ + Author: "author", + IssueID: anchor, + Text: " \t\n ", + }) + if !errors.Is(err, publicops.ErrValidation) { + t.Fatalf("AddComment with whitespace-only text: error = %v, want ErrValidation", err) + } + assertCommenterRowCount(t, ctx, fixture, "comments", anchor, 0) + if after := commenterHistoryCount(t, ctx, fixture); after != before { + t.Errorf("history entries went %d -> %d across a refused call, want no change", before, after) + } +} + +// RunCommenterRefusesAnEmptyAuthor pins commenter.go:14: a comment is signed, +// so the author must not be empty. It is a one-line tripwire on purpose — +// ValidateAddCommentRequest is shared by all three implementations, so what +// this guards against is a future implementation UNSHARING the validator, not +// three parallel validators drifting. +func RunCommenterRefusesAnEmptyAuthor(t *testing.T, ctx context.Context, fixture CommenterFixture) { + t.Helper() + anchor := fixture.IssuePrefix + "-unsigned" + seedCommenterIssue(t, ctx, fixture, anchor) + before := commenterHistoryCount(t, ctx, fixture) + + _, err := fixture.Commenter.AddComment(ctx, publicops.AddCommentRequest{ + Author: "", + IssueID: anchor, + Text: "unsigned", + }) + if !errors.Is(err, publicops.ErrValidation) { + t.Fatalf("AddComment with an empty author: error = %v, want ErrValidation", err) + } + assertCommenterRowCount(t, ctx, fixture, "comments", anchor, 0) + if after := commenterHistoryCount(t, ctx, fixture); after != before { + t.Errorf("history entries went %d -> %d across a refused call, want no change", before, after) + } +} + +// RunCommenterLeavesTheCallersRequestAlone pins commenter.go:61-64: +// implementations never mutate caller-owned request values, snapshot the +// request at method entry, and normalize only attempt-local clones. +// +// AddCommentRequest is three strings passed by value, so today no +// implementation CAN violate this. That is exactly why the tripwire is cheap +// and worth having: the day a field becomes a slice, a map or a pointer, the +// promise stops being free and this case is already in place to notice. +func RunCommenterLeavesTheCallersRequestAlone(t *testing.T, ctx context.Context, fixture CommenterFixture) { + t.Helper() + anchor := fixture.IssuePrefix + "-snapshot" + seedCommenterIssue(t, ctx, fixture, anchor) + + request := publicops.AddCommentRequest{ + Author: "author", + IssueID: anchor, + Text: "\n the caller keeps this string", + } + snapshot := request + if _, err := fixture.Commenter.AddComment(ctx, request); err != nil { + t.Fatalf("AddComment: %v", err) + } + if request != snapshot { + t.Errorf("the caller's request became %#v, want it left as %#v", request, snapshot) + } +} + +func seedCommenterIssue(t *testing.T, ctx context.Context, fixture CommenterFixture, id string) { + t.Helper() + if err := fixture.CreateIssue(ctx, commenterSeed(id, false), "seed"); err != nil { + t.Fatalf("seed issue %s: %v", id, err) + } +} + +func seedCommenterWisp(t *testing.T, ctx context.Context, fixture CommenterFixture, id string) { + t.Helper() + if err := fixture.CreateWisp(ctx, commenterSeed(id, true), "seed"); err != nil { + t.Fatalf("seed wisp %s: %v", id, err) + } +} + +func commenterSeed(id string, ephemeral bool) *types.Issue { + return &types.Issue{ + ID: id, + Title: id, + Status: types.StatusOpen, + Priority: 2, + IssueType: types.TypeTask, + Ephemeral: ephemeral, + } +} + +// requireCommenterResult checks the shape every successful AddComment owes its +// caller before a case reads the rest of it, so a nil Comment fails as "the +// result was empty" rather than as a nil dereference three lines later. +func requireCommenterResult(t *testing.T, result publicops.AddCommentResult) { + t.Helper() + if result.Comment == nil || result.Comment.ID == "" || result.Comment.CreatedAt.IsZero() { + t.Fatalf("Comment = %#v, want the stored row's id and created_at", result.Comment) + } +} + +// commenterStoredRow is one comment row as the database holds it. +type commenterStoredRow struct { + IssueID string + Author string + Text string + CreatedAt time.Time +} + +// readCommenterRow reads the row a result names, from the comment table of one +// plane. It fails the test when the row is absent, because every caller here +// has already been told the row exists. +func readCommenterRow(t *testing.T, ctx context.Context, fixture CommenterFixture, table, commentID string) commenterStoredRow { + t.Helper() + var row commenterStoredRow + //nolint:gosec // G201: table is one of the contract's two hardcoded names. + query := "SELECT issue_id, author, text, created_at FROM " + table + " WHERE id = ?" + if err := fixture.QueryScalar(ctx, query, []any{commentID}, + &row.IssueID, &row.Author, &row.Text, &row.CreatedAt); err != nil { + t.Fatalf("read the %s row %s the result names: %v", table, commentID, err) + } + return row +} + +// commenterAnchorRow is the issues row a comment must not disturb: three +// columns named so a failure reads as "the assignee moved" rather than as a +// diff of two long strings, plus the wide fingerprint that catches the rest. +type commenterAnchorRow struct { + Status string + Assignee string + UpdatedAt time.Time + Fingerprint string +} + +// readCommenterAnchorRow reads the anchor's row through the fixture's own SQL +// hook rather than through Reader.Get, because the subject is what the +// TRANSACTION wrote: a detail view composed in memory can report a field the +// row no longer carries. +// +// The fingerprint is CONCAT_WS rather than a column-by-column scan so the +// column list can be wide without the case growing a scan destination per +// column. CONCAT_WS skips NULL arguments, so a column going NULL -> ” still +// moves the string (the separator count changes) — the one shape that would +// otherwise slip past. +func readCommenterAnchorRow(t *testing.T, ctx context.Context, fixture CommenterFixture, issueID string) commenterAnchorRow { + t.Helper() + const query = `SELECT status, COALESCE(assignee, ''), updated_at, + CONCAT_WS('|', content_hash, title, description, design, acceptance_criteria, notes, + status, priority, issue_type, assignee, estimated_minutes, + created_at, created_by, owner, updated_at, closed_at, closed_by_session, + external_ref, spec_id, sender, ephemeral, wisp_type, pinned, is_template, + mol_type, work_type, source_system, source_repo, close_reason, is_blocked, + due_at, defer_until) + FROM issues WHERE id = ?` + var row commenterAnchorRow + if err := fixture.QueryScalar(ctx, query, []any{issueID}, + &row.Status, &row.Assignee, &row.UpdatedAt, &row.Fingerprint); err != nil { + t.Fatalf("read the anchor row %s: %v", issueID, err) + } + return row +} + +// assertCommenterRowCount counts one anchor's rows in one plane-specific +// table. Comment threads and event feeds are both keyed by issue_id, so the +// two kinds of assertion share it rather than differ by a copied query. +func assertCommenterRowCount(t *testing.T, ctx context.Context, fixture CommenterFixture, table, issueID string, want int) { + t.Helper() + var got int + //nolint:gosec // G201: table is one of the contract's four hardcoded names. + query := "SELECT COUNT(*) FROM " + table + " WHERE issue_id = ?" + if err := fixture.QueryScalar(ctx, query, []any{issueID}, &got); err != nil { + t.Fatalf("count %s rows for %s: %v", table, issueID, err) + } + if got != want { + t.Errorf("%s rows for %s = %d, want %d", table, issueID, got, want) + } +} + +// commenterHistoryCount reads the branch's history depth, or SKIPS the case +// with the reason when the backend cannot observe history at all. A silent +// pass would be worse than no case: the entry-per-call clause would look +// pinned on a backend that never checked it. +func commenterHistoryCount(t *testing.T, ctx context.Context, fixture CommenterFixture) int { + t.Helper() + if fixture.CountHistory == nil { + t.Skip("fixture cannot observe history: CountHistory is nil, so the at-most-one-entry clause is unpinned on this backend") + } + entries, err := fixture.CountHistory(ctx) + if err != nil { + t.Fatalf("count history entries: %v", err) + } + return entries +} diff --git a/backend/conformance/dependency_editor_contract.go b/backend/conformance/dependency_editor_contract.go new file mode 100644 index 000000000..36d51948c --- /dev/null +++ b/backend/conformance/dependency_editor_contract.go @@ -0,0 +1,1272 @@ +package conformance + +import ( + "context" + "errors" + "testing" + + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// This file holds the contract every implementation of +// publicops.DependencyEditor must satisfy. There are three of them — the +// direct store, the embedded store, and the unit-of-work backend — and the +// first two share a transaction body the third does not, so a rule asserted +// against one has repeatedly drifted on the others. A run on the third +// backend therefore catches WRAPPER AND ENGINE divergence between the two that +// share a body; only the unit-of-work run is an independent vote on the body. +// +// The first four cases pin the one thing the three had actually diverged on: +// which PLANE an edge lands in. `bd dep add ` writes the +// ephemeral graph, and it has to, because a wisp has no row in the issues +// plane for an edge to hang off. +// +// The rest pin the role's older semantics — request-order echo, idempotency, +// refusal atomicity, the typed refusals, application order, external targets, +// request hygiene and the one-history-entry-per-landed-request rule. Each is +// written to what issueops/dependencyeditor.go PROMISES; where an +// implementation disagrees, the case still asserts the doc and the losing +// backend's wiring parks it with skipKnownDivergence. + +// DependencyEditorFixture supplies adapter-specific storage access for the +// dependency-editor assertions. +type DependencyEditorFixture struct { + // IssuePrefix namespaces the ids each assertion seeds, so several of them + // can share one database. + IssuePrefix string + Editor publicops.DependencyEditor + // CreateIssue seeds a durable issue in the issues plane. + CreateIssue func(context.Context, *types.Issue, string) error + // CreateWisp seeds an ephemeral issue in the wisps plane. It is a separate + // field rather than an Ephemeral flag on CreateIssue because the three + // adapters reach the two planes through different verbs. + CreateWisp func(context.Context, *types.Issue, string) error + QueryScalar func(context.Context, string, []any, ...any) error + // CountHistory reports how many history entries the fixture's branch has. + // The cases that need it take it before and after the operation under test, + // because two commits made inside one second tie on date and their relative + // order is not something to rely on. + // + // A nil CountHistory means "this backend cannot observe history here", and + // the cases that need it then skip with that reason rather than pass + // quietly. It is non-nil on all three backends today. + CountHistory func(context.Context) (int, error) +} + +// RunDependencyEditorRoutesWispSourcedEdgeToTheWispPlane is the regression pin +// for a wisp-sourced edge. Both the edge and its event follow the SOURCE: +// wisp_dependencies and wisp_events, never the durable pair. Pinning the +// durable pair at zero is the half that catches a regression writing an edge +// whose issue_id names a row the issues plane does not have. +func RunDependencyEditorRoutesWispSourcedEdgeToTheWispPlane(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + wisp := fixture.IssuePrefix + "-wdep-src" + target := fixture.IssuePrefix + "-wdep-tgt" + seedDependencyEditorWisp(t, ctx, fixture, wisp) + seedDependencyEditorIssue(t, ctx, fixture, target) + + if _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{{IssueID: wisp, DependsOnID: target, Type: publicops.DepBlocks}}, + }); err != nil { + t.Fatalf("AddDependencies from a wisp source: %v", err) + } + + assertDependencyEdgeCount(t, ctx, fixture, "wisp_dependencies", wisp, target, 1) + assertDependencyEdgeCount(t, ctx, fixture, "dependencies", wisp, target, 0) + assertDependencyEditorEventCount(t, ctx, fixture, "wisp_events", wisp, types.EventDependencyAdded, 1) + assertDependencyEditorEventCount(t, ctx, fixture, "events", wisp, types.EventDependencyAdded, 0) +} + +// RunDependencyEditorMixedBatchWritesBothPlanes proves one request can span +// the two planes. The batch is one transaction with two write paths in it, so +// this is the case that catches a routing decision taken once for the whole +// request instead of once per edge. +func RunDependencyEditorMixedBatchWritesBothPlanes(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + wisp := fixture.IssuePrefix + "-mixed-wisp" + issue := fixture.IssuePrefix + "-mixed-issue" + target := fixture.IssuePrefix + "-mixed-target" + seedDependencyEditorWisp(t, ctx, fixture, wisp) + seedDependencyEditorIssue(t, ctx, fixture, issue) + seedDependencyEditorIssue(t, ctx, fixture, target) + + if _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{ + {IssueID: wisp, DependsOnID: target, Type: publicops.DepBlocks}, + {IssueID: issue, DependsOnID: target, Type: publicops.DepBlocks}, + }, + }); err != nil { + t.Fatalf("AddDependencies on a mixed-plane batch: %v", err) + } + + assertDependencyEdgeCount(t, ctx, fixture, "wisp_dependencies", wisp, target, 1) + assertDependencyEdgeCount(t, ctx, fixture, "dependencies", wisp, target, 0) + assertDependencyEdgeCount(t, ctx, fixture, "dependencies", issue, target, 1) + assertDependencyEdgeCount(t, ctx, fixture, "wisp_dependencies", issue, target, 0) +} + +// RunDependencyEditorMixedBatchRefusalRollsBackBothPlanes proves the +// all-or-nothing promise survives the plane split: a refusal on the durable +// edge must take the ephemeral edge written before it back out too. +// +// The refusal is a type conflict rather than a cycle so that it fires at the +// edge, after the earlier edge is already written, rather than at the +// whole-graph gate. +func RunDependencyEditorMixedBatchRefusalRollsBackBothPlanes(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + wisp := fixture.IssuePrefix + "-rb-wisp" + issue := fixture.IssuePrefix + "-rb-issue" + target := fixture.IssuePrefix + "-rb-target" + seedDependencyEditorWisp(t, ctx, fixture, wisp) + seedDependencyEditorIssue(t, ctx, fixture, issue) + seedDependencyEditorIssue(t, ctx, fixture, target) + + if _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{{IssueID: issue, DependsOnID: target, Type: publicops.DepBlocks}}, + }); err != nil { + t.Fatalf("seed the durable edge that the retype will collide with: %v", err) + } + + _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{ + {IssueID: wisp, DependsOnID: target, Type: publicops.DepBlocks}, + {IssueID: issue, DependsOnID: target, Type: publicops.DepRelated}, + }, + }) + var conflict *publicops.DependencyTypeConflictError + if !errors.As(err, &conflict) { + t.Fatalf("mixed-batch retype error = %v, want *DependencyTypeConflictError", err) + } + assertDependencyEdgeCount(t, ctx, fixture, "wisp_dependencies", wisp, target, 0) + assertDependencyEdgeCount(t, ctx, fixture, "dependencies", wisp, target, 0) + assertDependencyEditorEventCount(t, ctx, fixture, "wisp_events", wisp, types.EventDependencyAdded, 0) + assertDependencyEdgeTypedCount(t, ctx, fixture, "dependencies", issue, target, string(publicops.DepBlocks), 1) +} + +// RunDependencyEditorRefusesCrossPlaneCycle pins bd-xe27: the scheduling graph +// is one graph across the two tables, so an edge closing a loop that leaves +// the issues plane and comes back through the wisp plane is refused. +func RunDependencyEditorRefusesCrossPlaneCycle(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + issue := fixture.IssuePrefix + "-xcycle-issue" + wisp := fixture.IssuePrefix + "-xcycle-wisp" + seedDependencyEditorIssue(t, ctx, fixture, issue) + seedDependencyEditorWisp(t, ctx, fixture, wisp) + + // issue -> wisp lands in the durable table with a wisp target. + if _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{{IssueID: issue, DependsOnID: wisp, Type: publicops.DepBlocks}}, + }); err != nil { + t.Fatalf("AddDependencies issue -> wisp: %v", err) + } + assertDependencyEdgeCount(t, ctx, fixture, "dependencies", issue, wisp, 1) + + // wisp -> issue would close the loop through the other table. + _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{{IssueID: wisp, DependsOnID: issue, Type: publicops.DepBlocks}}, + }) + if !errors.Is(err, publicops.ErrDependencyCycle) { + t.Fatalf("cross-plane cycle error = %v, want ErrDependencyCycle", err) + } + assertDependencyEdgeCount(t, ctx, fixture, "wisp_dependencies", wisp, issue, 0) + + // The same loop, hidden from the per-edge probe, must still be refused by + // the whole-graph gate. + _, err = fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + SkipPerEdgeCycleCheck: true, + Edges: []publicops.DependencyEdge{{IssueID: wisp, DependsOnID: issue, Type: publicops.DepBlocks}}, + }) + if !errors.Is(err, publicops.ErrDependencyCycle) { + t.Fatalf("cross-plane cycle error with the probe skipped = %v, want ErrDependencyCycle from the final gate", err) + } + assertDependencyEdgeCount(t, ctx, fixture, "wisp_dependencies", wisp, issue, 0) +} + +// RunDependencyEditorAddedEchoesTheRequestOrder pins AddDependenciesResult.Added +// (issueops/dependencyeditor.go:76-81): all-or-nothing means Added is either +// every requested edge or the call failed, so it echoes the REQUEST — a caller +// reporting what landed reads the result and never has to know which. +// +// The request deliberately leads with a blocking edge and ends with a +// parent-child one, which is the reverse of the order the edges are APPLIED in +// (dependencyeditor.go:61-64). The application order must not leak into the +// result. +func RunDependencyEditorAddedEchoesTheRequestOrder(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + source := fixture.IssuePrefix + "-echo-source" + target := fixture.IssuePrefix + "-echo-target" + child := fixture.IssuePrefix + "-echo-child" + for _, id := range []string{source, target, child} { + seedDependencyEditorIssue(t, ctx, fixture, id) + } + + edges := []publicops.DependencyEdge{ + {IssueID: source, DependsOnID: target, Type: publicops.DepBlocks}, + {IssueID: child, DependsOnID: source, Type: publicops.DepParentChild}, + } + result, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{Actor: "writer", Edges: edges}) + if err != nil { + t.Fatalf("AddDependencies: %v", err) + } + if len(result.Added) != len(edges) { + t.Fatalf("Added = %#v, want %d edges", result.Added, len(edges)) + } + for i, want := range edges { + if result.Added[i] != want { + t.Errorf("Added[%d] = %#v, want %#v: the result echoes the REQUEST order, not the order the edges were applied in", i, result.Added[i], want) + } + } + + assertDependencyEdgeTypedCount(t, ctx, fixture, "dependencies", source, target, string(publicops.DepBlocks), 1) + assertDependencyEdgeTypedCount(t, ctx, fixture, "dependencies", child, source, string(publicops.DepParentChild), 1) +} + +// RunDependencyEditorSameTypeReAddIsIdempotent pins the same-type re-add +// clause: an edge that already exists with the SAME type is idempotent and +// refuses nothing. The row count is what makes it idempotent rather than +// merely tolerated. +// +// It also pins the clause's second half, that a request which wrote no durable +// edge records NO history entry. The doc reaches that by the same argument the +// removal side already made — nothing was written, so there is nothing to +// version — and the two halves belong in one case because the history delta is +// only meaningful next to the row count that explains it. +// +// The event stream is the third observable and the sharpest one: the leaf +// promises a dependency_added entry for a GENUINELY NEW edge, so a backend +// that re-emitted on the no-op would leave a history of work that did not +// happen even where the row count could not tell. +func RunDependencyEditorSameTypeReAddIsIdempotent(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + source := fixture.IssuePrefix + "-idem-source" + target := fixture.IssuePrefix + "-idem-target" + seedDependencyEditorIssue(t, ctx, fixture, source) + seedDependencyEditorIssue(t, ctx, fixture, target) + + request := publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{{IssueID: source, DependsOnID: target, Type: publicops.DepBlocks}}, + } + if _, err := fixture.Editor.AddDependencies(ctx, request); err != nil { + t.Fatalf("AddDependencies first: %v", err) + } + assertDependencyEditorEventCount(t, ctx, fixture, "events", source, types.EventDependencyAdded, 1) + + assertHistoryDelta := dependencyEditorHistoryProbe(t, ctx, fixture) + result, err := fixture.Editor.AddDependencies(ctx, request) + if err != nil { + t.Fatalf("re-adding the same edge with the same type refused: %v", err) + } + if len(result.Added) != 1 || result.Added[0] != request.Edges[0] { + t.Errorf("Added on the idempotent re-add = %#v, want the requested edge: the result echoes the request either way", result.Added) + } + assertDependencyEditorOutgoingCount(t, ctx, fixture, "dependencies", source, 1) + assertDependencyEdgeTypedCount(t, ctx, fixture, "dependencies", source, target, string(publicops.DepBlocks), 1) + assertDependencyEditorEventCount(t, ctx, fixture, "events", source, types.EventDependencyAdded, 1) + assertHistoryDelta(0, "every edge of the request already existed with the requested type, so nothing was written and nothing is versioned") +} + +// RunDependencyEditorRepeatsWithinOneRequestCollapse pins the clause that +// answers a request naming ONE PAIR TWICE. The same-type re-add rule is stated +// for the pair rather than for the call, so the second occurrence inside a +// request finds the first already written and the pair is applied once — while +// the result still echoes every edge the caller asked for, because +// AddDependenciesResult.Added is all-or-nothing and echoes the REQUEST. +// +// The second half is the conflict: two DIFFERENT types for one pair in one +// request raise the same *DependencyTypeConflictError a pre-existing edge of +// the other type raises, and the all-or-nothing rule takes the first +// occurrence back out with it. That the refusal is the TYPED one is the part +// worth pinning — a backend that treated a within-request repeat as a distinct +// insert would surface a primary-key violation instead, which is the same +// refusal with none of the information. +func RunDependencyEditorRepeatsWithinOneRequestCollapse(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + source := fixture.IssuePrefix + "-repeat-source" + target := fixture.IssuePrefix + "-repeat-target" + seedDependencyEditorIssue(t, ctx, fixture, source) + seedDependencyEditorIssue(t, ctx, fixture, target) + + edge := publicops.DependencyEdge{IssueID: source, DependsOnID: target, Type: publicops.DepBlocks} + assertHistoryDelta := dependencyEditorHistoryProbe(t, ctx, fixture) + result, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{edge, edge}, + }) + if err != nil { + t.Fatalf("AddDependencies naming one pair twice: %v — a repeat is the same-type re-add rule applied inside the request", err) + } + if len(result.Added) != 2 || result.Added[0] != edge || result.Added[1] != edge { + t.Errorf("Added = %#v, want both requested edges: the result echoes the REQUEST, not the rows written", result.Added) + } + assertDependencyEditorOutgoingCount(t, ctx, fixture, "dependencies", source, 1) + assertDependencyEdgeTypedCount(t, ctx, fixture, "dependencies", source, target, string(publicops.DepBlocks), 1) + assertDependencyEditorEventCount(t, ctx, fixture, "events", source, types.EventDependencyAdded, 1) + assertHistoryDelta(1, "one pair named twice is one edge written, so it is still ONE history entry") + + conflictSource := fixture.IssuePrefix + "-repeat-conflict-source" + conflictTarget := fixture.IssuePrefix + "-repeat-conflict-target" + seedDependencyEditorIssue(t, ctx, fixture, conflictSource) + seedDependencyEditorIssue(t, ctx, fixture, conflictTarget) + + _, err = fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{ + {IssueID: conflictSource, DependsOnID: conflictTarget, Type: publicops.DepBlocks}, + {IssueID: conflictSource, DependsOnID: conflictTarget, Type: publicops.DepRelated}, + }, + }) + var conflict *publicops.DependencyTypeConflictError + if !errors.As(err, &conflict) { + t.Fatalf("one pair given two types in one request: error = %v, want *DependencyTypeConflictError", err) + } + assertDependencyEditorNoEdgesFrom(t, ctx, fixture, conflictSource) +} + +// RunDependencyEditorAttributesItsEventsToTheActor pins what +// AddDependenciesRequest.Actor and RemoveDependencyRequest.Actor are FOR: the +// leaf says each is what the entry the operation records in the source's event +// stream is attributed to, and the result carries it nowhere else. +// +// Every other case in this file reads those rows as a plane-routing probe and +// counts them. This is the one that reads the attribution, and it uses a +// different actor for the add and the removal so a backend that stamped the +// row from anything but the request under way — a session identity, the +// creator, the previous actor — fails it. +func RunDependencyEditorAttributesItsEventsToTheActor(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + source := fixture.IssuePrefix + "-actor-source" + target := fixture.IssuePrefix + "-actor-target" + seedDependencyEditorIssue(t, ctx, fixture, source) + seedDependencyEditorIssue(t, ctx, fixture, target) + + if _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "edge-author", + Edges: []publicops.DependencyEdge{{IssueID: source, DependsOnID: target, Type: publicops.DepBlocks}}, + }); err != nil { + t.Fatalf("AddDependencies: %v", err) + } + assertDependencyEditorEventActor(t, ctx, fixture, source, types.EventDependencyAdded, "edge-author") + + removed, err := fixture.Editor.RemoveDependency(ctx, publicops.RemoveDependencyRequest{ + Actor: "edge-remover", IssueID: source, DependsOnID: target, + }) + if err != nil || !removed.Removed { + t.Fatalf("RemoveDependency = %#v, %v; want Removed true", removed, err) + } + assertDependencyEditorEventActor(t, ctx, fixture, source, types.EventDependencyRemoved, "edge-remover") +} + +// RunDependencyEditorRetypeRefusalLeavesTheOriginalEdge pins the other half of +// the same clause (dependencyeditor.go:145-146): a conflicting type on a pair +// that already has an edge is *DependencyTypeConflictError, and because the +// request is all-or-nothing the edge that was already there is untouched. +func RunDependencyEditorRetypeRefusalLeavesTheOriginalEdge(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + source := fixture.IssuePrefix + "-retype-source" + target := fixture.IssuePrefix + "-retype-target" + seedDependencyEditorIssue(t, ctx, fixture, source) + seedDependencyEditorIssue(t, ctx, fixture, target) + + if _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{{IssueID: source, DependsOnID: target, Type: publicops.DepBlocks}}, + }); err != nil { + t.Fatalf("seed the edge the retype will collide with: %v", err) + } + + _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{{IssueID: source, DependsOnID: target, Type: publicops.DepRelated}}, + }) + var conflict *publicops.DependencyTypeConflictError + if !errors.As(err, &conflict) { + t.Fatalf("retype error = %v, want *DependencyTypeConflictError", err) + } + assertDependencyEditorOutgoingCount(t, ctx, fixture, "dependencies", source, 1) + assertDependencyEdgeTypedCount(t, ctx, fixture, "dependencies", source, target, string(publicops.DepBlocks), 1) + assertDependencyEdgeTypedCount(t, ctx, fixture, "dependencies", source, target, string(publicops.DepRelated), 0) +} + +// RunDependencyEditorRefusalWritesNothing pins dependencyeditor.go:143-144 — +// any refused edge refuses the whole request and writes nothing — on BOTH +// refusal paths: the per-edge cycle probe, which fires with an earlier edge of +// the same request already written, and the whole-graph gate that runs when +// SkipPerEdgeCycleCheck turned the probe off (dependencyeditor.go:66-70). +// +// The skip-probe half needs three edges because the cycle it closes only +// exists once all three of the request's own edges are in place, which is +// exactly what a per-edge probe cannot see. +func RunDependencyEditorRefusalWritesNothing(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + a := fixture.IssuePrefix + "-refuse-a" + b := fixture.IssuePrefix + "-refuse-b" + c := fixture.IssuePrefix + "-refuse-c" + for _, id := range []string{a, b, c} { + seedDependencyEditorIssue(t, ctx, fixture, id) + } + + _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{ + {IssueID: a, DependsOnID: b, Type: publicops.DepBlocks}, + {IssueID: b, DependsOnID: a, Type: publicops.DepBlocks}, + }, + }) + if !errors.Is(err, publicops.ErrDependencyCycle) { + t.Fatalf("per-edge cycle error = %v, want ErrDependencyCycle", err) + } + assertDependencyEditorNoEdgesFrom(t, ctx, fixture, a, b) + + _, err = fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + SkipPerEdgeCycleCheck: true, + Edges: []publicops.DependencyEdge{ + {IssueID: a, DependsOnID: b, Type: publicops.DepBlocks}, + {IssueID: b, DependsOnID: c, Type: publicops.DepBlocks}, + {IssueID: c, DependsOnID: a, Type: publicops.DepBlocks}, + }, + }) + if !errors.Is(err, publicops.ErrDependencyCycle) { + t.Fatalf("skip-probe cycle error = %v, want ErrDependencyCycle from the final gate", err) + } + assertDependencyEditorNoEdgesFrom(t, ctx, fixture, a, b, c) +} + +// RunDependencyEditorRemoveIsIdempotent pins +// RemoveDependencyResult.Removed (dependencyeditor.go:97-101, :180-181): a +// missing edge is Removed false with a NIL error, not ErrNotFound, because an +// agent replaying its own teardown should not have to classify an error to +// discover it already ran. +func RunDependencyEditorRemoveIsIdempotent(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + source := fixture.IssuePrefix + "-rm-source" + target := fixture.IssuePrefix + "-rm-target" + seedDependencyEditorIssue(t, ctx, fixture, source) + seedDependencyEditorIssue(t, ctx, fixture, target) + + if _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{{IssueID: source, DependsOnID: target, Type: publicops.DepBlocks}}, + }); err != nil { + t.Fatalf("seed the edge to remove: %v", err) + } + + request := publicops.RemoveDependencyRequest{Actor: "writer", IssueID: source, DependsOnID: target} + removed, err := fixture.Editor.RemoveDependency(ctx, request) + if err != nil { + t.Fatalf("RemoveDependency: %v", err) + } + if !removed.Removed { + t.Fatal("Removed = false, want true for an edge that existed") + } + assertDependencyEditorOutgoingCount(t, ctx, fixture, "dependencies", source, 0) + assertDependencyEditorEventCount(t, ctx, fixture, "events", source, types.EventDependencyRemoved, 1) + + removed, err = fixture.Editor.RemoveDependency(ctx, request) + if err != nil { + t.Fatalf("replayed RemoveDependency error = %v, want nil: a missing edge is a success", err) + } + if removed.Removed { + t.Error("Removed = true, want false for an edge that was already gone") + } + assertDependencyEditorEventCount(t, ctx, fixture, "events", source, types.EventDependencyRemoved, 1) +} + +// RunDependencyEditorAppliesParentChildBeforeBlockingEdges pins +// dependencyeditor.go:61-64: edges are applied parent-child first REGARDLESS of +// request order, so the complete planned hierarchy is visible before any +// blocking edge is validated against it. +// +// The ordering is what decides the ANSWER. Applied hierarchy-first, the +// grandparent is an ancestor of the child by the time `child blocks grand` is +// checked, so the request is refused with the hierarchy sentinel and nothing is +// written. Applied in request order, that blocking edge is validated against a +// hierarchy that does not exist yet — a backend doing that answers something +// else, or nothing at all. +func RunDependencyEditorAppliesParentChildBeforeBlockingEdges(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + grand := fixture.IssuePrefix + "-pcfirst-grand" + parent := fixture.IssuePrefix + "-pcfirst-parent" + child := fixture.IssuePrefix + "-pcfirst-child" + for _, id := range []string{grand, parent, child} { + seedDependencyEditorIssue(t, ctx, fixture, id) + } + + _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{ + {IssueID: child, DependsOnID: grand, Type: publicops.DepBlocks}, + {IssueID: child, DependsOnID: parent, Type: publicops.DepParentChild}, + {IssueID: parent, DependsOnID: grand, Type: publicops.DepParentChild}, + }, + }) + var conflict *publicops.DependencyHierarchyConflictError + if !errors.As(err, &conflict) { + t.Fatalf("error = %v, want *DependencyHierarchyConflictError: the hierarchy this request creates is applied first", err) + } + if !conflict.BlockerIsAncestor { + t.Errorf("conflict = %#v, want the blocker reported as the child's ancestor", conflict) + } + assertDependencyEditorNoEdgesFrom(t, ctx, fixture, child, parent) +} + +// RunDependencyEditorAcceptsAnExternalTarget pins the first half of +// dependencyeditor.go:150-156: a target's existence is checked only where the +// backend can see it, and an "external:" reference is not something this +// database holds, so there is no unknown-target refusal to make. +func RunDependencyEditorAcceptsAnExternalTarget(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + source := fixture.IssuePrefix + "-ext-source" + const target = "external:https://example.invalid/tracker/17" + seedDependencyEditorIssue(t, ctx, fixture, source) + + if _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{{IssueID: source, DependsOnID: target, Type: publicops.DepBlocks}}, + }); err != nil { + t.Fatalf("AddDependencies onto an external: target: %v", err) + } + assertDependencyEdgeTypedCount(t, ctx, fixture, "dependencies", source, target, string(publicops.DepBlocks), 1) +} + +// RunDependencyEditorAcceptsAForeignRepoTarget pins the second half of +// dependencyeditor.go:150-156: an issue in ANOTHER REPOSITORY is equally not +// something this database holds. +// +// It is its own case rather than a second assertion in the external one +// because the two reach the target column by different routes — an "external:" +// prefix is a string test, a foreign repository is an id-prefix comparison +// against the source — so a backend can hold one promise and break the other. +// This is the promise the fk_dep_issue_target foreign key on +// depends_on_issue_id (internal/storage/schema/cli_migrations.go:141,155,168) +// turns into a write failure whenever a backend classifies the target as a +// local issue. +func RunDependencyEditorAcceptsAForeignRepoTarget(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + source := fixture.IssuePrefix + "-foreign-source" + const target = "otherrig-9001" + seedDependencyEditorIssue(t, ctx, fixture, source) + + if _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{{IssueID: source, DependsOnID: target, Type: publicops.DepBlocks}}, + }); err != nil { + t.Fatalf("AddDependencies onto a target in another repository: %v", err) + } + assertDependencyEdgeTypedCount(t, ctx, fixture, "dependencies", source, target, string(publicops.DepBlocks), 1) +} + +// RunDependencyEditorRefusesBlockingEdgeAcrossItsOwnHierarchy pins +// dependencyeditor.go:146-148: a blocking edge that would gate an issue on its +// own ancestor or descendant is *DependencyHierarchyConflictError. +// +// Both directions are asserted because they are two construction sites of the +// same typed sentinel, and the flag that distinguishes them is part of the +// value a caller reads. +func RunDependencyEditorRefusesBlockingEdgeAcrossItsOwnHierarchy(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + grand := fixture.IssuePrefix + "-hier-grand" + parent := fixture.IssuePrefix + "-hier-parent" + child := fixture.IssuePrefix + "-hier-child" + for _, id := range []string{grand, parent, child} { + seedDependencyEditorIssue(t, ctx, fixture, id) + } + if _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{ + {IssueID: parent, DependsOnID: grand, Type: publicops.DepParentChild}, + {IssueID: child, DependsOnID: parent, Type: publicops.DepParentChild}, + }, + }); err != nil { + t.Fatalf("seed the hierarchy: %v", err) + } + + _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{{IssueID: child, DependsOnID: grand, Type: publicops.DepBlocks}}, + }) + var ancestor *publicops.DependencyHierarchyConflictError + if !errors.As(err, &ancestor) { + t.Fatalf("gating a child on its ancestor: error = %v, want *DependencyHierarchyConflictError", err) + } + if !ancestor.BlockerIsAncestor { + t.Errorf("conflict = %#v, want BlockerIsAncestor true", ancestor) + } + assertDependencyEdgeTypedCount(t, ctx, fixture, "dependencies", child, grand, string(publicops.DepBlocks), 0) + + _, err = fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{{IssueID: grand, DependsOnID: child, Type: publicops.DepBlocks}}, + }) + var descendant *publicops.DependencyHierarchyConflictError + if !errors.As(err, &descendant) { + t.Fatalf("gating an ancestor on its descendant: error = %v, want *DependencyHierarchyConflictError", err) + } + if descendant.BlockerIsAncestor { + t.Errorf("conflict = %#v, want BlockerIsAncestor false: the blocker is the DESCENDANT here", descendant) + } + assertDependencyEdgeTypedCount(t, ctx, fixture, "dependencies", grand, child, string(publicops.DepBlocks), 0) +} + +// RunDependencyEditorRefusesSelfDependencyWithTheProbeSkipped pins +// dependencyeditor.go:66-70: SkipPerEdgeCycleCheck never drops the +// self-dependency refusal. An edge that points an issue at itself is refused +// with ErrSelfDependency with or without the flag, and for every type — a +// non-scheduling self-edge is never seen by a cycle probe at all, so the flag +// is not what was refusing it. +func RunDependencyEditorRefusesSelfDependencyWithTheProbeSkipped(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + source := fixture.IssuePrefix + "-self-source" + seedDependencyEditorIssue(t, ctx, fixture, source) + + for _, probe := range []struct { + name string + skip bool + depType publicops.DependencyType + }{ + {"blocking edge, probe on", false, publicops.DepBlocks}, + {"blocking edge, probe skipped", true, publicops.DepBlocks}, + {"non-scheduling edge, probe skipped", true, publicops.DepRelated}, + } { + _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + SkipPerEdgeCycleCheck: probe.skip, + Edges: []publicops.DependencyEdge{{IssueID: source, DependsOnID: source, Type: probe.depType}}, + }) + if !errors.Is(err, publicops.ErrSelfDependency) { + t.Errorf("%s: error = %v, want ErrSelfDependency", probe.name, err) + } + } + assertDependencyEditorNoEdgesFrom(t, ctx, fixture, source) +} + +// RunDependencyEditorRecordsOneHistoryEntryPerLandedRequest pins +// dependencyeditor.go:142-143 and :100-101: an assertion is ONE durable act +// with one history entry however many edges it wrote, and a removal that found +// nothing writes nothing and records no entry. +// +// The counts are deltas taken around each call rather than absolutes, because +// seeding versions its own writes. +func RunDependencyEditorRecordsOneHistoryEntryPerLandedRequest(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + if fixture.CountHistory == nil { + t.Skip("fixture.CountHistory is nil: this backend cannot observe history, so the one-entry-per-request clause cannot be checked here") + } + a := fixture.IssuePrefix + "-hist-a" + b := fixture.IssuePrefix + "-hist-b" + c := fixture.IssuePrefix + "-hist-c" + for _, id := range []string{a, b, c} { + seedDependencyEditorIssue(t, ctx, fixture, id) + } + + before := dependencyEditorHistoryCount(t, ctx, fixture) + if _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{ + {IssueID: a, DependsOnID: b, Type: publicops.DepBlocks}, + {IssueID: a, DependsOnID: c, Type: publicops.DepRelated}, + }, + }); err != nil { + t.Fatalf("AddDependencies: %v", err) + } + assertDependencyEditorHistoryDelta(t, ctx, fixture, before, 1, "two edges are ONE history entry") + + before = dependencyEditorHistoryCount(t, ctx, fixture) + if _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{{IssueID: b, DependsOnID: a, Type: publicops.DepBlocks}}, + }); !errors.Is(err, publicops.ErrDependencyCycle) { + t.Fatalf("cycle error = %v, want ErrDependencyCycle", err) + } + assertDependencyEditorHistoryDelta(t, ctx, fixture, before, 0, "a refused request records no history") + + before = dependencyEditorHistoryCount(t, ctx, fixture) + removed, err := fixture.Editor.RemoveDependency(ctx, publicops.RemoveDependencyRequest{ + Actor: "writer", IssueID: a, DependsOnID: b, + }) + if err != nil || !removed.Removed { + t.Fatalf("RemoveDependency = %#v, %v; want Removed true", removed, err) + } + assertDependencyEditorHistoryDelta(t, ctx, fixture, before, 1, "a removal that found its edge is one history entry") + + before = dependencyEditorHistoryCount(t, ctx, fixture) + removed, err = fixture.Editor.RemoveDependency(ctx, publicops.RemoveDependencyRequest{ + Actor: "writer", IssueID: a, DependsOnID: b, + }) + if err != nil || removed.Removed { + t.Fatalf("replayed RemoveDependency = %#v, %v; want Removed false and a nil error", removed, err) + } + assertDependencyEditorHistoryDelta(t, ctx, fixture, before, 0, "a removal that found nothing records no history") +} + +// RunDependencyEditorRecordsNoHistoryForAnAllEphemeralRequest pins +// dependencyeditor.go:122-123: only the durable half of the graph is versioned, +// so a request made entirely of ephemeral edges records no history entry. An +// edge is ephemeral when its SOURCE is, independently of the target's plane, +// which is why one of the two edges here points at a durable issue. +func RunDependencyEditorRecordsNoHistoryForAnAllEphemeralRequest(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + if fixture.CountHistory == nil { + t.Skip("fixture.CountHistory is nil: this backend cannot observe history, so the no-entry-for-ephemeral-edges clause cannot be checked here") + } + wisp := fixture.IssuePrefix + "-ephhist-wisp" + otherWisp := fixture.IssuePrefix + "-ephhist-wisp2" + issue := fixture.IssuePrefix + "-ephhist-issue" + seedDependencyEditorWisp(t, ctx, fixture, wisp) + seedDependencyEditorWisp(t, ctx, fixture, otherWisp) + seedDependencyEditorIssue(t, ctx, fixture, issue) + + before := dependencyEditorHistoryCount(t, ctx, fixture) + if _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{ + {IssueID: wisp, DependsOnID: issue, Type: publicops.DepBlocks}, + {IssueID: otherWisp, DependsOnID: wisp, Type: publicops.DepRelated}, + }, + }); err != nil { + t.Fatalf("AddDependencies on an all-ephemeral request: %v", err) + } + assertDependencyEdgeTypedCount(t, ctx, fixture, "wisp_dependencies", wisp, issue, string(publicops.DepBlocks), 1) + assertDependencyEdgeTypedCount(t, ctx, fixture, "wisp_dependencies", otherWisp, wisp, string(publicops.DepRelated), 1) + assertDependencyEditorHistoryDelta(t, ctx, fixture, before, 0, + "the wisp plane is not versioned, so a request made entirely of ephemeral edges records no history entry") +} + +// RunDependencyEditorSnapshotsTheRequest pins dependencyeditor.go:137-138: +// implementations never mutate caller-owned request values and snapshot the +// request at method entry. +// +// The observable half of that is the result. Added is documented as echoing +// the request, and an implementation that echoed it by handing the caller's own +// slice back would satisfy every equality check in this file while quietly +// aliasing state the caller still owns — so the caller mutates its slice after +// the call and the result must not move. +func RunDependencyEditorSnapshotsTheRequest(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + source := fixture.IssuePrefix + "-snap-source" + target := fixture.IssuePrefix + "-snap-target" + seedDependencyEditorIssue(t, ctx, fixture, source) + seedDependencyEditorIssue(t, ctx, fixture, target) + + edges := []publicops.DependencyEdge{{IssueID: source, DependsOnID: target, Type: publicops.DepBlocks}} + request := publicops.AddDependenciesRequest{Actor: "writer", Edges: edges} + result, err := fixture.Editor.AddDependencies(ctx, request) + if err != nil { + t.Fatalf("AddDependencies: %v", err) + } + if edges[0] != (publicops.DependencyEdge{IssueID: source, DependsOnID: target, Type: publicops.DepBlocks}) { + t.Fatalf("the caller's edge = %#v after the call, want it untouched", edges[0]) + } + + edges[0].DependsOnID = "rewritten-by-the-caller" + if len(result.Added) != 1 || result.Added[0].DependsOnID != target { + t.Fatalf("Added = %#v after the caller rewrote its own slice, want the edge it asked for: the result must not alias the request", result.Added) + } +} + +// RunDependencyEditorValidationRefusalsWriteNothing pins +// dependencyeditor.go:139-140: deterministic request-validation failures match +// ErrValidation and leave persistent state unchanged. +// +// The sentinel itself is pinned against the shared Validate* functions in a +// unit test; what only a live backend can show is the second half — that the +// refusal happened before anything was written, including for the edges of a +// batch that preceded the invalid one. +func RunDependencyEditorValidationRefusalsWriteNothing(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + source := fixture.IssuePrefix + "-valid-source" + target := fixture.IssuePrefix + "-valid-target" + seedDependencyEditorIssue(t, ctx, fixture, source) + seedDependencyEditorIssue(t, ctx, fixture, target) + + valid := publicops.DependencyEdge{IssueID: source, DependsOnID: target, Type: publicops.DepBlocks} + for _, refusal := range []struct { + name string + request publicops.AddDependenciesRequest + }{ + {"no actor", publicops.AddDependenciesRequest{Edges: []publicops.DependencyEdge{valid}}}, + {"no edges", publicops.AddDependenciesRequest{Actor: "writer"}}, + {"an edge with no type", publicops.AddDependenciesRequest{Actor: "writer", Edges: []publicops.DependencyEdge{ + valid, + {IssueID: source, DependsOnID: target + "-2"}, + }}}, + } { + if _, err := fixture.Editor.AddDependencies(ctx, refusal.request); !errors.Is(err, publicops.ErrValidation) { + t.Errorf("AddDependencies with %s: error = %v, want ErrValidation", refusal.name, err) + } + } + if _, err := fixture.Editor.RemoveDependency(ctx, publicops.RemoveDependencyRequest{ + IssueID: source, DependsOnID: target, + }); !errors.Is(err, publicops.ErrValidation) { + t.Errorf("RemoveDependency with no actor: error = %v, want ErrValidation", err) + } + assertDependencyEditorNoEdgesFrom(t, ctx, fixture, source) +} + +// RunDependencyEditorRoutesWispSourcedRemovalToTheWispPlane pins the REMOVE +// half of dependencyeditor.go:117-123. An edge follows its source on BOTH +// methods, so removing a wisp-sourced edge deletes from wisp_dependencies, +// leaves the durable pair untouched, and records no history entry — only the +// durable half is versioned. +// +// The add side of that clause got four cases because routing is what the three +// implementations had actually diverged on. The remove side had none at this +// seam, and it is a genuinely separate decision in the code: the add pins +// routing from a source set read once for the whole request, a removal reads it +// per call. +// +// The wisp_events assertions are contractual now rather than a probe: the leaf +// promises the entry follows the source's plane, and says why that matters +// most for an ephemeral edge — the wisp plane is not versioned, so the entry is +// the only record the operation leaves. +func RunDependencyEditorRoutesWispSourcedRemovalToTheWispPlane(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + wisp := fixture.IssuePrefix + "-wrm-wisp" + target := fixture.IssuePrefix + "-wrm-target" + seedDependencyEditorWisp(t, ctx, fixture, wisp) + seedDependencyEditorIssue(t, ctx, fixture, target) + + if _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{{IssueID: wisp, DependsOnID: target, Type: publicops.DepBlocks}}, + }); err != nil { + t.Fatalf("seed the wisp-sourced edge to remove: %v", err) + } + assertDependencyEdgeCount(t, ctx, fixture, "wisp_dependencies", wisp, target, 1) + + request := publicops.RemoveDependencyRequest{Actor: "remover", IssueID: wisp, DependsOnID: target} + assertHistoryDelta := dependencyEditorHistoryProbe(t, ctx, fixture) + removed, err := fixture.Editor.RemoveDependency(ctx, request) + if err != nil { + t.Fatalf("RemoveDependency on a wisp-sourced edge: %v", err) + } + if !removed.Removed { + t.Error("Removed = false, want true: the edge was there, in the plane its SOURCE lives in") + } + assertDependencyEditorOutgoingCount(t, ctx, fixture, "wisp_dependencies", wisp, 0) + assertDependencyEditorOutgoingCount(t, ctx, fixture, "dependencies", wisp, 0) + assertDependencyEditorEventCount(t, ctx, fixture, "wisp_events", wisp, types.EventDependencyRemoved, 1) + assertDependencyEditorEventCount(t, ctx, fixture, "events", wisp, types.EventDependencyRemoved, 0) + assertHistoryDelta(0, "the wisp plane is not versioned, so removing an ephemeral edge records no history entry") + + assertHistoryDelta = dependencyEditorHistoryProbe(t, ctx, fixture) + removed, err = fixture.Editor.RemoveDependency(ctx, request) + if err != nil { + t.Fatalf("replayed RemoveDependency on a wisp-sourced edge = %v, want nil: a missing edge is a success in either plane", err) + } + if removed.Removed { + t.Error("Removed = true, want false for a wisp-sourced edge that was already gone") + } + assertDependencyEditorEventCount(t, ctx, fixture, "wisp_events", wisp, types.EventDependencyRemoved, 1) + assertHistoryDelta(0, "a removal that found nothing records no history in either plane") +} + +// RunDependencyEditorRefusesAGhostSource pins the fifth refusal in +// dependencyeditor.go:143-148 — "a SOURCE that does not exist" — together with +// its all-or-nothing consequence: the edge of the same request that was already +// written comes back out. +// +// The ghost id is a strict PREFIX of a seeded id rather than a random unknown +// one, so the case doubles as the pin for dependencyeditor.go:34-37: both +// endpoints are exact canonical ids and there is no prefix resolution on this +// contract. A backend that resolved it would land the edge under the seeded id +// instead of refusing, and the ordinary unknown-id spelling could never tell. +// +// This refusal is checked ahead of the target's (dependencies.go:214-235), so +// the target here is deliberately a real seeded issue: the refusal under test +// is about the source alone. +// +// SPEC-GAP bd-yby99.9: the doc now states that the refusal HAPPENS and states +// that it deliberately names no identity yet, so err != nil is still the whole +// assertion — pinning a sentinel or a message here would assert more than the +// leaf says, and the leaf says the anonymity is a gap rather than a promise. +func RunDependencyEditorRefusesAGhostSource(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + source := fixture.IssuePrefix + "-ghostsrc-known" + target := fixture.IssuePrefix + "-ghostsrc-target" + seedDependencyEditorIssue(t, ctx, fixture, source) + seedDependencyEditorIssue(t, ctx, fixture, target) + ghost := source[:len(source)-1] + + if _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{ + {IssueID: source, DependsOnID: target, Type: publicops.DepBlocks}, + {IssueID: ghost, DependsOnID: target, Type: publicops.DepBlocks}, + }, + }); err == nil { + t.Fatalf("AddDependencies from the nonexistent source %q = nil error, want a refusal: %q exists but is a different id", ghost, source) + } + assertDependencyEditorNoEdgesFrom(t, ctx, fixture, source, ghost) +} + +// RunDependencyEditorRefusesAMissingLocalTarget pins the refusal half of the +// target-existence clause. Existence is checked "only where the backend can +// see it", and the two acceptance cases above pin what that therefore does NOT +// refuse — an "external:" reference and an issue in another repository. The +// leaf now states the half neither of them covers outright: a target whose +// absence the backend CAN see — same prefix, no "external:" marker, no row — +// is refused and nothing is written. Without it the clause reads as a blanket +// amnesty, which is the opposite of what it says. +// +// SPEC-GAP bd-yby99.9: the refusal's IDENTITY is still unnamed, and the leaf +// now says so deliberately, so err != nil is all this asserts. +func RunDependencyEditorRefusesAMissingLocalTarget(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + source := fixture.IssuePrefix + "-notgt-source" + seedDependencyEditorIssue(t, ctx, fixture, source) + // Same prefix as the source, so it is neither an external reference nor + // another repository's id: this database is exactly where it would be. + missing := fixture.IssuePrefix + "-notgt-ghost" + + if _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{{IssueID: source, DependsOnID: missing, Type: publicops.DepBlocks}}, + }); err == nil { + t.Fatalf("AddDependencies onto the missing local target %q = nil error, want a refusal", missing) + } + assertDependencyEditorNoEdgesFrom(t, ctx, fixture, source) +} + +// dependencyEditorUnlistedType is a DependencyType deliberately absent from the +// Dep* constants: a plausible workspace-configured value, short enough for the +// column, and outside the scheduling set, so nothing but the open-set rule +// decides whether it is accepted. +const dependencyEditorUnlistedType publicops.DependencyType = "caused-by" + +// RunDependencyEditorAcceptsATypeOutsideTheConstants pins the open-set rule +// (dependencyeditor.go:13-19, :41-44) END TO END. An implementation that +// refused a type absent from the constants "would break every workspace that +// spelled one of its own", and the constants "never authorize" a value — so +// acceptance cannot be a property of the listed six. +// +// The validator half is owned by a unit test against +// ValidateAddDependenciesRequest. What only a live backend can show is the rest +// of the write path: the scheduling-edge switch that reads the type, the target +// classification, the type column itself, and the existing-edge lookup that has +// to recognize the unlisted value as the SAME type on a re-add rather than +// raising a conflict against something it does not know. +func RunDependencyEditorAcceptsATypeOutsideTheConstants(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + source := fixture.IssuePrefix + "-opentype-source" + target := fixture.IssuePrefix + "-opentype-target" + seedDependencyEditorIssue(t, ctx, fixture, source) + seedDependencyEditorIssue(t, ctx, fixture, target) + + request := publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{{IssueID: source, DependsOnID: target, Type: dependencyEditorUnlistedType}}, + } + result, err := fixture.Editor.AddDependencies(ctx, request) + if err != nil { + t.Fatalf("AddDependencies with the unlisted type %q: %v — the vocabulary is an open set", dependencyEditorUnlistedType, err) + } + if len(result.Added) != 1 || result.Added[0].Type != dependencyEditorUnlistedType { + t.Errorf("Added = %#v, want the edge as spelled: the result must not normalize a type to a listed one", result.Added) + } + assertDependencyEdgeTypedCount(t, ctx, fixture, "dependencies", source, target, string(dependencyEditorUnlistedType), 1) + + if _, err := fixture.Editor.AddDependencies(ctx, request); err != nil { + t.Fatalf("re-adding the unlisted-type edge refused: %v — same type is idempotent whatever the type is", err) + } + assertDependencyEditorOutgoingCount(t, ctx, fixture, "dependencies", source, 1) + assertDependencyEdgeTypedCount(t, ctx, fixture, "dependencies", source, target, string(dependencyEditorUnlistedType), 1) +} + +// RunDependencyEditorRemovesOnlyTheNamedEdge pins "removes exactly the named +// edge" (dependencyeditor.go:180) as a statement about the edges it does NOT +// touch: a sibling edge from the same source survives a removal aimed at its +// neighbor. +// +// The edge removed is the "external:" one, which makes this the REMOVAL half of +// :136-139 as well. A target the backend cannot resolve is still a target a +// caller may name, and it lives in a different column from an ordinary one — +// so an implementation that matched removals against depends_on_issue_id alone +// reports Removed false here and leaves the edge in place. +func RunDependencyEditorRemovesOnlyTheNamedEdge(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + source := fixture.IssuePrefix + "-rmnamed-source" + sibling := fixture.IssuePrefix + "-rmnamed-sibling" + const external = "external:https://example.invalid/tracker/44" + seedDependencyEditorIssue(t, ctx, fixture, source) + seedDependencyEditorIssue(t, ctx, fixture, sibling) + + if _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{ + {IssueID: source, DependsOnID: sibling, Type: publicops.DepBlocks}, + {IssueID: source, DependsOnID: external, Type: publicops.DepRelated}, + }, + }); err != nil { + t.Fatalf("seed the two edges from one source: %v", err) + } + assertDependencyEditorOutgoingCount(t, ctx, fixture, "dependencies", source, 2) + + removed, err := fixture.Editor.RemoveDependency(ctx, publicops.RemoveDependencyRequest{ + Actor: "remover", IssueID: source, DependsOnID: external, + }) + if err != nil { + t.Fatalf("RemoveDependency naming the external target: %v", err) + } + if !removed.Removed { + t.Error("Removed = false, want true: an external target is still an edge a caller can name") + } + assertDependencyEdgeTypedCount(t, ctx, fixture, "dependencies", source, external, string(publicops.DepRelated), 0) + assertDependencyEdgeTypedCount(t, ctx, fixture, "dependencies", source, sibling, string(publicops.DepBlocks), 1) + assertDependencyEditorOutgoingCount(t, ctx, fixture, "dependencies", source, 1) +} + +// RunDependencyEditorSkipPerEdgeCycleCheckDropsOnlyTheProbe pins the rest of +// dependencyeditor.go:66-71. Two existing cases show what the flag does NOT +// drop — the whole-graph gate and the self-dependency refusal — but both are +// refusals, and so is every other skip=true request in this file. Nothing yet +// shows the flag doing the thing it exists for: a caller wiring a large acyclic +// graph gets the graph, and gets it persisted. +// +// The second half is that the other typed refusals still fire under it. A +// backend that read the flag as "skip validation" rather than "skip the +// per-edge cycle probe" passes every existing case in this file and fails this +// one. +func RunDependencyEditorSkipPerEdgeCycleCheckDropsOnlyTheProbe(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + a := fixture.IssuePrefix + "-skipok-a" + b := fixture.IssuePrefix + "-skipok-b" + c := fixture.IssuePrefix + "-skipok-c" + for _, id := range []string{a, b, c} { + seedDependencyEditorIssue(t, ctx, fixture, id) + } + + result, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + SkipPerEdgeCycleCheck: true, + Edges: []publicops.DependencyEdge{ + {IssueID: a, DependsOnID: b, Type: publicops.DepBlocks}, + {IssueID: b, DependsOnID: c, Type: publicops.DepBlocks}, + }, + }) + if err != nil { + t.Fatalf("AddDependencies on an acyclic graph with the probe skipped: %v", err) + } + if len(result.Added) != 2 { + t.Errorf("Added = %#v, want both edges", result.Added) + } + assertDependencyEdgeTypedCount(t, ctx, fixture, "dependencies", a, b, string(publicops.DepBlocks), 1) + assertDependencyEdgeTypedCount(t, ctx, fixture, "dependencies", b, c, string(publicops.DepBlocks), 1) + + _, err = fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + SkipPerEdgeCycleCheck: true, + Edges: []publicops.DependencyEdge{{IssueID: a, DependsOnID: b, Type: publicops.DepRelated}}, + }) + var conflict *publicops.DependencyTypeConflictError + if !errors.As(err, &conflict) { + t.Fatalf("retype with the probe skipped: error = %v, want *DependencyTypeConflictError: the flag drops the cycle probe, not the typed refusals", err) + } + assertDependencyEdgeTypedCount(t, ctx, fixture, "dependencies", a, b, string(publicops.DepBlocks), 1) + assertDependencyEditorOutgoingCount(t, ctx, fixture, "dependencies", a, 1) +} + +// RunDependencyEditorRecordsOneHistoryEntryForAMixedPlaneRequest interpolates +// between the two endpoints the file already pins: an all-durable request is +// one entry (RunDependencyEditorRecordsOneHistoryEntryPerLandedRequest) and an +// all-ephemeral one is none +// (RunDependencyEditorRecordsNoHistoryForAnAllEphemeralRequest). A request that +// mixes the planes is still ONE transaction (dependencyeditor.go:121) of which +// only the durable half is versioned (:117-118) — so one entry. Not two, which +// is what a backend versioning per plane rather than per request would record, +// and not zero, which is what a backend deciding "this request touches the +// ephemeral plane" once for the whole request would record. +func RunDependencyEditorRecordsOneHistoryEntryForAMixedPlaneRequest(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) { + t.Helper() + if fixture.CountHistory == nil { + t.Skip("fixture.CountHistory is nil: this backend cannot observe history, so the mixed-plane entry count cannot be checked here") + } + wisp := fixture.IssuePrefix + "-mixhist-wisp" + issue := fixture.IssuePrefix + "-mixhist-issue" + target := fixture.IssuePrefix + "-mixhist-target" + seedDependencyEditorWisp(t, ctx, fixture, wisp) + seedDependencyEditorIssue(t, ctx, fixture, issue) + seedDependencyEditorIssue(t, ctx, fixture, target) + + before := dependencyEditorHistoryCount(t, ctx, fixture) + if _, err := fixture.Editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{ + {IssueID: wisp, DependsOnID: target, Type: publicops.DepBlocks}, + {IssueID: issue, DependsOnID: target, Type: publicops.DepBlocks}, + }, + }); err != nil { + t.Fatalf("AddDependencies on a mixed-plane request: %v", err) + } + assertDependencyEdgeCount(t, ctx, fixture, "wisp_dependencies", wisp, target, 1) + assertDependencyEdgeCount(t, ctx, fixture, "dependencies", issue, target, 1) + assertDependencyEditorHistoryDelta(t, ctx, fixture, before, 1, + "a request spanning both planes is one transaction with one versioned half, so it is ONE history entry") +} + +func seedDependencyEditorIssue(t *testing.T, ctx context.Context, fixture DependencyEditorFixture, id string) { + t.Helper() + if err := fixture.CreateIssue(ctx, dependencyEditorSeed(id, false), "seed"); err != nil { + t.Fatalf("seed issue %s: %v", id, err) + } +} + +func seedDependencyEditorWisp(t *testing.T, ctx context.Context, fixture DependencyEditorFixture, id string) { + t.Helper() + if err := fixture.CreateWisp(ctx, dependencyEditorSeed(id, true), "seed"); err != nil { + t.Fatalf("seed wisp %s: %v", id, err) + } +} + +func dependencyEditorSeed(id string, ephemeral bool) *types.Issue { + return &types.Issue{ + ID: id, + Title: id, + Status: types.StatusOpen, + Priority: 2, + IssueType: types.TypeTask, + Ephemeral: ephemeral, + } +} + +// assertDependencyEdgeCount counts edges from source to target in one +// dependency table. The target is matched through the resolved target +// expression because a target's own class decides which typed column holds it, +// independently of the source routing under test. +func assertDependencyEdgeCount(t *testing.T, ctx context.Context, fixture DependencyEditorFixture, table, source, target string, want int) { + t.Helper() + var got int + //nolint:gosec // G201: table is one of the contract's two hardcoded names. + query := "SELECT COUNT(*) FROM " + table + + " WHERE issue_id = ? AND COALESCE(depends_on_issue_id, depends_on_wisp_id, depends_on_external) = ?" + if err := fixture.QueryScalar(ctx, query, []any{source, target}, &got); err != nil { + t.Fatalf("count %s edges %s -> %s: %v", table, source, target, err) + } + if got != want { + t.Errorf("%s edges %s -> %s = %d, want %d", table, source, target, got, want) + } +} + +func assertDependencyEdgeTypedCount(t *testing.T, ctx context.Context, fixture DependencyEditorFixture, table, source, target, depType string, want int) { + t.Helper() + var got int + //nolint:gosec // G201: table is one of the contract's two hardcoded names. + query := "SELECT COUNT(*) FROM " + table + + " WHERE issue_id = ? AND COALESCE(depends_on_issue_id, depends_on_wisp_id, depends_on_external) = ? AND type = ?" + if err := fixture.QueryScalar(ctx, query, []any{source, target, depType}, &got); err != nil { + t.Fatalf("count %s %s edges %s -> %s: %v", table, depType, source, target, err) + } + if got != want { + t.Errorf("%s %s edges %s -> %s = %d, want %d", table, depType, source, target, got, want) + } +} + +// assertDependencyEditorEventCount counts events of one type for one issue. +// Both event types the role writes go through it — the add cases read +// dependency_added, the removal cases dependency_removed — because the two +// differ only in that argument, and a second helper pinned to one of them was +// a copy waiting to drift. +func assertDependencyEditorEventCount(t *testing.T, ctx context.Context, fixture DependencyEditorFixture, table, issueID string, eventType types.EventType, want int) { + t.Helper() + var got int + //nolint:gosec // G201: table is one of the contract's two hardcoded names. + query := "SELECT COUNT(*) FROM " + table + " WHERE issue_id = ? AND event_type = ?" + if err := fixture.QueryScalar(ctx, query, []any{issueID, string(eventType)}, &got); err != nil { + t.Fatalf("count %s %s rows for %s: %v", table, eventType, issueID, err) + } + if got != want { + t.Errorf("%s %s rows for %s = %d, want %d", table, eventType, issueID, got, want) + } +} + +// assertDependencyEditorEventActor reads the actor off the one event of a +// given type for one issue. It reads the DURABLE stream only: the attribution +// clause is about who is recorded, and the plane that record lands in is +// already pinned by the routing cases. +func assertDependencyEditorEventActor(t *testing.T, ctx context.Context, fixture DependencyEditorFixture, issueID string, eventType types.EventType, want string) { + t.Helper() + var got string + if err := fixture.QueryScalar(ctx, + "SELECT COALESCE(actor, '') FROM events WHERE issue_id = ? AND event_type = ?", + []any{issueID, string(eventType)}, &got); err != nil { + t.Fatalf("read the %s actor for %s: %v", eventType, issueID, err) + } + if got != want { + t.Errorf("%s actor for %s = %q, want %q: the entry is attributed to the request's Actor", eventType, issueID, got, want) + } +} + +// assertDependencyEditorOutgoingCount counts ALL outgoing edges from one source +// in one table. Paired with assertDependencyEdgeTypedCount it pins a whole +// neighbor set: the typed count says the right edge is there, this one says +// nothing else is. +func assertDependencyEditorOutgoingCount(t *testing.T, ctx context.Context, fixture DependencyEditorFixture, table, source string, want int) { + t.Helper() + var got int + //nolint:gosec // G201: table is one of the contract's two hardcoded names. + query := "SELECT COUNT(*) FROM " + table + " WHERE issue_id = ?" + if err := fixture.QueryScalar(ctx, query, []any{source}, &got); err != nil { + t.Fatalf("count %s edges from %s: %v", table, source, err) + } + if got != want { + t.Errorf("%s edges from %s = %d, want %d", table, source, got, want) + } +} + +// assertDependencyEditorNoEdgesFrom is how a refusal case spells "the request +// is all-or-nothing". It counts BOTH planes for each source, because a refused +// request that left an ephemeral edge behind is exactly the partial commit the +// all-or-nothing rule exists to prevent. +func assertDependencyEditorNoEdgesFrom(t *testing.T, ctx context.Context, fixture DependencyEditorFixture, sources ...string) { + t.Helper() + for _, source := range sources { + for _, table := range []string{"dependencies", "wisp_dependencies"} { + assertDependencyEditorOutgoingCount(t, ctx, fixture, table, source, 0) + } + } +} + +func dependencyEditorHistoryCount(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) int { + t.Helper() + entries, err := fixture.CountHistory(ctx) + if err != nil { + t.Fatalf("CountHistory: %v", err) + } + return entries +} + +func assertDependencyEditorHistoryDelta(t *testing.T, ctx context.Context, fixture DependencyEditorFixture, before, want int, why string) { + t.Helper() + after := dependencyEditorHistoryCount(t, ctx, fixture) + if after-before != want { + t.Errorf("history entries went %d -> %d (delta %d), want a delta of %d: %s", before, after, after-before, want, why) + } +} + +// dependencyEditorHistoryProbe takes the history count now and returns the +// assertion for the delta since. It is for cases whose SUBJECT is something +// else and whose history count is one assertion among several: those must keep +// running on a fixture that cannot observe history rather than skip whole, the +// way the two cases about history itself correctly do. +func dependencyEditorHistoryProbe(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) func(want int, why string) { + t.Helper() + if fixture.CountHistory == nil { + return func(int, string) { + t.Log("fixture.CountHistory is nil: this backend cannot observe history, so only the history half of this case is unchecked") + } + } + before := dependencyEditorHistoryCount(t, ctx, fixture) + return func(want int, why string) { + t.Helper() + assertDependencyEditorHistoryDelta(t, ctx, fixture, before, want, why) + } +} diff --git a/backend/conformance/issue_operations_contract.go b/backend/conformance/issue_operations_contract.go index 25f52e258..283db8458 100644 --- a/backend/conformance/issue_operations_contract.go +++ b/backend/conformance/issue_operations_contract.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "reflect" + "sort" "strings" "testing" "time" @@ -751,3 +752,964 @@ func (c *issueOperationsEventCounter) assert(t *testing.T, label string, wantTot c.byType[eventType] = c.count(t, eventType) } } + +// RunIssueOperationsUpdateClaimConflictCarriesTheLosingState pins the payload a +// lost claim comes back with. The leaf promises a *ClaimConflictError "carrying +// the state that beat it" (issueops/issueops.go:399-401) and says which sentinel +// each shape wears: a foreign assignment is ErrAlreadyClaimed, an ineligible +// status is ErrNotClaimable (issueops.go:215-217). +// +// The sentinel alone was already reachable; the TYPED fields were not. A caller +// that reports who won without parsing prose reads them, and the two +// implementations that build this error do so from separate reads — the +// store-backed body re-selects the row after a lost CAS +// (internal/storage/issueops/claim.go:154), the unit-of-work one takes what the +// repository handed back (internal/storage/domain/issue.go:566) — so nothing but +// a case over both spellings keeps the payload honest. +func RunIssueOperationsUpdateClaimConflictCarriesTheLosingState(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture) { + t.Helper() + + heldID := fixture.IssuePrefix + "-claimconflict-held" + seedClosePolicyIssue(t, ctx, fixture, heldID, publicops.CreateRequest{}) + if _, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "holder", IssueID: heldID, Claim: true}); err != nil { + t.Fatalf("claim %s for holder: %v", heldID, err) + } + assertLiveAssignee(t, ctx, fixture, heldID, "holder") + + // A foreign live claim: the refusal names the holder and the status that + // beat the compare-and-set, and writes nothing. + events := newIssueOperationsEventCounter(t, ctx, fixture, heldID) + _, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "rival", IssueID: heldID, Claim: true}) + conflict := assertIssueOperationsClaimConflict(t, err, "foreign live claim", heldID) + if conflict != nil { + if conflict.Assignee != "holder" { + t.Errorf("foreign claim conflict Assignee = %q, want %q", conflict.Assignee, "holder") + } + if conflict.Status != types.StatusInProgress { + t.Errorf("foreign claim conflict Status = %q, want %q", conflict.Status, types.StatusInProgress) + } + } + if !errors.Is(err, publicops.ErrAlreadyClaimed) { + t.Errorf("foreign claim error = %v, want ErrAlreadyClaimed", err) + } + if errors.Is(err, publicops.ErrNotClaimable) { + t.Errorf("foreign claim error = %v, want it NOT to match ErrNotClaimable — the leaf gives the two shapes different sentinels", err) + } + assertLiveAssignee(t, ctx, fixture, heldID, "holder") + events.assert(t, "refused foreign claim", 0, nil) + + // An ineligible status: nobody holds the issue, so the refusal carries the + // status rather than an assignee, and wears the other sentinel. + deferredID := fixture.IssuePrefix + "-claimconflict-deferred" + seedClosePolicyIssue(t, ctx, fixture, deferredID, publicops.CreateRequest{}) + if err := fixture.UpdateRaw(ctx, deferredID, map[string]any{"status": string(types.StatusDeferred)}, "writer"); err != nil { + t.Fatalf("defer %s: %v", deferredID, err) + } + deferredEvents := newIssueOperationsEventCounter(t, ctx, fixture, deferredID) + _, err = fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "claimant", IssueID: deferredID, Claim: true}) + conflict = assertIssueOperationsClaimConflict(t, err, "ineligible status claim", deferredID) + if conflict != nil { + if conflict.Status != types.StatusDeferred { + t.Errorf("ineligible-status conflict Status = %q, want %q", conflict.Status, types.StatusDeferred) + } + if conflict.Assignee != "" { + t.Errorf("ineligible-status conflict Assignee = %q, want empty — nobody held it", conflict.Assignee) + } + } + if !errors.Is(err, publicops.ErrNotClaimable) { + t.Errorf("ineligible-status claim error = %v, want ErrNotClaimable", err) + } + if errors.Is(err, publicops.ErrAlreadyClaimed) { + t.Errorf("ineligible-status claim error = %v, want it NOT to match ErrAlreadyClaimed", err) + } + assertIssueOperationsAssigneeAndStatus(t, ctx, fixture, deferredID, "", types.StatusDeferred) + deferredEvents.assert(t, "refused ineligible claim", 0, nil) +} + +// assertIssueOperationsClaimConflict checks the refusal is the typed conflict +// naming the issue, and hands it back so the caller can assert the payload. It +// reports rather than fatals on the type so one bad shape does not hide the +// other arm's evidence. +func assertIssueOperationsClaimConflict(t *testing.T, err error, label, id string) *publicops.ClaimConflictError { + t.Helper() + if err == nil { + t.Fatalf("%s: err = nil, want a claim conflict", label) + } + var conflict *publicops.ClaimConflictError + if !errors.As(err, &conflict) { + t.Errorf("%s: err = %v (%T), want *ClaimConflictError", label, err, err) + return nil + } + if conflict.IssueID != id { + t.Errorf("%s: conflict IssueID = %q, want %q", label, conflict.IssueID, id) + } + return conflict +} + +// RunIssueOperationsUpdateClaimHonorsConfiguredActiveStatuses pins the claim +// eligibility rule at the Lifecycle seam: the leaf says an issue is claimable +// from "built-in StatusOpen or a configured active status" +// (issueops/issueops.go:213-217), so a workspace that spells its own +// draft -> ready -> in_progress lifecycle can claim from ready, and a wip +// custom stays fenced. +// +// Both claim bodies resolve the vocabulary through +// issueops.ClaimableSourceStatusesInTx, but they build the SQL predicate around +// it separately (internal/storage/issueops/claim.go:65 vs +// internal/storage/domain/db/issue.go:373), and the only test that covered this +// spoke to one store's ClaimIssue rather than to the guarded verb. +func RunIssueOperationsUpdateClaimHonorsConfiguredActiveStatuses(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture) { + t.Helper() + + if err := fixture.SetConfig(ctx, "status.custom", "ready:active,reviewing:wip"); err != nil { + t.Fatalf("SetConfig(status.custom): %v", err) + } + + // The create path validates status against a vocabulary that does not parse + // the "name:category" spelling, so each row is created open and moved with + // the raw funnel — the same way a custom-status row comes to exist in a real + // workspace. + readyID := fixture.IssuePrefix + "-customclaim-ready" + reviewingID := fixture.IssuePrefix + "-customclaim-reviewing" + for _, seed := range []struct { + id string + status types.Status + }{{readyID, "ready"}, {reviewingID, "reviewing"}} { + seedClosePolicyIssue(t, ctx, fixture, seed.id, publicops.CreateRequest{}) + if err := fixture.UpdateRaw(ctx, seed.id, map[string]any{"status": string(seed.status)}, "writer"); err != nil { + t.Fatalf("move %s to %s: %v", seed.id, seed.status, err) + } + } + + claimed, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "agent-a", IssueID: readyID, Claim: true}) + if err != nil { + t.Fatalf("claim %s from a configured active status: %v", readyID, err) + } + if !claimed.Changed { + t.Errorf("claiming %s from a configured active status reported Changed = false, want a committed claim", readyID) + } + if claimed.Issue.Assignee != "agent-a" || claimed.Issue.Status != types.StatusInProgress { + t.Errorf("claim result = assignee %q status %q, want agent-a/in_progress", claimed.Issue.Assignee, claimed.Issue.Status) + } + assertLiveAssignee(t, ctx, fixture, readyID, "agent-a") + + // A wip custom is not an active custom, so the anti-steal fence still holds + // and the row is untouched. + events := newIssueOperationsEventCounter(t, ctx, fixture, reviewingID) + _, err = fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "agent-b", IssueID: reviewingID, Claim: true}) + if !errors.Is(err, publicops.ErrNotClaimable) { + t.Fatalf("claim %s from a configured wip status: err = %v, want ErrNotClaimable", reviewingID, err) + } + assertIssueOperationsAssigneeAndStatus(t, ctx, fixture, reviewingID, "", "reviewing") + events.assert(t, "refused wip-status claim", 0, nil) +} + +// RunIssueOperationsUpdateIssuePlaneOnlyRefusesWisps pins the plane restriction +// the leaf declares on UpdateRequest.IssuePlaneOnly (issueops/issueops.go:251-260): +// with the flag set, an ID that names a wisp is ErrNotFound rather than an +// ephemeral row to update; with the zero value the same ID resolves and the +// update lands. +// +// It was pinned only against a stubbed unit of work, while the store-backed +// backends implement it in their shared execution body with no test at all. +func RunIssueOperationsUpdateIssuePlaneOnlyRefusesWisps(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture) { + t.Helper() + + wispID := fixture.IssuePrefix + "-planeonly-wisp" + if _, err := fixture.Operations.Create(ctx, publicops.CreateRequest{ + Actor: "seed", ForceIDPrefix: true, + Issue: &types.Issue{ID: wispID, Title: "seeded title", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: true}, + }); err != nil { + t.Fatalf("seed wisp %s: %v", wispID, err) + } + assertIssueOperationsRowCount(t, ctx, fixture, "wisps", wispID, 1) + + var beforeRowLock string + if err := fixture.QueryScalar(ctx, "SELECT CAST(row_lock AS CHAR) FROM wisps WHERE id = ?", []any{wispID}, &beforeRowLock); err != nil { + t.Fatalf("read wisp row lock for %s: %v", wispID, err) + } + restricted := publicops.UpdateRequest{ + Actor: "writer", IssueID: wispID, IssuePlaneOnly: true, + Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "restricted title"}}, + } + if _, err := fixture.Operations.Update(ctx, restricted); !errors.Is(err, publicops.ErrNotFound) { + t.Fatalf("issue-plane-only update of wisp %s: err = %v, want ErrNotFound", wispID, err) + } + assertIssueOperationsScalarValue(t, ctx, fixture, "wisp title after refused plane-only update", "seeded title", + "SELECT title FROM wisps WHERE id = ?", []any{wispID}) + assertIssueOperationsScalarValue(t, ctx, fixture, "wisp row lock after refused plane-only update", beforeRowLock, + "SELECT CAST(row_lock AS CHAR) FROM wisps WHERE id = ?", []any{wispID}) + + // The zero value keeps the both-plane auto-resolve, so the same edit lands. + unrestricted := restricted + unrestricted.IssuePlaneOnly = false + landed, err := fixture.Operations.Update(ctx, unrestricted) + if err != nil { + t.Fatalf("both-plane update of wisp %s: %v", wispID, err) + } + if !landed.Changed || landed.Issue.Title != "restricted title" { + t.Fatalf("both-plane update of wisp %s = %#v, want the title edit committed", wispID, landed) + } + assertIssueOperationsScalarValue(t, ctx, fixture, "wisp title after both-plane update", "restricted title", + "SELECT title FROM wisps WHERE id = ?", []any{wispID}) + + // The restriction is about the PLANE, not about the flag: a durable issue + // updates normally with it set. + durableID := fixture.IssuePrefix + "-planeonly-durable" + seedClosePolicyIssue(t, ctx, fixture, durableID, publicops.CreateRequest{}) + durable, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{ + Actor: "writer", IssueID: durableID, IssuePlaneOnly: true, + Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "durable title"}}, + }) + if err != nil { + t.Fatalf("issue-plane-only update of durable %s: %v", durableID, err) + } + if !durable.Changed || durable.Issue.Title != "durable title" { + t.Fatalf("issue-plane-only update of durable %s = %#v, want the title edit committed", durableID, durable) + } +} + +// RunIssueOperationsUpdateLabelPatchOrdering pins the order LabelPatch applies +// its three edits in: Replace, then Add, then Remove, "so removal wins when the +// same label appears in more than one edit" (issueops/issueops.go:56-58). A +// label named in every edit therefore ends up absent, and a patch that restates +// the current set is a no-op. +// +// The store-backed backends resolve the whole patch to a target set before +// touching the label tables (internal/storage/issueops/aggregate.go:276); the +// unit-of-work one replays the three edits as three separate use-case calls +// (internal/storage/domain/issue.go:648-680) and had no LabelPatch coverage of +// any kind. +func RunIssueOperationsUpdateLabelPatchOrdering(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture) { + t.Helper() + + id := fixture.IssuePrefix + "-labelpatch" + seedIssueOperationsLabeledIssue(t, ctx, fixture, id, "old", "shared") + assertIssueOperationsLabels(t, ctx, fixture, id, "seeded", "old", "shared") + + patched, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{ + Labels: publicops.LabelPatch{ + Replace: publicops.Field[[]string]{Set: true, Value: []string{"replace", "shared"}}, + Add: []string{"add", "shared"}, + Remove: []string{"old", "shared"}, + }, + }}) + if err != nil { + t.Fatalf("ordered label patch on %s: %v", id, err) + } + if !patched.Changed { + t.Errorf("ordered label patch on %s reported Changed = false, want a committed edit", id) + } + // "shared" was replaced in, added again, and removed: removal wins. "old" + // survived neither the replacement nor the removal. + assertIssueOperationsStringSet(t, "ordered label patch result labels", patched.Issue.Labels, "add", "replace") + assertIssueOperationsLabels(t, ctx, fixture, id, "after ordered label patch", "add", "replace") + + // A patch that restates the current set changes nothing. + restated, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{ + Labels: publicops.LabelPatch{Replace: publicops.Field[[]string]{Set: true, Value: []string{"replace", "add"}}}, + }}) + if err != nil { + t.Fatalf("restated label patch on %s: %v", id, err) + } + if restated.Changed { + t.Errorf("restating %s's label set reported Changed = true, want a no-op", id) + } + assertIssueOperationsLabels(t, ctx, fixture, id, "after restated label patch", "add", "replace") +} + +// RunIssueOperationsUpdateLabelPatchValueRules pins what LabelPatch now says +// about the VALUES its edits carry, which it said nothing about before: the +// create-side field rules apply, so an overlong label is ErrFieldTooLong and +// the whole update writes nothing; repetition is free in both directions. +// +// The overlong leg is the one with teeth. The label tables are VARCHAR(255), +// so a backend that let the value through would SILENTLY TRUNCATE it and the +// caller would find a label it never asked for — which is why the case asserts +// the refusal AND that no row with that prefix landed, rather than only the +// error. +// +// The empty-string leg was the last thing in this file to be adjudicated +// (bd-yby99.29): the store bodies wrote a labels row keyed on "" and the +// unit-of-work one dropped the entry. Dropping won, so the assertion is a +// NO-OP rather than a partial write — an Add carrying only "" must leave the +// label set alone AND report Changed false, which is what tells a dropped +// entry apart from one that was written and then swept. +func RunIssueOperationsUpdateLabelPatchValueRules(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture) { + t.Helper() + + id := fixture.IssuePrefix + "-labelvalues" + seedIssueOperationsLabeledIssue(t, ctx, fixture, id, "kept") + + overlong := strings.Repeat("x", types.MaxFieldLen+1) + if _, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{ + Labels: publicops.LabelPatch{Add: []string{overlong}}, + }}); !errors.Is(err, publicops.ErrFieldTooLong) { + t.Fatalf("adding a %d-character label: err = %v, want ErrFieldTooLong", len(overlong), err) + } + var truncated int + if err := fixture.QueryScalar(ctx, + "SELECT COUNT(*) FROM labels WHERE issue_id = ? AND label LIKE 'xxx%'", []any{id}, &truncated); err != nil { + t.Fatalf("look for a truncated label on %s: %v", id, err) + } + if truncated != 0 { + t.Errorf("%s carries %d label rows from the refused overlong add, want none: the column would truncate it silently", id, truncated) + } + assertIssueOperationsLabels(t, ctx, fixture, id, "after the refused overlong add", "kept") + + // The same value twice in one edit is applied once. + duplicated, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{ + Labels: publicops.LabelPatch{Add: []string{"twice", "twice"}}, + }}) + if err != nil { + t.Fatalf("adding one label twice in one edit on %s: %v", id, err) + } + if !duplicated.Changed { + t.Errorf("adding a new label twice on %s reported Changed = false, want a committed edit", id) + } + assertIssueOperationsLabels(t, ctx, fixture, id, "after the duplicated add", "kept", "twice") + + // Removing a label the issue does not carry is a no-op. + absent, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{ + Labels: publicops.LabelPatch{Remove: []string{"never-applied"}}, + }}) + if err != nil { + t.Fatalf("removing an absent label from %s: %v", id, err) + } + if absent.Changed { + t.Errorf("removing a label %s does not carry reported Changed = true, want a no-op", id) + } + assertIssueOperationsLabels(t, ctx, fixture, id, "after removing an absent label", "kept", "twice") + + // An empty-string entry is dropped, and dropping it is a NO-OP: an Add + // carrying only "" must not move Changed, because a backend that wrote the + // row and swept it later would also leave the label set correct here. + emptyOnly, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{ + Labels: publicops.LabelPatch{Add: []string{""}}, + }}) + if err != nil { + t.Fatalf("adding an empty-string label to %s: %v", id, err) + } + if emptyOnly.Changed { + t.Errorf("adding only an empty-string label to %s reported Changed = true, want a no-op", id) + } + var emptyRows int + if err := fixture.QueryScalar(ctx, + "SELECT COUNT(*) FROM labels WHERE issue_id = ? AND label = ''", []any{id}, &emptyRows); err != nil { + t.Fatalf("look for an empty label row on %s: %v", id, err) + } + if emptyRows != 0 { + t.Errorf("%s carries %d label rows keyed on the empty string, want none", id, emptyRows) + } + assertIssueOperationsLabels(t, ctx, fixture, id, "after adding an empty-string label", "kept", "twice") + + // The same entry alongside a real one drops only itself, which is the + // reason dropping beat refusing: one stray value does not fail the edit. + mixed, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{ + Labels: publicops.LabelPatch{Replace: publicops.Field[[]string]{Set: true, Value: []string{"kept", ""}}}, + }}) + if err != nil { + t.Fatalf("replacing labels on %s with a real value and an empty one: %v", id, err) + } + if !mixed.Changed { + t.Errorf("replacing %s's labels down to one value reported Changed = false, want a committed edit", id) + } + if err := fixture.QueryScalar(ctx, + "SELECT COUNT(*) FROM labels WHERE issue_id = ? AND label = ''", []any{id}, &emptyRows); err != nil { + t.Fatalf("look for an empty label row on %s after the mixed replace: %v", id, err) + } + if emptyRows != 0 { + t.Errorf("%s carries %d label rows keyed on the empty string after a mixed replace, want none", id, emptyRows) + } + assertIssueOperationsLabels(t, ctx, fixture, id, "after the mixed replace", "kept") +} + +// RunIssueOperationsUpdateParentIDReplacesTheParentEdge pins what a set +// IssuePatch.ParentID does (issueops/issueops.go:144-147): a nonempty value +// replaces the parent with exactly that target and "does not inherit labels" — +// the create-time InheritLabelsFromParent behavior must NOT follow a reparent — +// and a set empty value removes the parent-child edge. Both restatements are +// no-ops. +// +// The label clause is asserted nowhere today, and the unit-of-work backend +// reparents through its own use case (internal/storage/domain/dependency.go:296) +// rather than the shared target-set body the two stores share. +func RunIssueOperationsUpdateParentIDReplacesTheParentEdge(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture) { + t.Helper() + + oldParentID := fixture.IssuePrefix + "-reparent-old" + newParentID := fixture.IssuePrefix + "-reparent-new" + childID := fixture.IssuePrefix + "-reparent-child" + seedClosePolicyIssue(t, ctx, fixture, oldParentID, publicops.CreateRequest{}) + seedIssueOperationsLabeledIssue(t, ctx, fixture, newParentID, "parent-only-label") + seedClosePolicyIssue(t, ctx, fixture, childID, publicops.CreateRequest{ParentID: oldParentID}) + assertIssueOperationsParents(t, ctx, fixture, childID, "seeded", oldParentID) + + reparented, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: childID, Patch: publicops.IssuePatch{ + ParentID: publicops.Field[string]{Set: true, Value: newParentID}, + }}) + if err != nil { + t.Fatalf("reparent %s: %v", childID, err) + } + if !reparented.Changed { + t.Errorf("reparenting %s reported Changed = false, want a committed edit", childID) + } + assertIssueOperationsParents(t, ctx, fixture, childID, "after reparent", newParentID) + assertIssueOperationsStringSet(t, "reparent result labels", reparented.Issue.Labels) + assertIssueOperationsLabels(t, ctx, fixture, childID, "after reparent") + + restated, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: childID, Patch: publicops.IssuePatch{ + ParentID: publicops.Field[string]{Set: true, Value: newParentID}, + }}) + if err != nil { + t.Fatalf("restate %s's parent: %v", childID, err) + } + if restated.Changed { + t.Errorf("restating %s's parent reported Changed = true, want a no-op", childID) + } + assertIssueOperationsParents(t, ctx, fixture, childID, "after restated parent", newParentID) + + cleared, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: childID, Patch: publicops.IssuePatch{ + ParentID: publicops.Field[string]{Set: true, Value: ""}, + }}) + if err != nil { + t.Fatalf("clear %s's parent: %v", childID, err) + } + if !cleared.Changed { + t.Errorf("clearing %s's parent reported Changed = false, want a committed edit", childID) + } + assertIssueOperationsParents(t, ctx, fixture, childID, "after cleared parent") + + recleared, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: childID, Patch: publicops.IssuePatch{ + ParentID: publicops.Field[string]{Set: true, Value: ""}, + }}) + if err != nil { + t.Fatalf("re-clear %s's parent: %v", childID, err) + } + if recleared.Changed { + t.Errorf("re-clearing %s's parent reported Changed = true, want a no-op", childID) + } +} + +// RunIssueOperationsUpdateParentIDReplacesEveryParent pins the word ALL in the +// leaf's ParentID clause (issueops/issueops.go:144-147): a set nonempty value +// "atomically replaces all parents with exactly that target". A child can carry +// more than one parent edge — create takes ParentID and an explicit +// DepParentChild dependency in the same request — so "all" is a load-bearing +// word and not a restatement of the single-parent case. +func RunIssueOperationsUpdateParentIDReplacesEveryParent(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture) { + t.Helper() + + firstID := fixture.IssuePrefix + "-multiparent-first" + secondID := fixture.IssuePrefix + "-multiparent-second" + thirdID := fixture.IssuePrefix + "-multiparent-third" + childID := fixture.IssuePrefix + "-multiparent-child" + for _, id := range []string{firstID, secondID, thirdID} { + seedClosePolicyIssue(t, ctx, fixture, id, publicops.CreateRequest{}) + } + seedClosePolicyIssue(t, ctx, fixture, childID, publicops.CreateRequest{ + ParentID: firstID, + Dependencies: []publicops.CreateDependency{{TargetID: secondID, Type: types.DepParentChild}}, + }) + assertIssueOperationsParents(t, ctx, fixture, childID, "seeded with two parents", firstID, secondID) + + replaced, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: childID, Patch: publicops.IssuePatch{ + ParentID: publicops.Field[string]{Set: true, Value: thirdID}, + }}) + if err != nil { + t.Fatalf("replace every parent of %s: %v", childID, err) + } + if !replaced.Changed { + t.Errorf("replacing every parent of %s reported Changed = false, want a committed edit", childID) + } + assertIssueOperationsParents(t, ctx, fixture, childID, "after replacing every parent", thirdID) + for _, stale := range []string{firstID, secondID} { + var present int + if err := fixture.QueryScalar(ctx, + "SELECT COUNT(*) FROM dependencies WHERE issue_id = ? AND depends_on_issue_id = ? AND type = ?", + []any{childID, stale, string(types.DepParentChild)}, &present); err != nil { + t.Fatalf("look up replaced parent %s of %s: %v", stale, childID, err) + } + if present != 0 { + t.Errorf("%s kept its edge to replaced parent %s, want every prior parent removed", childID, stale) + } + } +} + +// RunIssueOperationsUpdateMetadataReplaceClearsAndValidates pins +// MetadataPatch.Replace itself: it "replaces the complete metadata document", +// "a nil or empty Value clears metadata", and "a nonempty Value must be valid +// JSON". The exclusivity rule beside it is already pinned; the three clauses +// about the value are not — the clear was asserted only against a private +// unit-of-work helper, and neither arm was pinned behaviorally on any backend. +// +// It also pins the REPRESENTATION the clause now states: metadata is never SQL +// NULL, and an issue created with no metadata holds the same empty document a +// clear leaves behind. The create-side leg is what makes that one fact rather +// than two — without it, "cleared reads as {}" would still leave a caller +// unable to write one filter that matches both ways of having no metadata. +func RunIssueOperationsUpdateMetadataReplaceClearsAndValidates(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture) { + t.Helper() + + bare := fixture.IssuePrefix + "-metadata-bare" + if err := fixture.CreateIssue(ctx, &types.Issue{ + ID: bare, Title: "no metadata at all", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, + }, "seed"); err != nil { + t.Fatalf("seed %s: %v", bare, err) + } + assertIssueOperationsStoredMetadata(t, ctx, fixture, bare, "created with no metadata", `{}`) + assertIssueOperationsMetadataIsNotNull(t, ctx, fixture, bare, "created with no metadata") + + id := fixture.IssuePrefix + "-metadata-replace" + issue := &types.Issue{ + ID: id, Title: "metadata replace", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, + Metadata: json.RawMessage(`{"keep":"old","drop":"old"}`), + } + if err := fixture.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatalf("seed %s: %v", id, err) + } + + // Invalid JSON is refused, and the stored document survives untouched. + events := newIssueOperationsEventCounter(t, ctx, fixture, id) + _, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{ + Metadata: publicops.MetadataPatch{Replace: publicops.Field[json.RawMessage]{Set: true, Value: json.RawMessage(`{"broken":`)}}, + }}) + if !errors.Is(err, publicops.ErrValidation) { + t.Fatalf("metadata replacement with invalid JSON: err = %v, want ErrValidation", err) + } + assertIssueOperationsStoredMetadata(t, ctx, fixture, id, "after refused replacement", `{"keep":"old","drop":"old"}`) + events.assert(t, "refused metadata replacement", 0, nil) + + // A nonempty document replaces the whole value rather than merging into it. + replaced, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{ + Metadata: publicops.MetadataPatch{Replace: publicops.Field[json.RawMessage]{Set: true, Value: json.RawMessage(`{"fresh":"new"}`)}}, + }}) + if err != nil { + t.Fatalf("metadata replacement on %s: %v", id, err) + } + if !replaced.Changed { + t.Errorf("metadata replacement on %s reported Changed = false, want a committed edit", id) + } + assertIssueOperationsMetadata(t, "metadata replacement", replaced.Issue.Metadata, `{"fresh":"new"}`) + assertIssueOperationsStoredMetadata(t, ctx, fixture, id, "after replacement", `{"fresh":"new"}`) + + // A nil Value clears the document. + cleared, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{ + Metadata: publicops.MetadataPatch{Replace: publicops.Field[json.RawMessage]{Set: true, Value: nil}}, + }}) + if err != nil { + t.Fatalf("metadata clear on %s: %v", id, err) + } + if !cleared.Changed { + t.Errorf("metadata clear on %s reported Changed = false, want a committed edit", id) + } + // MetadataPatch.Replace now states the representation: clearing stores the + // empty JSON document and the column is never NULL. Both halves are pinned, + // because a backend that stored NULL would satisfy a JSON comparison of the + // scanned value (the helper reads a NULL back as "null") and only the IS + // NULL probe tells them apart — which is exactly the predicate a consumer + // filtering on cleared metadata writes. + assertIssueOperationsStoredMetadata(t, ctx, fixture, id, "after clear", `{}`) + assertIssueOperationsMetadataIsNotNull(t, ctx, fixture, id, "after clear") + + // An empty Value clears an already-clear document, which is a no-op. + recleared, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{ + Metadata: publicops.MetadataPatch{Replace: publicops.Field[json.RawMessage]{Set: true, Value: json.RawMessage{}}}, + }}) + if err != nil { + t.Fatalf("metadata re-clear on %s: %v", id, err) + } + if recleared.Changed { + t.Errorf("re-clearing %s's metadata reported Changed = true, want a no-op", id) + } + assertIssueOperationsStoredMetadata(t, ctx, fixture, id, "after re-clear", `{}`) +} + +// RunIssueOperationsRequestValuesAreNotMutated pins the leaf's promise that +// "implementations never mutate caller-owned request values" +// (issueops/issueops.go:377-384) and that results are detached snapshots +// (issueops.go:329-346). Everything a request carries by reference is at +// risk — the labels slice, the metadata bytes, the external-reference pointer, +// the issue struct itself — and the create body has a documented reason to want +// to write back into it: infra-type routing sets Ephemeral and ID minting fills +// in an ID, both on the attempt clone rather than on what the caller passed. +// +// The non-mutation half was pinned only on the unit-of-work backend and the +// detachment half only in one store's wisp test, so neither was stated once and +// answered by all three. +func RunIssueOperationsRequestValuesAreNotMutated(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture) { + t.Helper() + + targetID := fixture.IssuePrefix + "-detach-target" + seedClosePolicyIssue(t, ctx, fixture, targetID, publicops.CreateRequest{}) + + externalRef := "caller-ref" + callerLabels := []string{"caller-label"} + callerMetadata := json.RawMessage(`{"caller":"owned"}`) + callerIssue := &types.Issue{ + Title: "caller title", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, + Labels: callerLabels, Metadata: callerMetadata, ExternalRef: &externalRef, + } + callerDependencies := []publicops.CreateDependency{{TargetID: targetID, Type: types.DepBlocks}} + created, err := fixture.Operations.Create(ctx, publicops.CreateRequest{ + Actor: "writer", Issue: callerIssue, Dependencies: callerDependencies, + }) + if err != nil { + t.Fatalf("create from a caller-owned request: %v", err) + } + + // Nothing the caller handed over came back changed — including the ID field + // the create filled in on its own copy and the Dependencies field it built + // there. + if callerIssue.ID != "" { + t.Errorf("create wrote the minted ID %q back into the caller's issue", callerIssue.ID) + } + if callerIssue.Ephemeral { + t.Error("create wrote its routing decision back into the caller's issue") + } + if len(callerIssue.Dependencies) != 0 { + t.Errorf("create wrote %d dependency records back into the caller's issue", len(callerIssue.Dependencies)) + } + if !reflect.DeepEqual(callerLabels, []string{"caller-label"}) { + t.Errorf("create mutated the caller's labels slice: %v", callerLabels) + } + if string(callerMetadata) != `{"caller":"owned"}` { + t.Errorf("create mutated the caller's metadata bytes: %s", callerMetadata) + } + if externalRef != "caller-ref" { + t.Errorf("create mutated the caller's external reference: %q", externalRef) + } + if !reflect.DeepEqual(callerDependencies, []publicops.CreateDependency{{TargetID: targetID, Type: types.DepBlocks}}) { + t.Errorf("create mutated the caller's dependency slice: %#v", callerDependencies) + } + + // The result is a detached snapshot: corrupting it reaches neither the + // caller's own values nor the stored row. + createdID := created.Issue.ID + if len(created.Issue.Labels) != 1 { + t.Fatalf("create result labels = %v, want exactly the one requested label", created.Issue.Labels) + } + created.Issue.Labels[0] = "corrupted-label" + if callerLabels[0] != "caller-label" { + t.Errorf("the create result's labels alias the caller's slice: %v", callerLabels) + } + assertIssueOperationsLabels(t, ctx, fixture, createdID, "after corrupting the create result", "caller-label") + assertIssueOperationsStoredMetadata(t, ctx, fixture, createdID, "after corrupting the create result", `{"caller":"owned"}`) + + // The same for update: its patch carries caller-owned collections too. + patchAdd := []string{"added-label"} + patchRemove := []string{"caller-label"} + patchSet := map[string]json.RawMessage{"added": json.RawMessage(`"value"`)} + patchRef := "patched-ref" + updated, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{ + Actor: "writer", IssueID: createdID, + Patch: publicops.IssuePatch{ + ExternalRef: publicops.Field[*string]{Set: true, Value: &patchRef}, + Labels: publicops.LabelPatch{Add: patchAdd, Remove: patchRemove}, + Metadata: publicops.MetadataPatch{Set: patchSet}, + }, + }) + if err != nil { + t.Fatalf("update from a caller-owned request: %v", err) + } + if !reflect.DeepEqual(patchAdd, []string{"added-label"}) || !reflect.DeepEqual(patchRemove, []string{"caller-label"}) { + t.Errorf("update mutated the caller's label slices: add %v remove %v", patchAdd, patchRemove) + } + if !reflect.DeepEqual(patchSet, map[string]json.RawMessage{"added": json.RawMessage(`"value"`)}) { + t.Errorf("update mutated the caller's metadata map: %v", patchSet) + } + if patchRef != "patched-ref" { + t.Errorf("update mutated the caller's external reference: %q", patchRef) + } + + assertIssueOperationsStringSet(t, "update result labels", updated.Issue.Labels, "added-label") + updated.Issue.Labels[0] = "corrupted-label" + if patchAdd[0] != "added-label" { + t.Errorf("the update result's labels alias the caller's slice: %v", patchAdd) + } + assertIssueOperationsLabels(t, ctx, fixture, createdID, "after corrupting the update result", "added-label") + assertIssueOperationsStoredMetadata(t, ctx, fixture, createdID, "after corrupting the update result", `{"caller":"owned","added":"value"}`) +} + +// RunIssueOperationsUpdateProvenanceLabelsHistory pins +// UpdateRequest.Provenance against the history the backend actually writes +// (issueops/issueops.go:261-270): the entry reads as the caller's own string, +// and the label "NEVER changes WHETHER history is recorded" — an update that +// records one records one with the field empty, and one that records none +// records none with it set. +// +// Every existing assertion about this reads a stub's captured commit message. +// All three fixtures are Dolt-backed, so the real log is readable here, which is +// the only place the claim "the entry reads as the caller's string" can be +// settled. +func RunIssueOperationsUpdateProvenanceLabelsHistory(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture) { + t.Helper() + + id := fixture.IssuePrefix + "-provenance" + seedClosePolicyIssue(t, ctx, fixture, id, publicops.CreateRequest{}) + + const label = "conformance: provenance label" + history := newIssueOperationsHistoryCounter(t, ctx, fixture) + labeled, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{ + Actor: "writer", IssueID: id, Provenance: label, + Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "labeled title"}}, + }) + if err != nil { + t.Fatalf("labeled update of %s: %v", id, err) + } + if !labeled.Changed { + t.Fatalf("labeled update of %s reported Changed = false, want a durable mutation to label", id) + } + history.assertTotal(t, "labeled update", 1) + history.assertMessage(t, "labeled update", label, 1) + + // The label decides how the entry reads, never whether one exists: a no-op + // update carrying it records nothing. + const noopLabel = "conformance: provenance no-op" + noOp, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{ + Actor: "writer", IssueID: id, Provenance: noopLabel, + Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "labeled title"}}, + }) + if err != nil { + t.Fatalf("no-op labeled update of %s: %v", id, err) + } + if noOp.Changed { + t.Fatalf("restating %s's title reported Changed = true, want a no-op", id) + } + history.assertTotal(t, "no-op labeled update", 0) + history.assertMessage(t, "no-op labeled update", noopLabel, 0) + + // And an update with no label still records its one entry, under whatever + // default the implementation picked. + unlabeled, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{ + Actor: "writer", IssueID: id, + Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "unlabeled title"}}, + }) + if err != nil { + t.Fatalf("unlabeled update of %s: %v", id, err) + } + if !unlabeled.Changed { + t.Fatalf("unlabeled update of %s reported Changed = false, want a durable mutation", id) + } + history.assertTotal(t, "unlabeled update", 1) + history.assertMessage(t, "unlabeled update", label, 1) +} + +// RunIssueOperationsUpdatePersistentPreservesUnversionedClass pins the half of +// the Persistence clause nobody asserts: "Persistent preserves an existing +// durable unversioned class" (issueops/issueops.go:135-136). The refusal beside +// it — an unversioned row cannot be demoted to a wisp mode — is pinned; this +// clause says the legal direction is a no-op that does NOT normalize the row +// into versioned storage. +func RunIssueOperationsUpdatePersistentPreservesUnversionedClass(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture) { + t.Helper() + + id := fixture.IssuePrefix + "-unversioned" + if _, err := fixture.Operations.Create(ctx, publicops.CreateRequest{ + Actor: "seed", ForceIDPrefix: true, + Issue: &types.Issue{ + ID: id, Title: "unversioned", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, + StorageClass: types.StorageClassUnversioned, + }, + }); err != nil { + t.Fatalf("seed unversioned %s: %v", id, err) + } + assertIssueOperationsScalarValue(t, ctx, fixture, "seeded storage class", string(types.StorageClassUnversioned), + "SELECT COALESCE(storage_class, '') FROM issues WHERE id = ?", []any{id}) + + restated, err := fixture.Operations.Update(ctx, publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{ + Persistence: publicops.Field[publicops.PersistenceMode]{Set: true, Value: publicops.PersistenceModePersistent}, + }}) + if err != nil { + t.Fatalf("restate %s as persistent: %v", id, err) + } + if restated.Changed { + t.Errorf("restating unversioned %s as persistent reported Changed = true, want a no-op", id) + } + assertIssueOperationsScalarValue(t, ctx, fixture, "storage class after a persistent restatement", string(types.StorageClassUnversioned), + "SELECT COALESCE(storage_class, '') FROM issues WHERE id = ?", []any{id}) + assertIssueOperationsRowCount(t, ctx, fixture, "issues", id, 1) + assertIssueOperationsRowCount(t, ctx, fixture, "wisps", id, 0) +} + +// seedIssueOperationsLabeledIssue creates one open task at an explicit ID +// carrying labels, through the store seed hook rather than the guarded create, +// so the labels are already durable state when the case under test runs. +func seedIssueOperationsLabeledIssue(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture, id string, labels ...string) { + t.Helper() + issue := &types.Issue{ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Labels: labels} + if err := fixture.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatalf("seed labeled %s: %v", id, err) + } +} + +// assertIssueOperationsLabels reads the stored label set back one membership +// query at a time. GROUP_CONCAT ordering is not portable across the three +// fixtures' SQL engines, and the set is what the contract is about. +func assertIssueOperationsLabels(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture, id, label string, want ...string) { + t.Helper() + var total int + if err := fixture.QueryScalar(ctx, "SELECT COUNT(*) FROM labels WHERE issue_id = ?", []any{id}, &total); err != nil { + t.Fatalf("count labels for %s (%s): %v", id, label, err) + } + if total != len(want) { + t.Errorf("%s %s stored label count = %d, want %d (%v)", id, label, total, len(want), want) + } + for _, value := range want { + var present int + if err := fixture.QueryScalar(ctx, "SELECT COUNT(*) FROM labels WHERE issue_id = ? AND label = ?", []any{id, value}, &present); err != nil { + t.Fatalf("look up label %q on %s (%s): %v", value, id, label, err) + } + if present != 1 { + t.Errorf("%s %s stored label %q count = %d, want 1", id, label, value, present) + } + } +} + +// assertIssueOperationsParents reads the stored outgoing parent-child edges. +func assertIssueOperationsParents(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture, id, label string, want ...string) { + t.Helper() + var total int + if err := fixture.QueryScalar(ctx, "SELECT COUNT(*) FROM dependencies WHERE issue_id = ? AND type = ?", []any{id, string(types.DepParentChild)}, &total); err != nil { + t.Fatalf("count parents for %s (%s): %v", id, label, err) + } + if total != len(want) { + t.Errorf("%s %s parent edge count = %d, want %d (%v)", id, label, total, len(want), want) + } + for _, parent := range want { + var present int + if err := fixture.QueryScalar(ctx, + "SELECT COUNT(*) FROM dependencies WHERE issue_id = ? AND depends_on_issue_id = ? AND type = ?", + []any{id, parent, string(types.DepParentChild)}, &present); err != nil { + t.Fatalf("look up parent %s of %s (%s): %v", parent, id, label, err) + } + if present != 1 { + t.Errorf("%s %s parent edge to %s count = %d, want 1", id, label, parent, present) + } + } +} + +// assertIssueOperationsStringSet compares a result slice as a set, because no +// leaf clause promises an order for labels. +func assertIssueOperationsStringSet(t *testing.T, label string, got []string, want ...string) { + t.Helper() + gotSorted := append([]string(nil), got...) + wantSorted := append([]string(nil), want...) + sort.Strings(gotSorted) + sort.Strings(wantSorted) + if !reflect.DeepEqual(gotSorted, wantSorted) && (len(gotSorted) != 0 || len(wantSorted) != 0) { + t.Errorf("%s = %v, want %v", label, got, want) + } +} + +// assertIssueOperationsStoredMetadata reads the metadata column back and +// compares it as a document, since the three fixtures do not agree on +// whitespace or key order in the stored JSON. +func assertIssueOperationsStoredMetadata(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture, id, label, want string) { + t.Helper() + var stored string + if err := fixture.QueryScalar(ctx, "SELECT COALESCE(CAST(metadata AS CHAR), '') FROM issues WHERE id = ?", []any{id}, &stored); err != nil { + t.Fatalf("read metadata for %s (%s): %v", id, label, err) + } + if stored == "" { + stored = "null" + } + assertIssueOperationsMetadata(t, id+" "+label, json.RawMessage(stored), want) +} + +// assertIssueOperationsMetadataIsNotNull is the half assertIssueOperations- +// StoredMetadata cannot make: it reads a NULL column back as the JSON literal +// "null" and compares values, so a backend that stored NULL where the leaf +// promises an empty document would need this probe to be caught. It is the +// predicate a consumer filtering on cleared metadata actually writes. +func assertIssueOperationsMetadataIsNotNull(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture, id, label string) { + t.Helper() + var isNull bool + if err := fixture.QueryScalar(ctx, "SELECT metadata IS NULL FROM issues WHERE id = ?", []any{id}, &isNull); err != nil { + t.Fatalf("probe metadata nullability for %s (%s): %v", id, label, err) + } + if isNull { + t.Errorf("%s metadata (%s) is SQL NULL, want the empty JSON document: metadata is never NULL", id, label) + } +} + +// assertIssueOperationsScalarValue reads one scalar and compares it, reporting +// rather than fatalling so a case keeps collecting evidence. +func assertIssueOperationsScalarValue(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture, label, want, query string, args []any) { + t.Helper() + var got string + if err := fixture.QueryScalar(ctx, query, args, &got); err != nil { + t.Fatalf("%s: %v", label, err) + } + if got != want { + t.Errorf("%s = %q, want %q", label, got, want) + } +} + +// assertIssueOperationsAssigneeAndStatus reads back the two columns a claim +// writes, for the refusals that must leave both alone. +func assertIssueOperationsAssigneeAndStatus(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture, id, wantAssignee string, wantStatus types.Status) { + t.Helper() + var assignee, status string + if err := fixture.QueryScalar(ctx, "SELECT COALESCE(assignee, ''), status FROM issues WHERE id = ?", []any{id}, &assignee, &status); err != nil { + t.Fatalf("read assignee and status for %s: %v", id, err) + } + if assignee != wantAssignee { + t.Errorf("%s assignee = %q, want %q", id, assignee, wantAssignee) + } + if types.Status(status) != wantStatus { + t.Errorf("%s status = %q, want %q", id, status, wantStatus) + } +} + +// issueOperationsHistoryCounter reports how many version-control entries each +// operation adds. It takes deltas rather than reading the top of the log +// because two commits made inside one second tie on date, so their relative +// order is not something to assert on. +type issueOperationsHistoryCounter struct { + ctx context.Context + fixture IssueOperationsStagingFixture + total int +} + +func newIssueOperationsHistoryCounter(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture) *issueOperationsHistoryCounter { + t.Helper() + counter := &issueOperationsHistoryCounter{ctx: ctx, fixture: fixture} + counter.total = counter.count(t, "") + return counter +} + +func (c *issueOperationsHistoryCounter) count(t *testing.T, message string) int { + t.Helper() + query := "SELECT COUNT(*) FROM dolt_log" + var args []any + if message != "" { + query += " WHERE message = ?" + args = append(args, message) + } + var got int + if err := c.fixture.QueryScalar(c.ctx, query, args, &got); err != nil { + t.Fatalf("count history entries (%q): %v", message, err) + } + return got +} + +// assertTotal checks the entries added since the previous assertTotal and +// re-baselines. +func (c *issueOperationsHistoryCounter) assertTotal(t *testing.T, label string, want int) { + t.Helper() + total := c.count(t, "") + if got := total - c.total; got != want { + t.Errorf("%s recorded %d history entries, want %d", label, got, want) + } + c.total = total +} + +// assertMessage checks how many entries carry an exact message, which is the +// only way to tell the caller's spelling from the implementation's default. +func (c *issueOperationsHistoryCounter) assertMessage(t *testing.T, label, message string, want int) { + t.Helper() + if got := c.count(t, message); got != want { + t.Errorf("%s left %d history entries reading %q, want %d", label, got, message, want) + } +} diff --git a/backend/conformance/lifecycle_close_reopen_contract.go b/backend/conformance/lifecycle_close_reopen_contract.go new file mode 100644 index 000000000..6d7823c69 --- /dev/null +++ b/backend/conformance/lifecycle_close_reopen_contract.go @@ -0,0 +1,768 @@ +package conformance + +import ( + "context" + "errors" + "testing" + + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// This file holds the semantic contract for the two Lifecycle verbs that own +// the close/reopen transition — publicops.Lifecycle.Close and +// publicops.Lifecycle.Reopen — written against what issueops/issueops.go +// promises rather than against what any one implementation does. Create and +// Update live in issue_operations_contract.go; splitting the role across two +// files keeps two slices off one file, the way the staging contract already +// splits the persistence-level assertions out. +// +// Every case here runs on all three implementations. That matters more than +// usual for these two verbs: the server-backed and embedded stores share one +// validate/execute body (internal/storage/issueops/execution.go ExecuteClose +// and ExecuteReopen), so they are ONE vote on the semantics, while the +// unit-of-work backend reaches the same row bodies through domain/db and then +// derives Changed by comparing post-state instead of reading the row-write +// facts (internal/storage/uow/issue_operations.go:419, 458). Every Changed, +// OpenChildren, and refusal rule below is therefore a genuine two-implementation +// question, and the per-backend suites at dolt and embeddeddolt could never +// answer it. + +// LifecycleCloseReopenFixture supplies adapter-specific storage access for the +// Close and Reopen assertions. Every field is named and typed exactly like the +// per-backend roleFixtureKit hook it is filled from, so a wiring is kit plus +// accessor plus prefix with no adapter in between. +type LifecycleCloseReopenFixture struct { + // IssuePrefix namespaces the ids each assertion seeds, so several of them + // can share one database. + IssuePrefix string + // Lifecycle is the role under test, reached through the backend's + // capability accessor rather than a constructor. + Lifecycle publicops.Lifecycle + // CreateIssue seeds a durable issue in the issues plane, including its + // labels. + CreateIssue func(context.Context, *types.Issue, string) error + // AddDependency seeds ONE edge and records a dependency_added event, so + // every event assertion below is a DELTA around the verb under test. + AddDependency func(context.Context, *types.Dependency, string) error + // SetConfig installs the custom-status vocabulary the configured-done- + // category cases are read against. + SetConfig func(context.Context, string, string) error + QueryScalar func(context.Context, string, []any, ...any) error +} + +// lifecycleCloseReopenCustomStatuses is the vocabulary the category cases +// install. Both cases that need custom statuses write this SAME value, so the +// suite has no ordering coupling through a shared config key: whichever runs +// first, the other still finds both names installed. +const lifecycleCloseReopenCustomStatuses = "lcrtriage:active,lcrarchived:done" + +const ( + lifecycleCloseReopenActiveStatus = types.Status("lcrtriage") + lifecycleCloseReopenDoneStatus = types.Status("lcrarchived") +) + +// RunLifecycleCloseRefusalsCarryTheirTypesAndWriteNothing pins the two unforced +// Close refusals at the level a caller can act on: not merely "an error", but +// the typed identity the leaf names, carrying the count a CLI renders — and +// with the row and the event stream untouched. +// +// issueops/issueops.go:406-409 promises "An unforced close with open children +// returns CloseOpenChildrenError without mutation" and that "Force bypasses +// blocker and open-child policy"; errors.go:105-128 declares the sentinel pair +// and the struct's IssueID/OpenChildren fields and its Unwrap to +// ErrCloseOpenChildren. A sentinel-only assertion — which is all the two +// store-backed per-backend suites make, and all the unit-of-work suite made +// before this case — cannot tell a refusal that reports one open child from one +// that reports zero, and cannot tell a refusal that rolled back from one that +// stamped closed_at on the way out. +func RunLifecycleCloseRefusalsCarryTheirTypesAndWriteNothing(t *testing.T, ctx context.Context, fixture LifecycleCloseReopenFixture) { + t.Helper() + + parent := fixture.IssuePrefix + "-lcr-refuse-parent" + child := fixture.IssuePrefix + "-lcr-refuse-child" + blocker := fixture.IssuePrefix + "-lcr-refuse-blocker" + blocked := fixture.IssuePrefix + "-lcr-refuse-blocked" + for _, id := range []string{parent, child, blocker, blocked} { + lifecycleCloseReopenSeedIssue(t, ctx, fixture, id, types.StatusOpen, nil) + } + lifecycleCloseReopenSeedEdge(t, ctx, fixture, child, parent, types.DepParentChild) + lifecycleCloseReopenSeedEdge(t, ctx, fixture, blocked, blocker, types.DepBlocks) + + // The open-child refusal names the issue and counts the children, and + // unwraps to the sentinel a caller may match instead. + before := lifecycleCloseReopenReadRow(t, ctx, fixture, parent) + events := newLifecycleCloseReopenEventCounter(t, ctx, fixture, parent) + var openChildren *publicops.CloseOpenChildrenError + _, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: parent}) + if !errors.As(err, &openChildren) { + t.Fatalf("unforced close of %s with an open child: err = %v, want *CloseOpenChildrenError", parent, err) + } + if openChildren.IssueID != parent { + t.Errorf("refusal names issue %q, want %q", openChildren.IssueID, parent) + } + if openChildren.OpenChildren != 1 { + t.Errorf("refusal reports %d open children, want 1", openChildren.OpenChildren) + } + if !errors.Is(err, publicops.ErrCloseOpenChildren) { + t.Errorf("refusal %v does not match ErrCloseOpenChildren", err) + } + lifecycleCloseReopenAssertRow(t, ctx, fixture, parent, "after the open-child refusal", before) + events.assertNoneAdded(t, "open-child refusal") + + // The live-direct-blocker refusal is the other half, and it is a plain + // sentinel: errors.go:105-108 declares no struct for it. + before = lifecycleCloseReopenReadRow(t, ctx, fixture, blocked) + blockedEvents := newLifecycleCloseReopenEventCounter(t, ctx, fixture, blocked) + if _, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: blocked}); !errors.Is(err, publicops.ErrCloseBlocked) { + t.Fatalf("unforced close of %s with a live blocker: err = %v, want ErrCloseBlocked", blocked, err) + } + lifecycleCloseReopenAssertRow(t, ctx, fixture, blocked, "after the blocker refusal", before) + blockedEvents.assertNoneAdded(t, "blocker refusal") + + // Force bypasses both, which is what makes the two refusals above policy + // rather than some unrelated failure to close. + for _, id := range []string{parent, blocked} { + forced, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: id, Force: true}) + if err != nil { + t.Fatalf("forced close of %s: %v", id, err) + } + if !forced.Changed || forced.Issue.Status != types.StatusClosed { + t.Fatalf("forced close of %s = %#v, want a committed close", id, forced) + } + } +} + +// RunLifecycleCloseIsIdempotentAndKeepsTheFirstClose pins what a second Close +// of an already-closed issue does. issueops/issueops.go:354-359 promises +// Changed "is false for an idempotent re-close" and that OpenChildren "is +// reported even for an idempotent re-close"; :406-409 promises the unforced +// open-child refusal without qualifying it to open targets, and the shared +// store body reads the target's closed state precisely so a closed parent with +// open children still refuses (internal/storage/issueops/close.go:70-73). +// +// The attribution half — that the first close's reason, session, and closed_at +// survive a second one — is now stated outright by CloseRequest.Reason and +// CloseRequest.Session ("THE FIRST CLOSE WINS"), which also promise both +// values are read back on CloseResult.Issue. audit_issue-lifecycle.go:50-81 +// pins the same rule at the STORE seam; this is the role seam, and the only +// place the two backends that never run that audit answer for it. +func RunLifecycleCloseIsIdempotentAndKeepsTheFirstClose(t *testing.T, ctx context.Context, fixture LifecycleCloseReopenFixture) { + t.Helper() + + id := fixture.IssuePrefix + "-lcr-idem" + lifecycleCloseReopenSeedIssue(t, ctx, fixture, id, types.StatusOpen, nil) + + first, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{ + Actor: "writer", IssueID: id, Reason: "first pass", Session: "session-one", + }) + if err != nil { + t.Fatalf("close %s: %v", id, err) + } + if !first.Changed { + t.Fatalf("first close of %s reported Changed = false, want a committed close", id) + } + closedRow := lifecycleCloseReopenReadRow(t, ctx, fixture, id) + if closedRow.CloseReason != "first pass" || closedRow.ClosedBySession != "session-one" { + t.Fatalf("stored close attribution = (%q, %q), want (%q, %q)", + closedRow.CloseReason, closedRow.ClosedBySession, "first pass", "session-one") + } + if closedRow.ClosedAt == "" { + t.Fatalf("stored closed_at is empty after closing %s", id) + } + // The RESULT is the caller-visible half of the same clause: a caller that + // never queries the row still reads the attribution it just wrote. + if first.Issue.CloseReason != "first pass" || first.Issue.ClosedBySession != "session-one" { + t.Errorf("CloseResult.Issue attribution = (%q, %q), want (%q, %q)", + first.Issue.CloseReason, first.Issue.ClosedBySession, "first pass", "session-one") + } + if first.Issue.ClosedAt == nil { + t.Errorf("CloseResult.Issue.ClosedAt is nil after closing %s, want the stamp the close wrote", id) + } + + events := newLifecycleCloseReopenEventCounter(t, ctx, fixture, id) + again, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{ + Actor: "writer", IssueID: id, Reason: "second pass", Session: "session-two", + }) + if err != nil { + t.Fatalf("re-close %s: %v", id, err) + } + if again.Changed { + t.Errorf("re-close of %s reported Changed = true, want false for an idempotent close", id) + } + if again.Issue.Status != types.StatusClosed { + t.Errorf("re-close of %s reported status %q, want %q", id, again.Issue.Status, types.StatusClosed) + } + lifecycleCloseReopenAssertRow(t, ctx, fixture, id, "after the idempotent re-close", closedRow) + events.assertNoneAdded(t, "idempotent re-close") + + // A reopen clears the pair, the other half of the same clause: they + // describe a closure that no longer holds. + if _, err := fixture.Lifecycle.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: id}); err != nil { + t.Fatalf("reopen %s: %v", id, err) + } + reopenedRow := lifecycleCloseReopenReadRow(t, ctx, fixture, id) + if reopenedRow.CloseReason != "" || reopenedRow.ClosedBySession != "" { + t.Errorf("close attribution after reopening %s = (%q, %q), want both cleared", + id, reopenedRow.CloseReason, reopenedRow.ClosedBySession) + } + + // A forced close of a parent with an open child reports the count, and so + // does the forced re-close that changes nothing — while the UNFORCED + // re-close of that same closed parent still refuses, because the policy + // answers to the children, not to the target's own status. + parent := fixture.IssuePrefix + "-lcr-idem-parent" + child := fixture.IssuePrefix + "-lcr-idem-child" + lifecycleCloseReopenSeedIssue(t, ctx, fixture, parent, types.StatusOpen, nil) + lifecycleCloseReopenSeedIssue(t, ctx, fixture, child, types.StatusOpen, nil) + lifecycleCloseReopenSeedEdge(t, ctx, fixture, child, parent, types.DepParentChild) + + forced, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: parent, Force: true}) + if err != nil { + t.Fatalf("forced close of %s: %v", parent, err) + } + if !forced.Changed || forced.OpenChildren != 1 { + t.Fatalf("forced close of %s = (Changed %t, OpenChildren %d), want (true, 1)", parent, forced.Changed, forced.OpenChildren) + } + + var openChildren *publicops.CloseOpenChildrenError + if _, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: parent}); !errors.As(err, &openChildren) { + t.Fatalf("unforced re-close of closed %s with an open child: err = %v, want *CloseOpenChildrenError", parent, err) + } + + forcedAgain, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: parent, Force: true}) + if err != nil { + t.Fatalf("forced re-close of %s: %v", parent, err) + } + if forcedAgain.Changed { + t.Errorf("forced re-close of %s reported Changed = true, want false", parent) + } + if forcedAgain.OpenChildren != 1 { + t.Errorf("forced re-close of %s reported %d open children, want 1 — the count is promised even when nothing moved", parent, forcedAgain.OpenChildren) + } +} + +// RunLifecycleReopenLeavesNonDoneStatusesUnchanged pins the Reopen no-op. +// issueops/issueops.go:411-413 promises Reopen "moves literal StatusClosed and +// configured done statuses to StatusOpen; non-done statuses unchanged", and +// :368-370 promises Changed "is false when non-done statuses are unchanged". +// +// "Non-done" is wider than "already open", and that is the whole point of the +// case: a wip built-in and a configured ACTIVE custom status are both left +// alone, and neither is the AlreadyOpen shape the shared body computes +// (internal/storage/issueops/reopen.go:47-49). The store bodies' own unit test +// covers the custom-status branch against sqlmock +// (internal/storage/issueops/reopen_test.go:82-195); this is the real-fixture, +// three-backend version, and the only one the unit-of-work backend runs. +// +// The configured-active leg needs a control, because an UNCONFIGURED status is +// also left alone and would pass this case for the wrong reason. Two things +// supply it: the readback below proves SetConfig landed, and +// RunLifecycleCloseAndReopenSpanTheConfiguredDoneCategory — same suite, same +// installed vocabulary, same const — proves this fixture's resolver reads that +// vocabulary, since an unresolved lcrarchived would fail it. +func RunLifecycleReopenLeavesNonDoneStatusesUnchanged(t *testing.T, ctx context.Context, fixture LifecycleCloseReopenFixture) { + t.Helper() + + if err := fixture.SetConfig(ctx, "status.custom", lifecycleCloseReopenCustomStatuses); err != nil { + t.Fatalf("SetConfig(status.custom): %v", err) + } + var installed string + if err := fixture.QueryScalar(ctx, "SELECT value FROM config WHERE `key` = ?", []any{"status.custom"}, &installed); err != nil { + t.Fatalf("read back status.custom: %v", err) + } + if installed != lifecycleCloseReopenCustomStatuses { + t.Fatalf("installed status.custom = %q, want %q", installed, lifecycleCloseReopenCustomStatuses) + } + + cases := []struct { + name string + id string + status types.Status + }{ + {name: "already open", id: fixture.IssuePrefix + "-lcr-noop-open", status: types.StatusOpen}, + {name: "built-in wip", id: fixture.IssuePrefix + "-lcr-noop-wip", status: types.StatusInProgress}, + {name: "configured active", id: fixture.IssuePrefix + "-lcr-noop-custom", status: lifecycleCloseReopenActiveStatus}, + } + for _, tc := range cases { + lifecycleCloseReopenSeedIssue(t, ctx, fixture, tc.id, tc.status, nil) + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + before := lifecycleCloseReopenReadRow(t, ctx, fixture, tc.id) + if types.Status(before.Status) != tc.status { + t.Fatalf("seeded %s at status %q, want %q", tc.id, before.Status, tc.status) + } + events := newLifecycleCloseReopenEventCounter(t, ctx, fixture, tc.id) + // A Reason rides along: a status the verb leaves alone records + // nothing, Reason or not (issueops.go:310-313). + result, err := fixture.Lifecycle.Reopen(ctx, publicops.ReopenRequest{ + Actor: "writer", IssueID: tc.id, Reason: "ignored", + }) + if err != nil { + t.Fatalf("reopen %s at %q: %v", tc.id, tc.status, err) + } + if result.Changed { + t.Errorf("reopen of %s at %q reported Changed = true, want false", tc.id, tc.status) + } + if result.Issue.Status != tc.status { + t.Errorf("reopen of %s reported status %q, want it unchanged at %q", tc.id, result.Issue.Status, tc.status) + } + lifecycleCloseReopenAssertRow(t, ctx, fixture, tc.id, "after the reopen no-op", before) + events.assertNoneAdded(t, "reopen no-op") + }) + } +} + +// RunLifecycleCloseAndReopenSpanTheConfiguredDoneCategory pins that both verbs +// speak in terms of the configured done CATEGORY, not the literal closed +// status. issueops/issueops.go:403-405 promises Close "moves the issue to +// literal StatusClosed, including from a configured done status"; :370-372 +// promises Reopen moves "literal StatusClosed and configured done statuses" to +// StatusOpen. Both are a real move — a caller that treated a configured done +// status as already-final would report Changed = false and leave the row on a +// status no built-in query matches. +func RunLifecycleCloseAndReopenSpanTheConfiguredDoneCategory(t *testing.T, ctx context.Context, fixture LifecycleCloseReopenFixture) { + t.Helper() + + if err := fixture.SetConfig(ctx, "status.custom", lifecycleCloseReopenCustomStatuses); err != nil { + t.Fatalf("SetConfig(status.custom): %v", err) + } + + closing := fixture.IssuePrefix + "-lcr-done-close" + reopening := fixture.IssuePrefix + "-lcr-done-reopen" + lifecycleCloseReopenSeedIssue(t, ctx, fixture, closing, lifecycleCloseReopenDoneStatus, nil) + lifecycleCloseReopenSeedIssue(t, ctx, fixture, reopening, lifecycleCloseReopenDoneStatus, nil) + + closed, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: closing}) + if err != nil { + t.Fatalf("close %s from configured done status %q: %v", closing, lifecycleCloseReopenDoneStatus, err) + } + if !closed.Changed { + t.Errorf("close of %s from %q reported Changed = false, want a committed move to literal closed", closing, lifecycleCloseReopenDoneStatus) + } + if closed.Issue.Status != types.StatusClosed { + t.Errorf("close of %s reported status %q, want %q", closing, closed.Issue.Status, types.StatusClosed) + } + if row := lifecycleCloseReopenReadRow(t, ctx, fixture, closing); types.Status(row.Status) != types.StatusClosed { + t.Errorf("stored status for %s = %q, want %q", closing, row.Status, types.StatusClosed) + } + + reopened, err := fixture.Lifecycle.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: reopening}) + if err != nil { + t.Fatalf("reopen %s from configured done status %q: %v", reopening, lifecycleCloseReopenDoneStatus, err) + } + if !reopened.Changed { + t.Errorf("reopen of %s from %q reported Changed = false, want a committed move to open", reopening, lifecycleCloseReopenDoneStatus) + } + if reopened.Issue.Status != types.StatusOpen { + t.Errorf("reopen of %s reported status %q, want %q", reopening, reopened.Issue.Status, types.StatusOpen) + } + if row := lifecycleCloseReopenReadRow(t, ctx, fixture, reopening); types.Status(row.Status) != types.StatusOpen { + t.Errorf("stored status for %s = %q, want %q", reopening, row.Status, types.StatusOpen) + } +} + +// RunLifecycleExpectedVersionIsCheckedBeforeTheNoOps pins the ORDERING clause +// both requests spell out. CloseRequest.ExpectedVersion "requires the current +// row version to match and is checked before an idempotent close" +// (issueops/issueops.go:295-300); ReopenRequest.ExpectedVersion is "checked +// before a non-done no-op" (:272-275); and Close's own doc adds "ExpectedVersion +// is checked first, including for an idempotent close", with Force bypassing +// "blocker and open-child policy" and nothing else (:364-365). +// +// The dangerous shape is not a stale version on a live mutation — it is a stale +// version on the request that would have done nothing anyway. An implementation +// that filters the no-op first answers a lost-update precondition with success, +// and the caller's compare-and-set silently stops fencing. +func RunLifecycleExpectedVersionIsCheckedBeforeTheNoOps(t *testing.T, ctx context.Context, fixture LifecycleCloseReopenFixture) { + t.Helper() + + closedID := fixture.IssuePrefix + "-lcr-version-closed" + openID := fixture.IssuePrefix + "-lcr-version-open" + lifecycleCloseReopenSeedIssue(t, ctx, fixture, closedID, types.StatusOpen, nil) + lifecycleCloseReopenSeedIssue(t, ctx, fixture, openID, types.StatusOpen, nil) + + closed, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: closedID, Reason: "done"}) + if err != nil { + t.Fatalf("close %s: %v", closedID, err) + } + + // A stale version on a re-close that would have been a no-op. Force is the + // interesting leg: it waives close policy, never this. + stale := closed.Issue.RowVersion + 1 + before := lifecycleCloseReopenReadRow(t, ctx, fixture, closedID) + for _, force := range []bool{false, true} { + events := newLifecycleCloseReopenEventCounter(t, ctx, fixture, closedID) + _, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{ + Actor: "writer", IssueID: closedID, ExpectedVersion: &stale, Force: force, + }) + if !errors.Is(err, publicops.ErrVersionMismatch) { + t.Fatalf("re-close of closed %s with a stale version (force = %t): err = %v, want ErrVersionMismatch", closedID, force, err) + } + lifecycleCloseReopenAssertRow(t, ctx, fixture, closedID, "after the stale-version re-close", before) + events.assertNoneAdded(t, "stale-version re-close") + } + + // The current version still closes idempotently, which is what makes the + // two refusals above about the precondition rather than about re-closing. + current := before.RowLock + matched, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{ + Actor: "writer", IssueID: closedID, ExpectedVersion: ¤t, + }) + if err != nil { + t.Fatalf("re-close of %s with the current version: %v", closedID, err) + } + if matched.Changed { + t.Errorf("re-close of %s with the current version reported Changed = true, want false", closedID) + } + + // The same ordering on the other verb: a stale version on a reopen that + // would have been a non-done no-op. + openRow := lifecycleCloseReopenReadRow(t, ctx, fixture, openID) + staleOpen := openRow.RowLock + 1 + events := newLifecycleCloseReopenEventCounter(t, ctx, fixture, openID) + if _, err := fixture.Lifecycle.Reopen(ctx, publicops.ReopenRequest{ + Actor: "writer", IssueID: openID, ExpectedVersion: &staleOpen, + }); !errors.Is(err, publicops.ErrVersionMismatch) { + t.Fatalf("reopen of open %s with a stale version: err = %v, want ErrVersionMismatch", openID, err) + } + lifecycleCloseReopenAssertRow(t, ctx, fixture, openID, "after the stale-version reopen", openRow) + events.assertNoneAdded(t, "stale-version reopen") + + currentOpen := openRow.RowLock + noOp, err := fixture.Lifecycle.Reopen(ctx, publicops.ReopenRequest{ + Actor: "writer", IssueID: openID, ExpectedVersion: ¤tOpen, + }) + if err != nil { + t.Fatalf("reopen of %s with the current version: %v", openID, err) + } + if noOp.Changed { + t.Errorf("reopen of open %s with the current version reported Changed = true, want false", openID) + } +} + +// RunLifecycleReopenRecordsItsReason pins ReopenRequest.Reason: it "records +// why literal closed and configured done statuses move to open", and the leaf +// now says WHERE — the issue's event history, on the reopened entry the move +// itself records, and nowhere on the issue or the result. +// +// The no-reason leg is what makes the location a promise rather than a +// coincidence. It proves the reopened entry exists independently of the +// reason, so the first leg is reading a reason carried BY that entry rather +// than an entry minted because a reason was supplied. +func RunLifecycleReopenRecordsItsReason(t *testing.T, ctx context.Context, fixture LifecycleCloseReopenFixture) { + t.Helper() + + id := fixture.IssuePrefix + "-lcr-reason" + lifecycleCloseReopenSeedIssue(t, ctx, fixture, id, types.StatusOpen, nil) + if _, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: id, Reason: "shipped"}); err != nil { + t.Fatalf("close %s: %v", id, err) + } + + reopened, err := fixture.Lifecycle.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: id, Reason: "regressed"}) + if err != nil { + t.Fatalf("reopen %s: %v", id, err) + } + if !reopened.Changed { + t.Fatalf("reopen of closed %s reported Changed = false, want a committed reopen", id) + } + + var recorded int + if err := fixture.QueryScalar(ctx, + "SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ? AND COALESCE(new_value, '') = ?", + []any{id, string(types.EventReopened), "regressed"}, &recorded); err != nil { + t.Fatalf("count recorded reopen reasons for %s: %v", id, err) + } + if recorded != 1 { + t.Errorf("reopen of %s recorded %d reopened events carrying the reason, want 1", id, recorded) + } + + quiet := fixture.IssuePrefix + "-lcr-reason-none" + lifecycleCloseReopenSeedIssue(t, ctx, fixture, quiet, types.StatusOpen, nil) + if _, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: quiet}); err != nil { + t.Fatalf("close %s: %v", quiet, err) + } + if _, err := fixture.Lifecycle.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: quiet}); err != nil { + t.Fatalf("reopen %s with no reason: %v", quiet, err) + } + var entries, carrying int + if err := fixture.QueryScalar(ctx, + "SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ?", + []any{quiet, string(types.EventReopened)}, &entries); err != nil { + t.Fatalf("count reopened events for %s: %v", quiet, err) + } + if entries != 1 { + t.Errorf("reopen of %s with no reason recorded %d reopened events, want 1: the entry is the move's, not the reason's", quiet, entries) + } + if err := fixture.QueryScalar(ctx, + "SELECT COUNT(*) FROM events WHERE issue_id = ? AND event_type = ? AND COALESCE(new_value, '') <> ''", + []any{quiet, string(types.EventReopened)}, &carrying); err != nil { + t.Fatalf("count reopened events carrying a reason for %s: %v", quiet, err) + } + if carrying != 0 { + t.Errorf("reopen of %s with no reason recorded %d reopened events carrying one, want 0", quiet, carrying) + } +} + +// RunLifecycleResultsAreHydratedPostStateSnapshots pins the shape both results +// promise: CloseResult.Issue and ReopenResult.Issue are "a detached post-state +// snapshot with labels and dependency records" (issueops/issueops.go:348-353, +// 362-367). A result that returned the bare row would leave a caller rendering +// an issue with no labels and no edges, and the two per-backend detachment +// tests only prove the snapshot does not ALIAS store state — not that it +// carries anything. +// +// Comments are the other half of that clause ("Comments are omitted") and are +// not asserted here: the frozen role fixture kit exposes no comment-seeding +// hook, so the assertion would pass on an empty comment table for the wrong +// reason. It belongs with a kit that can seed one. +func RunLifecycleResultsAreHydratedPostStateSnapshots(t *testing.T, ctx context.Context, fixture LifecycleCloseReopenFixture) { + t.Helper() + + subject := fixture.IssuePrefix + "-lcr-snapshot" + peer := fixture.IssuePrefix + "-lcr-snapshot-peer" + lifecycleCloseReopenSeedIssue(t, ctx, fixture, subject, types.StatusOpen, []string{"lcr-tag"}) + lifecycleCloseReopenSeedIssue(t, ctx, fixture, peer, types.StatusOpen, nil) + // relates-to, not blocks: the edge has to be visible in the result without + // making the subject unclosable. + lifecycleCloseReopenSeedEdge(t, ctx, fixture, subject, peer, types.DepRelatesTo) + + closed, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: subject}) + if err != nil { + t.Fatalf("close %s: %v", subject, err) + } + lifecycleCloseReopenAssertSnapshot(t, "close result", closed.Issue, peer) + + reopened, err := fixture.Lifecycle.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: subject}) + if err != nil { + t.Fatalf("reopen %s: %v", subject, err) + } + lifecycleCloseReopenAssertSnapshot(t, "reopen result", reopened.Issue, peer) +} + +// RunLifecycleCloseAndReopenRequireActorAndIssueID pins the deterministic +// validation floor both verbs sit on. The Lifecycle doc states "Deterministic +// request validation failures match ErrValidation" and "Refusals and +// deterministic validation failures leave persistent state unchanged" +// (issueops/issueops.go:375-376, 385-386); the shared store body spells the +// same two fields at internal/storage/issueops/execution.go:255-258, 281-284. +// +// The empty-Actor legs are the ones with teeth: the id names a real row, so an +// implementation that skipped the guard would close or reopen it. +func RunLifecycleCloseAndReopenRequireActorAndIssueID(t *testing.T, ctx context.Context, fixture LifecycleCloseReopenFixture) { + t.Helper() + + id := fixture.IssuePrefix + "-lcr-validation" + lifecycleCloseReopenSeedIssue(t, ctx, fixture, id, types.StatusOpen, nil) + before := lifecycleCloseReopenReadRow(t, ctx, fixture, id) + + closeCases := map[string]publicops.CloseRequest{ + "close without an actor": {IssueID: id}, + "close without an issue": {Actor: "writer"}, + "close without either": {}, + "close with a blank actor": {Actor: "", IssueID: id, Reason: "ignored", Force: true}, + } + for name, request := range closeCases { + t.Run(name, func(t *testing.T) { + if _, err := fixture.Lifecycle.Close(ctx, request); !errors.Is(err, publicops.ErrValidation) { + t.Fatalf("%s: err = %v, want ErrValidation", name, err) + } + lifecycleCloseReopenAssertRow(t, ctx, fixture, id, "after "+name, before) + }) + } + + reopenCases := map[string]publicops.ReopenRequest{ + "reopen without an actor": {IssueID: id}, + "reopen without an issue": {Actor: "writer"}, + "reopen without either": {}, + } + for name, request := range reopenCases { + t.Run(name, func(t *testing.T) { + if _, err := fixture.Lifecycle.Reopen(ctx, request); !errors.Is(err, publicops.ErrValidation) { + t.Fatalf("%s: err = %v, want ErrValidation", name, err) + } + lifecycleCloseReopenAssertRow(t, ctx, fixture, id, "after "+name, before) + }) + } +} + +// RunLifecycleReopenProvenanceLabelsHistory pins both halves of +// ReopenRequest.Provenance (issueops/issueops.go:317-326): a spelled label is +// what the recorded entry reads, and the field "NEVER changes WHETHER history +// is recorded — only how the entry reads". +// +// The second half is the one worth a case. A caller reaching for Provenance is +// reaching for an entry it can find later, and an implementation that treated a +// label as a reason to record one would turn every no-op reopen into a commit +// naming work that did not happen. +// +// What this deliberately does NOT assert is the DEFAULT spelling. The clause +// says outright that the implementations disagree on it — the store-backed ones +// write "bd: reopen issue" and the unit-of-work one "reopen issue" — so pinning +// either would be asserting a promise the doc declines to make. +func RunLifecycleReopenProvenanceLabelsHistory(t *testing.T, ctx context.Context, fixture LifecycleCloseReopenFixture) { + t.Helper() + + const label = "conformance: reopen provenance label" + + id := fixture.IssuePrefix + "-lcr-prov" + lifecycleCloseReopenSeedIssue(t, ctx, fixture, id, types.StatusOpen, nil) + if _, err := fixture.Lifecycle.Close(ctx, publicops.CloseRequest{Actor: "writer", IssueID: id, Reason: "shipped"}); err != nil { + t.Fatalf("close %s: %v", id, err) + } + + before := lifecycleCloseReopenCountHistory(t, ctx, fixture, label) + + reopened, err := fixture.Lifecycle.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: id, Reason: "regressed", Provenance: label}) + if err != nil { + t.Fatalf("reopen %s: %v", id, err) + } + if !reopened.Changed { + t.Fatalf("reopen of closed %s reported Changed = false, want a committed reopen", id) + } + if got := lifecycleCloseReopenCountHistory(t, ctx, fixture, label); got != before+1 { + t.Errorf("reopen of %s left %d history entries reading %q, want %d", id, got, label, before+1) + } + + // The issue is open now, so this reopen is a no-op. A label must not be + // enough on its own to make an entry appear. + noop, err := fixture.Lifecycle.Reopen(ctx, publicops.ReopenRequest{Actor: "writer", IssueID: id, Reason: "again", Provenance: label}) + if err != nil { + t.Fatalf("no-op reopen %s: %v", id, err) + } + if noop.Changed { + t.Fatalf("reopen of already-open %s reported Changed = true, want a no-op", id) + } + if got := lifecycleCloseReopenCountHistory(t, ctx, fixture, label); got != before+1 { + t.Errorf("no-op reopen of %s left %d history entries reading %q, want the %d the committed reopen wrote", id, got, label, before+1) + } +} + +// lifecycleCloseReopenCountHistory counts version-control entries carrying an +// EXACT message, which is the only way to tell the caller's spelling from the +// implementation's default. It is read as a delta by every caller: these +// fixtures share a database with their sibling cases, so an absolute count +// would carry their commits too. +func lifecycleCloseReopenCountHistory(t *testing.T, ctx context.Context, fixture LifecycleCloseReopenFixture, message string) int { + t.Helper() + var count int + if err := fixture.QueryScalar(ctx, "SELECT COUNT(*) FROM dolt_log WHERE message = ?", []any{message}, &count); err != nil { + t.Fatalf("count history entries reading %q: %v", message, err) + } + return count +} + +// lifecycleCloseReopenRow is the stored close-lifecycle state one assertion +// compares before and after. row_lock is read as an int64 rather than a string +// because the version cases hand it straight back as an ExpectedVersion. +type lifecycleCloseReopenRow struct { + Status string + RowLock int64 + ClosedAt string + CloseReason string + ClosedBySession string +} + +func lifecycleCloseReopenReadRow(t *testing.T, ctx context.Context, fixture LifecycleCloseReopenFixture, id string) lifecycleCloseReopenRow { + t.Helper() + var row lifecycleCloseReopenRow + if err := fixture.QueryScalar(ctx, + "SELECT status, row_lock, COALESCE(CAST(closed_at AS CHAR), ''), COALESCE(close_reason, ''), COALESCE(closed_by_session, '') FROM issues WHERE id = ?", + []any{id}, &row.Status, &row.RowLock, &row.ClosedAt, &row.CloseReason, &row.ClosedBySession); err != nil { + t.Fatalf("read close-lifecycle row for %s: %v", id, err) + } + return row +} + +// lifecycleCloseReopenAssertRow checks that the whole close-lifecycle row is +// where a previous read left it. Refusals and no-ops assert against it, so it +// covers row_lock too: a rewritten version is a lifecycle write that happened, +// even when status came out the same. +func lifecycleCloseReopenAssertRow(t *testing.T, ctx context.Context, fixture LifecycleCloseReopenFixture, id, label string, want lifecycleCloseReopenRow) { + t.Helper() + if got := lifecycleCloseReopenReadRow(t, ctx, fixture, id); got != want { + t.Errorf("%s %s row = %+v, want it unchanged at %+v", id, label, got, want) + } +} + +// lifecycleCloseReopenAssertSnapshot checks a result issue carries the hydrated +// state the result doc promises. +func lifecycleCloseReopenAssertSnapshot(t *testing.T, label string, issue *types.Issue, wantEdgeTarget string) { + t.Helper() + if issue == nil { + t.Fatalf("%s issue = nil, want a post-state snapshot", label) + } + found := false + for _, name := range issue.Labels { + if name == "lcr-tag" { + found = true + } + } + if !found { + t.Errorf("%s labels = %v, want the seeded label", label, issue.Labels) + } + for _, dependency := range issue.Dependencies { + if dependency != nil && dependency.DependsOnID == wantEdgeTarget { + return + } + } + t.Errorf("%s dependencies = %v, want a record naming %s", label, issue.Dependencies, wantEdgeTarget) +} + +func lifecycleCloseReopenSeedIssue(t *testing.T, ctx context.Context, fixture LifecycleCloseReopenFixture, id string, status types.Status, labels []string) { + t.Helper() + if err := fixture.CreateIssue(ctx, &types.Issue{ + ID: id, Title: id, Status: status, Priority: 2, IssueType: types.TypeTask, Labels: labels, + }, "seed"); err != nil { + t.Fatalf("seed %s at status %q: %v", id, status, err) + } +} + +func lifecycleCloseReopenSeedEdge(t *testing.T, ctx context.Context, fixture LifecycleCloseReopenFixture, from, to string, kind types.DependencyType) { + t.Helper() + if err := fixture.AddDependency(ctx, &types.Dependency{ + IssueID: from, DependsOnID: to, Type: kind, + }, "seed"); err != nil { + t.Fatalf("seed %s %s -> %s: %v", kind, from, to, err) + } +} + +// lifecycleCloseReopenEventCounter reports how many event rows one issue gained +// across the operation under test. It is a DELTA, not an absolute: the fixture's +// AddDependency seed records a dependency_added event of its own. +type lifecycleCloseReopenEventCounter struct { + ctx context.Context + fixture LifecycleCloseReopenFixture + id string + total int +} + +func newLifecycleCloseReopenEventCounter(t *testing.T, ctx context.Context, fixture LifecycleCloseReopenFixture, id string) *lifecycleCloseReopenEventCounter { + t.Helper() + counter := &lifecycleCloseReopenEventCounter{ctx: ctx, fixture: fixture, id: id} + counter.total = counter.count(t) + return counter +} + +func (c *lifecycleCloseReopenEventCounter) count(t *testing.T) int { + t.Helper() + var got int + if err := c.fixture.QueryScalar(c.ctx, "SELECT COUNT(*) FROM events WHERE issue_id = ?", []any{c.id}, &got); err != nil { + t.Fatalf("count events for %s: %v", c.id, err) + } + return got +} + +// assertNoneAdded checks that nothing landed since the previous baseline, and +// re-baselines. Zero is the only count this file ever asserts: every operation +// it counts around is a refusal or a no-op, and the promise in both cases is +// that the event stream did not move. +func (c *lifecycleCloseReopenEventCounter) assertNoneAdded(t *testing.T, label string) { + t.Helper() + total := c.count(t) + if got := total - c.total; got != 0 { + t.Errorf("%s wrote %d event rows for %s, want none", label, got, c.id) + } + c.total = total +} diff --git a/backend/conformance/reader_contract.go b/backend/conformance/reader_contract.go new file mode 100644 index 000000000..0fce2685e --- /dev/null +++ b/backend/conformance/reader_contract.go @@ -0,0 +1,1472 @@ +package conformance + +import ( + "context" + "errors" + "reflect" + "slices" + "strings" + "testing" + "time" + + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// This file holds the semantic contract every implementation of +// publicops.Reader must satisfy. There are three wirings — the direct store, +// the embedded store, and the unit-of-work backend — but only TWO bodies: the +// two store accessors both return workapi/storereader.New(store), so the +// store-backed body gets two votes that are one vote. The genuinely separate +// implementation is internal/storage/uow/issue_reader.go. The embedded wiring +// still earns its place: it runs the same body against a different engine, and +// engine-level disagreement (SQL dialect, staging, connection wrapper) is the +// class it has caught before. +// +// WHAT THIS CONTRACT PINS: the QUERY-SEAM RESIDUE. Whether each backend's query +// seam honors the request the shared builder produced, end to end against a +// real database, and whether the implementations agree on the resulting page +// shape and boundary behavior. The existing fake-based comparison test +// (internal/storage/uow/issue_reader_test.go) drives both bodies through stub +// seams and therefore cannot see any of that; it stays where it is, as the unit +// pin for the epilogue, and this contract does not restate it. +// +// WHAT THIS CONTRACT DELIBERATELY DOES NOT PIN, and why each one is already +// owned somewhere else — re-pinning them here is the duplicate-scenario +// anti-pattern engdocs/TESTING.md names: +// +// - PER-FIELD REQUEST-TO-FILTER MAPPING. Both requests are turned into +// storage filters by ONE builder pair, workapi.BuildReadyFilter and +// workapi.BuildListFilter, which every implementation calls and which +// internal/workapi's golden files pin field by field +// (ready_golden_test.go, list_golden_test.go, +// testdata/list_filter_golden.json). A case here that asserted "Assignee +// reaches the query" would be asserting the golden's job through a Dolt +// server. The residue this file DOES pin is the part the goldens cannot +// see: what the SEAM does with the filter once it has it — the type +// exclusions the ready WHERE clause applies when Type is empty, the +// fetch-all-then-trim for a sort SQL cannot express, the keyset predicate, +// the has-more verdict at the page boundary. +// +// - THE PAGE EPILOGUE ITSELF. Sort, trim and the truncation verdict are +// workapi.FinishPage, one function with four callers, unit-tested in +// workapi/page_test.go. The boundary cases below assert the ANSWER a +// request gets, which is where the two seams feed FinishPage differently +// (the store body over-fetches one row; the uow body reports has-more +// natively) — not the epilogue's internals. +// +// - THE GET RESOLVE. workapi.GetIssueOrWisp is shared with Commenter and +// Relations and has its own tests. What is pinned here is that a Reader +// request reaches it and that its verdicts survive the trip: exact id only, +// the wisp fallback, ErrNotFound, and no decay of a backend failure into +// not-found. +// +// - LABEL PATTERN / REGEX / METADATA-KEY MATCHING SEMANTICS. Those are +// storage-surface behaviors pinned by the audit leaves; the role adds no +// promise on top of them. +// +// - THE CONFIGURED INFRA-TYPE VOCABULARY. Which types a workspace calls +// infra is read through a per-store cache +// (dolt/config.go:194-214) whose invalidation is a storage concern, not a +// role promise. The infra assertion below therefore uses the plane the +// default listing suppresses, not a reconfigured vocabulary. +// +// - THE NEVER-MUTATE-CALLER-REQUEST RULE, beyond the single tripwire +// RunReaderDoesNotMutateTheCallerRequest. reader.go:326 makes it a promise, +// so it gets one case for the whole role; it is a property of the shared +// implementation, not of each method, and asserting it per method would +// triple the cost for no new information. +// +// THE DOC COMMENT IS THE SPEC. Every case below asserts what +// issueops/reader.go promises, not what any implementation currently does. A +// backend that disagrees is parked at its own wiring site with +// skipKnownDivergence and a bead, never by weakening the case. + +// ReaderFixture supplies adapter-specific storage access for the reader +// assertions. It carries only the hooks these cases use: the role is read-only, +// so every assertion is on the returned page or detail view and none of them +// needs a scalar query. +// +// AddComment is the one hook the shared per-backend role kit does not expose +// (bd-kue5t's kit has CreateIssue/CreateWisp/AddDependency/SetConfig/ +// QueryScalar/CountHistory). The Get detail view carries a comment count and an +// opt-in comment list, so this contract cannot assert either half without a way +// to put a comment on an issue. Each wiring supplies it locally; see the S0 +// follow-up noted in this slice's report. +type ReaderFixture struct { + // IssuePrefix namespaces the ids each assertion seeds, so all of them can + // share one database. Every case below scopes its query to its own seeded + // rows — by id set, by label, or by exact id — because a list request with + // no scope answers with the whole workspace, and on the unit-of-work + // backend that workspace is shared by every case in the suite. + IssuePrefix string + Reader publicops.Reader + // CreateIssue seeds a durable issue in the issues plane. + CreateIssue func(context.Context, *types.Issue, string) error + // CreateWisp seeds an ephemeral issue in the wisps plane. + CreateWisp func(context.Context, *types.Issue, string) error + // AddDependency seeds one edge and recomputes the source's blocked state, + // which is what makes the ready and --ready queries answer differently. + AddDependency func(context.Context, *types.Dependency, string) error + // AddComment puts one comment on a durable issue. + AddComment func(ctx context.Context, issueID, author, text string) error +} + +// RunReaderReadyDefaultTypeExclusionsYieldToAnExplicitType pins +// ReadyRequest.IssueType's three-part promise (reader.go:30-34): the default +// type exclusions hide a gate; naming the type drops those exclusions AND the +// caller's own ExcludeTypes along with them; and a type nobody has heard of +// matches nothing rather than failing. +// +// The last third is the asymmetry with ListRequest.IssueType, which validates +// against the workspace vocabulary and errors — see +// RunReaderListRejectsATypeOutsideTheWorkspaceVocabulary, whose comment names +// the other side of it. +func RunReaderReadyDefaultTypeExclusionsYieldToAnExplicitType(t *testing.T, ctx context.Context, fixture ReaderFixture) { + t.Helper() + scope := readerLabel(fixture, "rdytype") + task := readerID(fixture, "rdytype", "task") + gate := readerID(fixture, "rdytype", "gate") + seedReaderIssue(t, ctx, fixture, readerIssue(task, types.TypeTask, scope)) + seedReaderIssue(t, ctx, fixture, readerIssue(gate, types.TypeGate, scope)) + + page, err := fixture.Reader.Ready(ctx, publicops.ReadyRequest{Labels: []string{scope}}) + if err != nil { + t.Fatalf("Ready with no type: %v", err) + } + assertReaderPageIDSet(t, "Ready with no type", page, []string{task}) + + // Naming the type drops the default exclusions. ExcludeTypes goes with + // them: the field's doc says it is ignored when IssueType is set, so + // asking for gates while excluding gates still answers with the gate. + page, err = fixture.Reader.Ready(ctx, publicops.ReadyRequest{ + Labels: []string{scope}, + IssueType: string(types.TypeGate), + ExcludeTypes: []string{string(types.TypeGate)}, + }) + if err != nil { + t.Fatalf("Ready with IssueType=gate: %v", err) + } + assertReaderPageIDSet(t, "Ready with IssueType=gate and ExcludeTypes=[gate]", page, []string{gate}) + + page, err = fixture.Reader.Ready(ctx, publicops.ReadyRequest{ + Labels: []string{scope}, + IssueType: "no-such-type-anywhere", + }) + if err != nil { + t.Fatalf("Ready with an unrecognized type must match nothing rather than fail: %v", err) + } + assertReaderPageIDSet(t, "Ready with an unrecognized type", page, nil) +} + +// RunReaderReadyDeferredAndEphemeralGates pins the two admission flags +// (reader.go:62-65). Both default to off and each admits exactly its own class: +// IncludeDeferred does not let the wisp in and IncludeEphemeral does not let the +// deferred row in. +func RunReaderReadyDeferredAndEphemeralGates(t *testing.T, ctx context.Context, fixture ReaderFixture) { + t.Helper() + scope := readerLabel(fixture, "rdygate") + plain := readerID(fixture, "rdygate", "plain") + deferred := readerID(fixture, "rdygate", "deferred") + wisp := readerID(fixture, "rdygate", "wisp") + + later := time.Now().UTC().Add(24 * time.Hour) + deferredIssue := readerIssue(deferred, types.TypeTask, scope) + deferredIssue.DeferUntil = &later + wispIssue := readerIssue(wisp, types.TypeTask, scope) + wispIssue.Ephemeral = true + + seedReaderIssue(t, ctx, fixture, readerIssue(plain, types.TypeTask, scope)) + seedReaderIssue(t, ctx, fixture, deferredIssue) + seedReaderWisp(t, ctx, fixture, wispIssue) + + for _, test := range []struct { + name string + req publicops.ReadyRequest + want []string + }{ + {"neither gate open", publicops.ReadyRequest{Labels: []string{scope}}, []string{plain}}, + {"IncludeDeferred", publicops.ReadyRequest{Labels: []string{scope}, IncludeDeferred: true}, []string{plain, deferred}}, + {"IncludeEphemeral", publicops.ReadyRequest{Labels: []string{scope}, IncludeEphemeral: true}, []string{plain, wisp}}, + } { + page, err := fixture.Reader.Ready(ctx, test.req) + if err != nil { + t.Fatalf("Ready (%s): %v", test.name, err) + } + assertReaderPageIDSet(t, "Ready ("+test.name+")", page, test.want) + } +} + +// RunReaderReadyLimitBoundary walks the whole Limit vocabulary +// (reader.go:85-100) against the page shape it produces (reader.go:310-315). +// +// This is the one case that exercises a genuine two-implementation seam rather +// than one body twice. The store-backed body has no has-more of its own, so it +// asks the query for one row past the page and lets the extra row's presence be +// the answer (workapi/storereader/reader.go:62-67). The unit-of-work body's +// seam reports has-more natively and feeds that verdict into the same epilogue +// (uow/issue_reader.go:58-68). The two must agree exactly AT the boundary, which +// is where an off-by-one in either mechanism shows: three rows, asked for two, +// three, all, and by default. +// +// Offset is the neighboring knob and is deliberately NOT asserted here: the +// two bodies answer it differently on purpose, so what the contract can pin is +// weaker than a row count. RunReaderOffsetIsHonoredOrRefused owns it. +func RunReaderReadyLimitBoundary(t *testing.T, ctx context.Context, fixture ReaderFixture) { + t.Helper() + scope := readerLabel(fixture, "rdylimit") + var ids []string + for _, tag := range []string{"a", "b", "c"} { + id := readerID(fixture, "rdylimit", tag) + ids = append(ids, id) + seedReaderIssue(t, ctx, fixture, readerIssue(id, types.TypeTask, scope)) + } + + for _, test := range []struct { + name string + limit *int + wantN int + hasMore bool + }{ + {"unset takes the shared default, which does not truncate three rows", nil, 3, false}, + {"explicit 0 is unlimited", readerLimit(0), 3, false}, + {"a limit under the result count truncates and says so", readerLimit(2), 2, true}, + {"a limit exactly at the result count hides nothing", readerLimit(3), 3, false}, + } { + page, err := fixture.Reader.Ready(ctx, publicops.ReadyRequest{Labels: []string{scope}, Limit: test.limit}) + if err != nil { + t.Fatalf("Ready (%s): %v", test.name, err) + } + assertReaderPageNotNil(t, "Ready ("+test.name+")", page) + if len(page.Items) != test.wantN { + t.Errorf("Ready (%s) returned %d items %v, want %d", test.name, len(page.Items), readerPageIDs(page), test.wantN) + } + if page.HasMore != test.hasMore { + t.Errorf("Ready (%s) HasMore = %v, want %v", test.name, page.HasMore, test.hasMore) + } + for _, got := range readerPageIDs(page) { + if !slices.Contains(ids, got) { + t.Errorf("Ready (%s) returned %s, which this case did not seed", test.name, got) + } + } + } +} + +// RunReaderOffsetIsHonoredOrRefused pins the one thing every implementation +// owes on ReadyRequest.Offset and ListRequest.Offset: a non-zero Offset is +// either HONORED or REFUSED with a typed *ErrUnsupported, and never SILENTLY +// IGNORED. +// +// It is deliberately weaker than "Offset skips N rows", and the weakness is the +// point. The two bodies disagree by design — the unit-of-work one renders +// LIMIT/OFFSET, the store-backed one renders LIMIT only and therefore refuses +// rather than answering the first page again — so a case written to either +// behavior would fail the other. What they do share is the property whose +// ABSENCE made this a spec gap (bd-yby99.7): with three matching rows, Offset +// 0/1/2 came back 3/3/3 through the store body, with no error for a pager to +// notice. Which body does which is a per-backend fact and is asserted at the +// wirings, not here. +// +// The assertion is therefore comparative. The same request is issued at Offset +// 0 and at Offset 1, and the second must either refuse with an error a caller +// can classify, or answer with a genuinely different page. Both requests name a +// total order over rows seeded minutes apart, so "different" cannot be storage +// order wobbling between two calls. +func RunReaderOffsetIsHonoredOrRefused(t *testing.T, ctx context.Context, fixture ReaderFixture) { + t.Helper() + scope := readerLabel(fixture, "offset") + var ids []string + base := time.Now().UTC().Truncate(time.Second).Add(-3 * time.Hour) + for i, tag := range []string{"a", "b", "c"} { + id := readerID(fixture, "offset", tag) + ids = append(ids, id) + issue := readerIssue(id, types.TypeTask, scope) + at := base.Add(time.Duration(i) * time.Minute) + issue.CreatedAt = at + issue.UpdatedAt = at + seedReaderIssue(t, ctx, fixture, issue) + } + idScope := readerIDFilter(ids...) + + for _, test := range []struct { + what string + call func(offset int) (publicops.IssuePage, error) + }{ + {"Ready", func(offset int) (publicops.IssuePage, error) { + return fixture.Reader.Ready(ctx, publicops.ReadyRequest{ + Labels: []string{scope}, Sort: "oldest", Offset: offset, + }) + }}, + {"List", func(offset int) (publicops.IssuePage, error) { + return fixture.Reader.List(ctx, publicops.ListRequest{ + IDFilter: idScope, SortBy: "created", Offset: offset, + }) + }}, + } { + // Offset 0 is not a page request, so it is served everywhere and is + // the baseline the paged call has to differ from. + unpaged, err := test.call(0) + if err != nil { + t.Fatalf("%s at Offset 0: %v", test.what, err) + } + if len(unpaged.Items) != len(ids) { + t.Fatalf("%s at Offset 0 returned %v, want the three seeded rows", test.what, readerPageIDs(unpaged)) + } + + paged, err := test.call(1) + if err != nil { + var unsupported *publicops.ErrUnsupported + if !errors.As(err, &unsupported) { + t.Errorf("%s at Offset 1 refused with %v; a refusal has to be a typed *ErrUnsupported a caller can classify", test.what, err) + continue + } + if unsupported.Op == "" || unsupported.Backend == "" { + t.Errorf("%s at Offset 1 refused with Op=%q Backend=%q; a refusal naming neither the operation nor the backend leaves the caller nowhere to go", + test.what, unsupported.Op, unsupported.Backend) + } + continue + } + if slices.Equal(readerPageIDs(paged), readerPageIDs(unpaged)) { + t.Errorf("%s at Offset 1 returned the same page as Offset 0 (%v) and no error: the offset was silently ignored", + test.what, readerPageIDs(paged)) + } + } +} + +// RunReaderReadySortPoliciesOrderTheSameRows pins that the two concrete ready +// policies order identically across implementations (reader.go:79-83). The rows +// are chosen so the policies disagree with each other: the newer row is the +// higher priority, so "priority" leads with it and "oldest" leads with the other. +// A seam that ignored the policy would answer both requests the same way and +// fail one of them. +// +// The empty-sort fallback is deliberately NOT pinned. The doc says it resolves +// to hybrid at the storage layer and that no front door should rely on it, and +// hybrid's order depends on a wall-clock recency cutoff +// (sqlbuild/ready.go:57-65) — pinning it would both contradict the doc and be +// time-dependent. +func RunReaderReadySortPoliciesOrderTheSameRows(t *testing.T, ctx context.Context, fixture ReaderFixture) { + t.Helper() + scope := readerLabel(fixture, "rdysort") + urgent := readerID(fixture, "rdysort", "urgent") + ancient := readerID(fixture, "rdysort", "ancient") + + now := time.Now().UTC() + urgentIssue := readerIssue(urgent, types.TypeTask, scope) + urgentIssue.Priority = 0 + urgentIssue.CreatedAt = now.Add(-1 * time.Hour) + ancientIssue := readerIssue(ancient, types.TypeTask, scope) + ancientIssue.Priority = 3 + ancientIssue.CreatedAt = now.Add(-90 * 24 * time.Hour) + + seedReaderIssue(t, ctx, fixture, urgentIssue) + seedReaderIssue(t, ctx, fixture, ancientIssue) + + for _, test := range []struct { + policy string + want []string + }{ + {"priority", []string{urgent, ancient}}, + {"oldest", []string{ancient, urgent}}, + } { + page, err := fixture.Reader.Ready(ctx, publicops.ReadyRequest{Labels: []string{scope}, Sort: test.policy}) + if err != nil { + t.Fatalf("Ready --sort %s: %v", test.policy, err) + } + assertReaderPageIDs(t, "Ready --sort "+test.policy, page, test.want) + } +} + +// RunReaderListDefaultExclusionsAndTheirOverrides pins what the default listing +// hides and which knob takes each exclusion back off (reader.go:117-123, +// reader.go:182-188, reader.go:204). +// +// The load-bearing half is that Status and AllFlag REPLACE the status +// exclusions rather than fighting them, and that they replace ONLY those: a +// caller who asks for everything still does not get gates, templates or the +// ephemeral plane, each of which has its own knob. +// +// PINNED IS TWO EXCLUSIONS, not one, and the leaf says so (reader.go:109-115). +// A row can be pinned by STATUS or by the separate Pinned FLAG, each is hidden +// by its own predicate, and each has a different knob: `Status: pinned` for the +// first, PinnedFlag for the second. The table seeds one of each — plus the two +// rows carrying BOTH, which are the only rows that can tell the predicates +// apart when a request lifts one of them and not the other. +// +// (This was a spec gap, bd-yby99.16: the enumeration named status, template, +// gate and infra but not pinned, so no answer could be asserted without +// inventing a promise. The owner ruled the doc was lagging the code.) +func RunReaderListDefaultExclusionsAndTheirOverrides(t *testing.T, ctx context.Context, fixture ReaderFixture) { + t.Helper() + open := readerID(fixture, "lsdef", "open") + closed := readerID(fixture, "lsdef", "closed") + gate := readerID(fixture, "lsdef", "gate") + template := readerID(fixture, "lsdef", "template") + wisp := readerID(fixture, "lsdef", "wisp") + flagOnly := readerID(fixture, "lsdef", "flagonly") + statusOnly := readerID(fixture, "lsdef", "statusonly") + flagAndStatus := readerID(fixture, "lsdef", "flagandstatus") + flagAndClosed := readerID(fixture, "lsdef", "flagandclosed") + + closedIssue := readerIssue(closed, types.TypeTask, "") + closedIssue.Status = types.StatusClosed + templateIssue := readerIssue(template, types.TypeTask, "") + templateIssue.IsTemplate = true + wispIssue := readerIssue(wisp, types.TypeTask, "") + wispIssue.Ephemeral = true + // Open, pinned only by the FLAG: no status exclusion can hide it, so it + // isolates the flag predicate. + flagOnlyIssue := readerIssue(flagOnly, types.TypeTask, "") + flagOnlyIssue.Pinned = true + // Pinned only by STATUS: the flag predicate cannot hide it, so it isolates + // the status exclusion. + statusOnlyIssue := readerIssue(statusOnly, types.TypeTask, "") + statusOnlyIssue.Status = types.StatusPinned + // Both, so a request that lifts only the status half still has a row the + // flag half would hide — which is what makes "Status pinned drops the flag + // predicate too" an observation rather than a restatement. + flagAndStatusIssue := readerIssue(flagAndStatus, types.TypeTask, "") + flagAndStatusIssue.Status = types.StatusPinned + flagAndStatusIssue.Pinned = true + // Hidden twice over the other way round, so PinnedFlag dropping the status + // exclusions on its way is observable too. + flagAndClosedIssue := readerIssue(flagAndClosed, types.TypeTask, "") + flagAndClosedIssue.Status = types.StatusClosed + flagAndClosedIssue.Pinned = true + + seedReaderIssue(t, ctx, fixture, readerIssue(open, types.TypeTask, "")) + seedReaderIssue(t, ctx, fixture, closedIssue) + seedReaderIssue(t, ctx, fixture, readerIssue(gate, types.TypeGate, "")) + seedReaderIssue(t, ctx, fixture, templateIssue) + seedReaderWisp(t, ctx, fixture, wispIssue) + seedReaderIssue(t, ctx, fixture, flagOnlyIssue) + seedReaderIssue(t, ctx, fixture, statusOnlyIssue) + seedReaderIssue(t, ctx, fixture, flagAndStatusIssue) + seedReaderIssue(t, ctx, fixture, flagAndClosedIssue) + + scope := readerIDFilter(open, closed, gate, template, wisp, flagOnly, statusOnly, flagAndStatus, flagAndClosed) + for _, test := range []struct { + name string + req publicops.ListRequest + want []string + }{ + {"default", publicops.ListRequest{IDFilter: scope}, []string{open}}, + {"AllFlag replaces the status exclusions only", publicops.ListRequest{IDFilter: scope, AllFlag: true}, []string{open, closed, flagOnly, statusOnly, flagAndStatus, flagAndClosed}}, + {"Status replaces the status exclusions", publicops.ListRequest{IDFilter: scope, Status: string(types.StatusClosed)}, []string{closed}}, + {"Status pinned drops the flag predicate too", publicops.ListRequest{IDFilter: scope, Status: string(types.StatusPinned)}, []string{statusOnly, flagAndStatus}}, + {"PinnedFlag answers the flagged rows at any status", publicops.ListRequest{IDFilter: scope, PinnedFlag: true}, []string{flagOnly, flagAndStatus, flagAndClosed}}, + {"NoPinnedFlag changes nothing on a default listing", publicops.ListRequest{IDFilter: scope, NoPinnedFlag: true}, []string{open}}, + {"NoPinnedFlag holds the flag predicate under AllFlag", publicops.ListRequest{IDFilter: scope, AllFlag: true, NoPinnedFlag: true}, []string{open, closed, statusOnly}}, + {"IncludeGates", publicops.ListRequest{IDFilter: scope, IncludeGates: true}, []string{open, gate}}, + {"IncludeTemplates", publicops.ListRequest{IDFilter: scope, IncludeTemplates: true}, []string{open, template}}, + {"IncludeInfra reaches the ephemeral plane", publicops.ListRequest{IDFilter: scope, IncludeInfra: true}, []string{open, wisp}}, + } { + page, err := fixture.Reader.List(ctx, test.req) + if err != nil { + t.Fatalf("List (%s): %v", test.name, err) + } + assertReaderPageIDSet(t, "List ("+test.name+")", page, test.want) + } +} + +// RunReaderListRejectsATypeOutsideTheWorkspaceVocabulary pins the asymmetry +// ListRequest.IssueType's doc calls out by name (reader.go:124-126): this method +// validates the type against the workspace vocabulary and ERRORS, where +// ReadyRequest.IssueType matches nothing and succeeds. Both halves are asserted +// here, in one place, because the promise is the difference between them. +func RunReaderListRejectsATypeOutsideTheWorkspaceVocabulary(t *testing.T, ctx context.Context, fixture ReaderFixture) { + t.Helper() + const unknown = "no-such-type-anywhere" + + page, err := fixture.Reader.List(ctx, publicops.ListRequest{IssueType: unknown}) + if err == nil { + t.Fatalf("List with an unknown issue type returned %d items and no error, want a refusal", len(page.Items)) + } + + // A built-in type is accepted by the same validation, so the refusal above + // is the vocabulary check and not a blanket rejection of IssueType. + if _, err := fixture.Reader.List(ctx, publicops.ListRequest{ + IDFilter: readerIDFilter(readerID(fixture, "lstype", "absent")), + IssueType: string(types.TypeTask), + }); err != nil { + t.Fatalf("List with a built-in issue type: %v", err) + } + + if _, err := fixture.Reader.Ready(ctx, publicops.ReadyRequest{IssueType: unknown}); err != nil { + t.Fatalf("the same unknown type must be tolerated by Ready, which matches nothing rather than failing: %v", err) + } +} + +// RunReaderListNaturalNumericIDSortTrimsAfterTheFetch pins the sort the database +// cannot express (reader.go:239-250). `--sort id` needs natural-numeric +// comparison — bd-9 before bd-10, which no lexical ORDER BY produces — so the +// query runs unlimited and the page limit is applied afterwards, in Go, over the +// full result set. This is the historical divergence (one implementation +// returned the --ready arm untrimmed), asserted here against real rows rather +// than a stub seam. +func RunReaderListNaturalNumericIDSortTrimsAfterTheFetch(t *testing.T, ctx context.Context, fixture ReaderFixture) { + t.Helper() + one := readerID(fixture, "lsnat", "1") + two := readerID(fixture, "lsnat", "2") + ten := readerID(fixture, "lsnat", "10") + // Seeded in an order that is neither the natural order nor the lexical one, + // so an implementation that returns storage order fails visibly. + for _, id := range []string{ten, one, two} { + seedReaderIssue(t, ctx, fixture, readerIssue(id, types.TypeTask, "")) + } + scope := readerIDFilter(one, two, ten) + + page, err := fixture.Reader.List(ctx, publicops.ListRequest{IDFilter: scope, SortBy: "id"}) + if err != nil { + t.Fatalf("List --sort id: %v", err) + } + assertReaderPageIDs(t, "List --sort id", page, []string{one, two, ten}) + if page.HasMore { + t.Error("List --sort id reported HasMore on an untruncated page") + } + + // The trim is the ONLY thing bounding this page, and it runs after the + // natural sort: a limit of two must keep the two natural-lowest ids, not + // the two the query happened to return first. + page, err = fixture.Reader.List(ctx, publicops.ListRequest{IDFilter: scope, SortBy: "id", Limit: readerLimit(2)}) + if err != nil { + t.Fatalf("List --sort id --limit 2: %v", err) + } + assertReaderPageIDs(t, "List --sort id --limit 2", page, []string{one, two}) + if !page.HasMore { + t.Error("List --sort id --limit 2 hid a row without reporting HasMore") + } + + page, err = fixture.Reader.List(ctx, publicops.ListRequest{IDFilter: scope, SortBy: "id", Reverse: true, Limit: readerLimit(2)}) + if err != nil { + t.Fatalf("List --sort id --reverse --limit 2: %v", err) + } + assertReaderPageIDs(t, "List --sort id --reverse --limit 2", page, []string{ten, two}) +} + +// RunReaderListKeysetPositionResumesTheCreatedDescIDAscOrder pins the decoded +// cursor (reader.go:264-268). The position is a PAIR, and both halves matter: +// rows older than the cursor's timestamp are returned, and rows sharing that +// timestamp are returned only when their id sorts after the cursor's. A seam +// that compared the timestamp alone would drop the same-second row, which is +// exactly how a keyset page loses records. +func RunReaderListKeysetPositionResumesTheCreatedDescIDAscOrder(t *testing.T, ctx context.Context, fixture ReaderFixture) { + t.Helper() + newest := readerID(fixture, "lskeys", "c") + cursor := readerID(fixture, "lskeys", "b1") + sameSecond := readerID(fixture, "lskeys", "b2") + oldest := readerID(fixture, "lskeys", "a") + + // Whole seconds, minutes apart: the created_at columns are DATETIME, so a + // sub-second difference is not something a cursor may depend on. + base := time.Now().UTC().Truncate(time.Second).Add(-1 * time.Hour) + cursorAt := base.Add(30 * time.Minute) + for _, seed := range []struct { + id string + at time.Time + }{ + {newest, base.Add(45 * time.Minute)}, + {cursor, cursorAt}, + {sameSecond, cursorAt}, + {oldest, base}, + } { + issue := readerIssue(seed.id, types.TypeTask, "") + issue.CreatedAt = seed.at + issue.UpdatedAt = seed.at + seedReaderIssue(t, ctx, fixture, issue) + } + + page, err := fixture.Reader.List(ctx, publicops.ListRequest{ + IDFilter: readerIDFilter(newest, cursor, sameSecond, oldest), + SortBy: "created", + AfterCreatedAt: &cursorAt, + AfterID: cursor, + }) + if err != nil { + t.Fatalf("List from a keyset position: %v", err) + } + // created_at DESC, id ASC: the same-second row with the larger id comes + // first, then everything strictly older. The cursor row itself and + // everything newer are already delivered and must not repeat. + assertReaderPageIDs(t, "List from a keyset position", page, []string{sameSecond, oldest}) +} + +// RunReaderListReadyFlagAnswersTheBlockerAwareSet pins the CARRIED half of the +// --ready arm (reader.go:204-237): it switches the query to blocker-aware ready +// work, the labels that scope it survive the trip, and the page epilogue still +// runs over the result. The last part is the regression: the arm once returned +// storage order, unsorted and untrimmed, while the other arm of the same method +// sorted and trimmed. +// +// Scoped by LABEL rather than by the id set every other list case here uses, +// and that is now the doc's promise rather than a workaround: the ready query +// is reached through a narrower filter vocabulary, Labels is on the carried +// side of it and IDFilter is not. The DROPPED half — and the refusal that +// replaced the silent widening — is +// RunReaderListReadyFlagRefusesAFilterItCannotCarry. +func RunReaderListReadyFlagAnswersTheBlockerAwareSet(t *testing.T, ctx context.Context, fixture ReaderFixture) { + t.Helper() + scope := readerLabel(fixture, "lsready") + blocker := readerID(fixture, "lsready", "1") + blocked := readerID(fixture, "lsready", "2") + free := readerID(fixture, "lsready", "10") + for _, id := range []string{blocker, blocked, free} { + seedReaderIssue(t, ctx, fixture, readerIssue(id, types.TypeTask, scope)) + } + if err := fixture.AddDependency(ctx, &types.Dependency{ + IssueID: blocked, DependsOnID: blocker, Type: types.DepBlocks, + }, "seed"); err != nil { + t.Fatalf("seed the blocking edge: %v", err) + } + + page, err := fixture.Reader.List(ctx, publicops.ListRequest{ + Labels: []string{scope}, ReadyFlag: true, SortBy: "id", + }) + if err != nil { + t.Fatalf("List --ready: %v", err) + } + assertReaderPageIDs(t, "List --ready", page, []string{blocker, free}) + + // The same arm, under a sort the database cannot express and a limit: the + // epilogue has to sort AND trim here, and report the truncation. + page, err = fixture.Reader.List(ctx, publicops.ListRequest{ + Labels: []string{scope}, ReadyFlag: true, SortBy: "id", Limit: readerLimit(1), + }) + if err != nil { + t.Fatalf("List --ready --sort id --limit 1: %v", err) + } + assertReaderPageIDs(t, "List --ready --sort id --limit 1", page, []string{blocker}) + if !page.HasMore { + t.Error("List --ready --sort id --limit 1 hid a row without reporting HasMore") + } +} + +// RunReaderListReadyFlagRefusesAFilterItCannotCarry pins the DROPPED half of +// the --ready arm (reader.go:219-226): a request that asks the blocker-aware +// query to honor a filter it cannot carry is REFUSED with ErrValidation +// naming the field, not answered with the wider set. +// +// This is the case that would have caught the original defect. An +// IDFilter-scoped --ready request used to answer with every open row in the +// workspace — measured at 18 rows for a three-id scope on the unit-of-work leg, +// where the suite shares one database. The store-backed leg ran the same +// unscoped query and passed anyway, because each of its cases owns a private +// branch and the workspace happened to BE the seeded rows. A silently dropped +// filter looks exactly like a passing test, so the assertion cannot be on the +// rows: it has to be on the refusal. +// +// The message is asserted, not just the sentinel. A generic "unsupported +// combination" would leave a caller to bisect their own request to find which +// half of it was the problem. +func RunReaderListReadyFlagRefusesAFilterItCannotCarry(t *testing.T, ctx context.Context, fixture ReaderFixture) { + t.Helper() + scope := readerLabel(fixture, "lsdrop") + one := readerID(fixture, "lsdrop", "1") + two := readerID(fixture, "lsdrop", "2") + for _, id := range []string{one, two} { + seedReaderIssue(t, ctx, fixture, readerIssue(id, types.TypeTask, scope)) + } + cutoff := time.Now().UTC().Add(-time.Hour) + maxPriority := 1 + + // One per family the doc names, not one per field: the id set, the text + // searches, the date bounds, the pinned/absent-relation flags, the numeric + // range and the keyset position. + for _, tc := range []struct { + name string + req publicops.ListRequest + field string + }{ + {"IDFilter", publicops.ListRequest{IDFilter: readerIDFilter(one), ReadyFlag: true}, "IDFilter"}, + {"TitleContains", publicops.ListRequest{Labels: []string{scope}, TitleContains: one, ReadyFlag: true}, "TitleContains"}, + {"CreatedAfter", publicops.ListRequest{Labels: []string{scope}, CreatedAfter: &cutoff, ReadyFlag: true}, "CreatedAfter"}, + {"PinnedFlag", publicops.ListRequest{Labels: []string{scope}, PinnedFlag: true, ReadyFlag: true}, "PinnedFlag"}, + {"PriorityMax", publicops.ListRequest{Labels: []string{scope}, PriorityMax: &maxPriority, ReadyFlag: true}, "PriorityMax"}, + {"keyset position", publicops.ListRequest{Labels: []string{scope}, AfterCreatedAt: &cutoff, AfterID: one, ReadyFlag: true}, "AfterCreatedAt"}, + } { + page, err := fixture.Reader.List(ctx, tc.req) + if !errors.Is(err, publicops.ErrValidation) { + t.Errorf("List --ready with %s: got (%d items, %v); want ErrValidation", tc.name, len(page.Items), err) + continue + } + if !strings.Contains(err.Error(), tc.field) { + t.Errorf("List --ready with %s refused without naming the field: %v", tc.name, err) + } + } + + // Naming every field it could not honor, not just the first: a caller who + // fixes one and retries should not have to discover the next one the same + // way. + _, err := fixture.Reader.List(ctx, publicops.ListRequest{ + IDFilter: readerIDFilter(one), OverdueFlag: true, ReadyFlag: true, + }) + if !errors.Is(err, publicops.ErrValidation) { + t.Fatalf("List --ready with two dropped fields: %v; want ErrValidation", err) + } + for _, field := range []string{"IDFilter", "OverdueFlag"} { + if !strings.Contains(err.Error(), field) { + t.Errorf("List --ready with two dropped fields did not name %s: %v", field, err) + } + } + + // The refusal is scoped to what the query cannot carry. Labels is carried, + // and NoPinnedFlag is already true of the ready set, so neither is refused + // — the doc promises both, and a validator that refused every flag it did + // not recognize would break `bd list --ready` outright. + page, err := fixture.Reader.List(ctx, publicops.ListRequest{ + Labels: []string{scope}, NoPinnedFlag: true, ReadyFlag: true, SortBy: "id", + }) + if err != nil { + t.Fatalf("List --ready --no-pinned on a carried scope: %v", err) + } + assertReaderPageIDs(t, "List --ready --no-pinned on a carried scope", page, []string{one, two}) + + // Without ReadyFlag the same dropped fields are ordinary list filters and + // must still work: the refusal belongs to the arm, not to the request type. + page, err = fixture.Reader.List(ctx, publicops.ListRequest{IDFilter: readerIDFilter(one), SortBy: "id"}) + if err != nil { + t.Fatalf("List --id without --ready: %v", err) + } + assertReaderPageIDs(t, "List --id without --ready", page, []string{one}) +} + +// RunReaderListEmptyPageIsWellFormed pins the page shape when nothing matches +// (reader.go:310-315). Items is never nil for a successful call, so no caller +// has to tell null from empty to learn that nothing matched, and an empty page +// hid nothing. +func RunReaderListEmptyPageIsWellFormed(t *testing.T, ctx context.Context, fixture ReaderFixture) { + t.Helper() + absent := readerIDFilter(readerID(fixture, "lsempty", "never-seeded")) + + listed, err := fixture.Reader.List(ctx, publicops.ListRequest{IDFilter: absent}) + if err != nil { + t.Fatalf("List matching nothing: %v", err) + } + assertReaderPageIDs(t, "List matching nothing", listed, nil) + if listed.HasMore { + t.Error("List matching nothing reported HasMore") + } + + // Ready shares the page type deliberately, so it owes the same shape. + ready, err := fixture.Reader.Ready(ctx, publicops.ReadyRequest{Labels: []string{readerLabel(fixture, "lsempty-never-applied")}}) + if err != nil { + t.Fatalf("Ready matching nothing: %v", err) + } + assertReaderPageIDs(t, "Ready matching nothing", ready, nil) + if ready.HasMore { + t.Error("Ready matching nothing reported HasMore") + } +} + +// RunReaderGetResolvesTheExactIDAcrossBothPlanes pins GetRequest.ID +// (reader.go:273-276): the id is exact and canonical, the issue-to-wisp fallback +// happens inside, and there is no fuzzy, prefix or substring resolution. The +// prefix probe is the half that matters — an affordance that can answer with a +// different issue than the caller named has no place on a contract an +// unattended client calls. +func RunReaderGetResolvesTheExactIDAcrossBothPlanes(t *testing.T, ctx context.Context, fixture ReaderFixture) { + t.Helper() + issue := readerID(fixture, "getid", "durable") + wisp := readerID(fixture, "getid", "ephemeral") + wispIssue := readerIssue(wisp, types.TypeTask, "") + wispIssue.Ephemeral = true + seedReaderIssue(t, ctx, fixture, readerIssue(issue, types.TypeTask, "")) + seedReaderWisp(t, ctx, fixture, wispIssue) + + for _, id := range []string{issue, wisp} { + details, err := fixture.Reader.Get(ctx, publicops.GetRequest{ID: id}) + if err != nil { + t.Fatalf("Get(%s): %v", id, err) + } + if details == nil || details.ID != id { + t.Fatalf("Get(%s) answered with %#v, want the issue itself", id, details) + } + } + + for _, name := range []struct{ what, id string }{ + {"a prefix of a real id", issue[:len(issue)-2]}, + {"a real id with a suffix", issue + "x"}, + } { + details, err := fixture.Reader.Get(ctx, publicops.GetRequest{ID: name.id}) + if !errors.Is(err, publicops.ErrNotFound) { + t.Errorf("Get(%s) = (%#v, %v), want ErrNotFound: this contract resolves exact ids only", name.what, details, err) + } + } +} + +// RunReaderGetMissIsNotFoundAndBackendFailureDoesNotDecay pins both halves of +// Get's error promise (reader.go:420-423). A miss on BOTH planes is ErrNotFound; +// a backend failure passes through unchanged and never decays into not-found. +// +// The decay half needs a fixture that can induce a backend error without +// destroying the fixture for the cases that follow, so it uses an +// already-canceled context: every backend has to begin a transaction or open a +// connection before it can look anything up, so the failure lands underneath the +// resolve rather than inside it. What is asserted is only that the error is NOT +// ErrNotFound — the error's spelling is each backend's own. +func RunReaderGetMissIsNotFoundAndBackendFailureDoesNotDecay(t *testing.T, ctx context.Context, fixture ReaderFixture) { + t.Helper() + missing := readerID(fixture, "getmiss", "never-seeded") + + details, err := fixture.Reader.Get(ctx, publicops.GetRequest{ID: missing}) + if !errors.Is(err, publicops.ErrNotFound) { + t.Fatalf("Get on a miss = (%#v, %v), want ErrNotFound", details, err) + } + if details != nil { + t.Errorf("Get on a miss returned %#v alongside its error, want nil", details) + } + + dead, cancel := context.WithCancel(ctx) + cancel() + details, err = fixture.Reader.Get(dead, publicops.GetRequest{ID: missing}) + if err == nil { + t.Fatalf("Get on a dead context returned %#v and no error", details) + } + if errors.Is(err, publicops.ErrNotFound) { + t.Errorf("a backend failure decayed into not-found: %v", err) + } +} + +// RunReaderGetOptionalRowListsAreOffByDefault pins the two DetailOptions +// (reader.go:300-303): the detail view carries counts either way, the expensive +// row lists are absent until asked for, and a positive comment count with no +// rows says so rather than reading as "no comments". +func RunReaderGetOptionalRowListsAreOffByDefault(t *testing.T, ctx context.Context, fixture ReaderFixture) { + t.Helper() + subject := readerID(fixture, "getopt", "subject") + dependent := readerID(fixture, "getopt", "dependent") + seedReaderIssue(t, ctx, fixture, readerIssue(subject, types.TypeTask, "")) + seedReaderIssue(t, ctx, fixture, readerIssue(dependent, types.TypeTask, "")) + if err := fixture.AddDependency(ctx, &types.Dependency{ + IssueID: dependent, DependsOnID: subject, Type: types.DepBlocks, + }, "seed"); err != nil { + t.Fatalf("seed the incoming edge: %v", err) + } + const commentText = "the detail view carries a count for this" + if err := fixture.AddComment(ctx, subject, "seed", commentText); err != nil { + t.Fatalf("seed the comment: %v", err) + } + + details, err := fixture.Reader.Get(ctx, publicops.GetRequest{ID: subject}) + if err != nil { + t.Fatalf("Get with both options off: %v", err) + } + assertReaderCount(t, "DependentCount", details.DependentCount, 1) + assertReaderCount(t, "CommentCount", details.CommentCount, 1) + if len(details.Dependents) != 0 { + t.Errorf("Get with IncludeDependents off returned %d dependent rows, want none", len(details.Dependents)) + } + if len(details.Comments) != 0 { + t.Errorf("Get with IncludeComments off returned %d comment rows, want none", len(details.Comments)) + } + if details.CommentsOmitted == nil || !*details.CommentsOmitted { + t.Errorf("CommentsOmitted = %v with a nonzero comment count and no rows, want true", details.CommentsOmitted) + } + + details, err = fixture.Reader.Get(ctx, publicops.GetRequest{ + ID: subject, IncludeDependents: true, IncludeComments: true, + }) + if err != nil { + t.Fatalf("Get with both options on: %v", err) + } + assertReaderCount(t, "DependentCount with the rows requested", details.DependentCount, 1) + assertReaderCount(t, "CommentCount with the rows requested", details.CommentCount, 1) + if len(details.Dependents) != 1 || details.Dependents[0].ID != dependent { + t.Errorf("Get with IncludeDependents returned %v, want the one dependent %s", readerDependencyIDs(details.Dependents), dependent) + } + if len(details.Comments) != 1 || details.Comments[0].Text != commentText { + t.Errorf("Get with IncludeComments returned %d rows, want the one seeded comment verbatim", len(details.Comments)) + } + if details.CommentsOmitted != nil { + t.Errorf("CommentsOmitted = %v alongside a populated Comments slice, want unset", *details.CommentsOmitted) + } +} + +// RunReaderGetDetailShapeMatchesTheSeededIssue pins the shape of the detail view +// against what was actually stored (reader.go:15, reader.go:272-304): the +// issue's own fields, its labels, its OUTGOING edges with their types, and the +// three cardinalities. The direction split is the part worth pinning — an +// implementation that answered Dependencies with the incoming edges would still +// return a plausible-looking detail view. +func RunReaderGetDetailShapeMatchesTheSeededIssue(t *testing.T, ctx context.Context, fixture ReaderFixture) { + t.Helper() + subject := readerID(fixture, "getshape", "subject") + blocker := readerID(fixture, "getshape", "blocker") + label := readerLabel(fixture, "getshape") + seeded := readerIssue(subject, types.TypeBug, label) + seeded.Title = "a title the detail view must echo" + seeded.Priority = 1 + seedReaderIssue(t, ctx, fixture, seeded) + seedReaderIssue(t, ctx, fixture, readerIssue(blocker, types.TypeTask, "")) + if err := fixture.AddDependency(ctx, &types.Dependency{ + IssueID: subject, DependsOnID: blocker, Type: types.DepBlocks, + }, "seed"); err != nil { + t.Fatalf("seed the outgoing edge: %v", err) + } + + details, err := fixture.Reader.Get(ctx, publicops.GetRequest{ID: subject}) + if err != nil { + t.Fatalf("Get: %v", err) + } + if details.Title != seeded.Title { + t.Errorf("Title = %q, want %q", details.Title, seeded.Title) + } + if details.IssueType != types.TypeBug { + t.Errorf("IssueType = %q, want %q", details.IssueType, types.TypeBug) + } + if details.Priority != 1 { + t.Errorf("Priority = %d, want 1", details.Priority) + } + if !slices.Contains(details.Labels, label) { + t.Errorf("Labels = %v, want it to carry the seeded label %q", details.Labels, label) + } + if got := readerDependencyIDs(details.Dependencies); !slices.Equal(got, []string{blocker}) { + t.Errorf("Dependencies = %v, want the one outgoing edge to %s", got, blocker) + } + if len(details.Dependencies) == 1 && details.Dependencies[0].DependencyType != types.DepBlocks { + t.Errorf("the outgoing edge came back with type %q, want %q", details.Dependencies[0].DependencyType, types.DepBlocks) + } + assertReaderCount(t, "DependencyCount", details.DependencyCount, 1) + assertReaderCount(t, "DependentCount", details.DependentCount, 0) + assertReaderCount(t, "CommentCount", details.CommentCount, 0) +} + +// RunReaderDoesNotMutateTheCallerRequest is the role's single request-snapshot +// tripwire (reader.go:326-327). One case for the whole role, not one per +// method: the promise is a property of the shared implementation, and every +// method is driven here through the same request values so a normalization +// written in place is caught wherever it lives. +// +// The slices are the point. A builder that normalized labels or exclude-types +// into the caller's backing array instead of a new one would leave the request +// struct's header untouched and its CONTENTS changed, which is what +// reflect.DeepEqual over a deep copy sees and a shallow compare does not. +func RunReaderDoesNotMutateTheCallerRequest(t *testing.T, ctx context.Context, fixture ReaderFixture) { + t.Helper() + limit := 5 + ready := publicops.ReadyRequest{ + Labels: []string{"Beta", "alpha"}, + LabelsAny: []string{"gamma", " delta "}, + ExcludeLabels: []string{"omega"}, + ExcludeTypes: []string{"chore,epic", " feat "}, + MetadataFields: map[string]string{"kind": "probe"}, + Sort: "priority", + Limit: &limit, + } + list := publicops.ListRequest{ + IDFilter: readerIDFilter(readerID(fixture, "nomut", "a"), readerID(fixture, "nomut", "b")), + Labels: []string{"Beta", "alpha"}, + LabelsAny: []string{"gamma", " delta "}, + ExcludeLabels: []string{"omega"}, + ExcludeTypes: []string{"chore,epic", " feat "}, + MetadataFields: map[string]string{"kind": "probe"}, + SortBy: "id", + Limit: &limit, + } + get := publicops.GetRequest{ID: readerID(fixture, "nomut", "absent")} + + readySnapshot := readerCopyReadyRequest(ready) + listSnapshot := readerCopyListRequest(list) + getSnapshot := get + + if _, err := fixture.Reader.Ready(ctx, ready); err != nil { + t.Fatalf("Ready: %v", err) + } + if _, err := fixture.Reader.List(ctx, list); err != nil { + t.Fatalf("List: %v", err) + } + if _, err := fixture.Reader.Get(ctx, get); !errors.Is(err, publicops.ErrNotFound) { + t.Fatalf("Get on an absent id: %v", err) + } + + if !reflect.DeepEqual(ready, readySnapshot) { + t.Errorf("Ready mutated the caller's request\n after: %#v\nbefore: %#v", ready, readySnapshot) + } + if !reflect.DeepEqual(list, listSnapshot) { + t.Errorf("List mutated the caller's request\n after: %#v\nbefore: %#v", list, listSnapshot) + } + if !reflect.DeepEqual(get, getSnapshot) { + t.Errorf("Get mutated the caller's request\n after: %#v\nbefore: %#v", get, getSnapshot) + } +} + +// RunReaderListLimitBoundaryUnderASortTheDatabaseCanExpress walks +// ListRequest.Limit's vocabulary at the page boundary (reader.go:246-250) under +// a display order SQL CAN express, which is the only way to reach the seam this +// case exists for. +// +// Both existing List cases that set a limit sort by id, and workapi.SQLLimit +// zeroes the QUERY's limit for that sort (workapi/list.go:36-41) because +// natural-numeric order has to be applied in Go over the whole result set. So +// both of them run the fetch-everything-then-trim path and neither ever reaches +// the over-fetch. Under `--sort created` the limit is pushed into the query +// instead, and the two bodies detect truncation by genuinely different +// mechanisms: the store body asks the query for one row past the page +// (workapi.WithFetchOneExtra, storereader/reader.go:118) and lets the extra +// row's presence be the answer, while the unit-of-work body renders LIMIT n+1 +// itself and reports the verdict natively (domain/db/issue_search.go:511-529). +// An off-by-one in either one shows here and nowhere else in this file: +// RunReaderReadyLimitBoundary pins the analogous mechanism for the READY query, +// and the store body derives its extra row differently per method — an inline +// limit+1 in Ready (storereader/reader.go:83-88) against WithFetchOneExtra in +// List. +// +// The page is asserted as a PREFIX of the unlimited answer rather than by id +// set. "Limit bounds the page the caller receives" is a bound on a page, not a +// license to answer with a different one, and a limit pushed into a query whose +// ORDER BY disagrees with the epilogue's would return the wrong END of the +// order while still returning the right COUNT. +func RunReaderListLimitBoundaryUnderASortTheDatabaseCanExpress(t *testing.T, ctx context.Context, fixture ReaderFixture) { + t.Helper() + var ids []string + base := time.Now().UTC().Truncate(time.Second).Add(-5 * time.Hour) + for i, tag := range []string{"a", "b", "c"} { + id := readerID(fixture, "lslimit", tag) + ids = append(ids, id) + issue := readerIssue(id, types.TypeTask, "") + // Minutes apart and whole seconds, so `--sort created` is a total order + // over these rows and "the first two" is a well-defined answer. + at := base.Add(time.Duration(i) * time.Minute) + issue.CreatedAt = at + issue.UpdatedAt = at + seedReaderIssue(t, ctx, fixture, issue) + } + scope := readerIDFilter(ids...) + + full, err := fixture.Reader.List(ctx, publicops.ListRequest{ + IDFilter: scope, SortBy: "created", Limit: readerLimit(0), + }) + if err != nil { + t.Fatalf("List --sort created --limit 0: %v", err) + } + if len(full.Items) != len(ids) { + t.Fatalf("List --sort created --limit 0 returned %v, want the three seeded rows", readerPageIDs(full)) + } + if full.HasMore { + t.Error("List --sort created --limit 0 is unlimited and can hide nothing, but reported HasMore") + } + order := readerPageIDs(full) + + for _, test := range []struct { + name string + limit *int + wantN int + hasMore bool + }{ + {"unset takes the shared list default, which does not truncate three rows", nil, 3, false}, + {"a limit under the result count truncates and says so", readerLimit(2), 2, true}, + {"a limit exactly at the result count hides nothing", readerLimit(3), 3, false}, + {"a limit of one is the tightest page the over-fetch has to get right", readerLimit(1), 1, true}, + } { + page, err := fixture.Reader.List(ctx, publicops.ListRequest{ + IDFilter: scope, SortBy: "created", Limit: test.limit, + }) + if err != nil { + t.Fatalf("List --sort created (%s): %v", test.name, err) + } + assertReaderPageNotNil(t, "List --sort created ("+test.name+")", page) + if len(page.Items) != test.wantN { + t.Errorf("List --sort created (%s) returned %d items %v, want %d", test.name, len(page.Items), readerPageIDs(page), test.wantN) + } + if page.HasMore != test.hasMore { + t.Errorf("List --sort created (%s) HasMore = %v, want %v", test.name, page.HasMore, test.hasMore) + } + assertReaderPageIsPrefixOf(t, "List --sort created ("+test.name+")", page, order) + } +} + +// RunReaderReadySetOwnsItsStatusPinnedAndTemplateDecisions pins the three things +// the ready set decides for itself, which no request field overrides +// (reader.go:216-217, 228-235, 415-416). +// +// STATUS: ready work is open work — "Open only, not in_progress" +// (workapi/ready.go:44) — so neither an in_progress nor a closed row is in it. +// PINNED: it never returns pinned issues. TEMPLATES: it applies no template +// predicate AT ALL, which is the counter-intuitive half — the default listing's +// template exclusion does not reach this query, so an open task-type template IS +// ready work and IncludeTemplates changes nothing. And SkipLabels is not carried +// either: labels are hydrated on this arm either way. +// +// Asserted through BOTH doors, because they are two entry points to one query +// and the doc states the promise as a property of the SET rather than of either +// request. RunReaderListReadyFlagRefusesAFilterItCannotCarry pins only that the +// flags are accepted or refused, never what the rows underneath them are; the +// audit leaf that pins the pinned and type exclusions at the storage surface +// (audit_dependencies_readiness.go) runs through the Factory, which hands back a +// bare storage.DoltStorage, so it never runs on the unit-of-work backend at all +// — and that backend composes the shared ready WHERE into a UNION query of its +// own (domain/db/ready_work_union.go), where a dropped conjunct is exactly this +// class. +func RunReaderReadySetOwnsItsStatusPinnedAndTemplateDecisions(t *testing.T, ctx context.Context, fixture ReaderFixture) { + t.Helper() + scope := readerLabel(fixture, "rdyset") + open := readerID(fixture, "rdyset", "open") + inProgress := readerID(fixture, "rdyset", "inprogress") + closed := readerID(fixture, "rdyset", "closed") + pinned := readerID(fixture, "rdyset", "pinned") + template := readerID(fixture, "rdyset", "template") + + inProgressIssue := readerIssue(inProgress, types.TypeTask, scope) + inProgressIssue.Status = types.StatusInProgress + closedIssue := readerIssue(closed, types.TypeTask, scope) + closedIssue.Status = types.StatusClosed + pinnedIssue := readerIssue(pinned, types.TypeTask, scope) + pinnedIssue.Pinned = true + templateIssue := readerIssue(template, types.TypeTask, scope) + templateIssue.IsTemplate = true + + seedReaderIssue(t, ctx, fixture, readerIssue(open, types.TypeTask, scope)) + seedReaderIssue(t, ctx, fixture, inProgressIssue) + seedReaderIssue(t, ctx, fixture, closedIssue) + seedReaderIssue(t, ctx, fixture, pinnedIssue) + seedReaderIssue(t, ctx, fixture, templateIssue) + + // The template is IN the answer: the ready query has no template predicate, + // and this type is not one it already excludes. + want := []string{open, template} + + page, err := fixture.Reader.Ready(ctx, publicops.ReadyRequest{Labels: []string{scope}}) + if err != nil { + t.Fatalf("Ready: %v", err) + } + assertReaderPageIDSet(t, "Ready over a scope holding an in_progress, a closed, a pinned and a template row", page, want) + + for _, test := range []struct { + name string + req publicops.ListRequest + }{ + {"List --ready", publicops.ListRequest{Labels: []string{scope}, ReadyFlag: true}}, + {"List --ready --templates", publicops.ListRequest{Labels: []string{scope}, ReadyFlag: true, IncludeTemplates: true}}, + {"List --ready --skip-labels", publicops.ListRequest{Labels: []string{scope}, ReadyFlag: true, SkipLabels: true}}, + } { + page, err := fixture.Reader.List(ctx, test.req) + if err != nil { + t.Fatalf("%s: %v", test.name, err) + } + assertReaderPageIDSet(t, test.name, page, want) + // SkipLabels is not carried onto the ready query, so the rows come back + // hydrated on every one of these requests, not just the first two. + assertReaderItemsCarryLabel(t, test.name, page, scope) + } +} + +// RunReaderListReadyFlagCarriesTheAssigneeAndPriorityFilters pins three more +// entries from the --ready arm's CARRIED list (reader.go:211-217): Assignee, +// NoAssignee and the exact Priority. +// +// RunReaderListReadyFlagAnswersTheBlockerAwareSet pins that list for Labels +// alone. The rest of it reaches the ready query through +// workapi.ReadyFilterFromIssueFilter (sort.go:49-84), the projection that stands +// between "these filters reach the ready query" and a silently WIDER answer, and +// nothing pins that projection field by field at any layer: the builder goldens +// stop at BuildListFilter's IssueFilter, one step before it. A field dropped +// there reproduces the defect class this file's own header narrates — a silently +// dropped filter looks exactly like a passing test — so the assertion is that +// the answer NARROWS, with a row present that the filter has to leave out. +// +// The three chosen are the three projection lines with distinct shapes: +// Assignee copies a pointer, NoAssignee changes NAME on the way across (it +// becomes WorkFilter.Unassigned), and Priority is the pointer that exists +// because P0 has been lost to a value-plus-flag pair once already. +func RunReaderListReadyFlagCarriesTheAssigneeAndPriorityFilters(t *testing.T, ctx context.Context, fixture ReaderFixture) { + t.Helper() + scope := readerLabel(fixture, "lsrdyf") + mine := readerID(fixture, "lsrdyf", "mine") + theirs := readerID(fixture, "lsrdyf", "theirs") + nobodys := readerID(fixture, "lsrdyf", "nobodys") + me := fixture.IssuePrefix + "-lsrdyf-me" + them := fixture.IssuePrefix + "-lsrdyf-them" + + mineIssue := readerIssue(mine, types.TypeTask, scope) + mineIssue.Assignee = me + mineIssue.Priority = 1 + theirsIssue := readerIssue(theirs, types.TypeTask, scope) + theirsIssue.Assignee = them + theirsIssue.Priority = 3 + nobodysIssue := readerIssue(nobodys, types.TypeTask, scope) + nobodysIssue.Priority = 3 + + seedReaderIssue(t, ctx, fixture, mineIssue) + seedReaderIssue(t, ctx, fixture, theirsIssue) + seedReaderIssue(t, ctx, fixture, nobodysIssue) + + // The unfiltered arm first: all three rows are ready, so every narrowing + // below is the filter's doing and not the scope's. + page, err := fixture.Reader.List(ctx, publicops.ListRequest{Labels: []string{scope}, ReadyFlag: true}) + if err != nil { + t.Fatalf("List --ready: %v", err) + } + assertReaderPageIDSet(t, "List --ready with nothing to narrow it", page, []string{mine, theirs, nobodys}) + + priority := 3 + for _, test := range []struct { + name string + req publicops.ListRequest + want []string + }{ + {"List --ready --assignee", publicops.ListRequest{Labels: []string{scope}, ReadyFlag: true, Assignee: me}, []string{mine}}, + {"List --ready --unassigned", publicops.ListRequest{Labels: []string{scope}, ReadyFlag: true, NoAssignee: true}, []string{nobodys}}, + {"List --ready --priority", publicops.ListRequest{Labels: []string{scope}, ReadyFlag: true, Priority: &priority}, []string{theirs, nobodys}}, + } { + page, err := fixture.Reader.List(ctx, test.req) + if err != nil { + t.Fatalf("%s: %v", test.name, err) + } + assertReaderPageIDSet(t, test.name, page, test.want) + } +} + +// RunReaderListStatusAcceptsACommaSeparatedORSet pins the plural half of +// ListRequest.Status (reader.go:117-123): "one name, OR a comma-separated OR +// set", and either way it REPLACES the default exclusions rather than fighting +// them. +// +// The singular branch is pinned by +// RunReaderListDefaultExclusionsAndTheirOverrides and the request-side parse by +// the builder's golden (list_filter_golden.json, status_multi). The residue is +// the seam: the two branches render DIFFERENT SQL — `status = ?` against a +// `status IN (...)` placeholder set (sqlbuild/filter.go:86-92, and the same +// twin structure at sqlbuild/ready.go:96-105) — and no case drives the plural +// one end to end against a database. A set of THREE is deliberate: two entries +// is the smallest IN clause and would pass against a renderer that emitted only +// the first and the last. +func RunReaderListStatusAcceptsACommaSeparatedORSet(t *testing.T, ctx context.Context, fixture ReaderFixture) { + t.Helper() + open := readerID(fixture, "lsstat", "open") + inProgress := readerID(fixture, "lsstat", "inprogress") + closed := readerID(fixture, "lsstat", "closed") + + inProgressIssue := readerIssue(inProgress, types.TypeTask, "") + inProgressIssue.Status = types.StatusInProgress + closedIssue := readerIssue(closed, types.TypeTask, "") + closedIssue.Status = types.StatusClosed + + seedReaderIssue(t, ctx, fixture, readerIssue(open, types.TypeTask, "")) + seedReaderIssue(t, ctx, fixture, inProgressIssue) + seedReaderIssue(t, ctx, fixture, closedIssue) + + scope := readerIDFilter(open, inProgress, closed) + for _, test := range []struct { + name string + status string + want []string + }{ + {"a two-status set reaches past the default closed exclusion", "closed,in_progress", []string{closed, inProgress}}, + {"a three-status set is the whole seeded scope", "open,in_progress,closed", []string{open, inProgress, closed}}, + {"whitespace around a member is the caller's, not the query's", " closed , open ", []string{closed, open}}, + } { + page, err := fixture.Reader.List(ctx, publicops.ListRequest{IDFilter: scope, Status: test.status}) + if err != nil { + t.Fatalf("List --status %q (%s): %v", test.status, test.name, err) + } + assertReaderPageIDSet(t, "List --status "+test.status, page, test.want) + } +} + +// readerIssue builds the seed every case starts from: an open, unassigned, +// unblocked task that qualifies for ready work. A case that needs it to fail one +// of those tests changes the field it means to test and nothing else. +func readerIssue(id string, issueType types.IssueType, label string) *types.Issue { + issue := &types.Issue{ + ID: id, + Title: id, + Status: types.StatusOpen, + Priority: 2, + IssueType: issueType, + } + if label != "" { + issue.Labels = []string{label} + } + return issue +} + +func seedReaderIssue(t *testing.T, ctx context.Context, fixture ReaderFixture, issue *types.Issue) { + t.Helper() + if err := fixture.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatalf("seed issue %s: %v", issue.ID, err) + } +} + +func seedReaderWisp(t *testing.T, ctx context.Context, fixture ReaderFixture, issue *types.Issue) { + t.Helper() + if err := fixture.CreateWisp(ctx, issue, "seed"); err != nil { + t.Fatalf("seed wisp %s: %v", issue.ID, err) + } +} + +// readerID namespaces one seeded id by the fixture's prefix and the case's own +// tag, so every case in a suite can share one database. +func readerID(fixture ReaderFixture, caseTag, name string) string { + return fixture.IssuePrefix + "-" + caseTag + "-" + name +} + +// readerLabel is how a ready case scopes its query: WorkFilter carries no id +// set, so the rows a ready assertion owns are the rows carrying its label. +func readerLabel(fixture ReaderFixture, caseTag string) string { + return fixture.IssuePrefix + "-scope-" + caseTag +} + +// readerIDFilter is how a list case scopes its query. The default listing +// answers with the whole workspace, and on the unit-of-work backend that +// workspace is shared by every case in the suite. +func readerIDFilter(ids ...string) string { + out := "" + for i, id := range ids { + if i > 0 { + out += "," + } + out += id + } + return out +} + +func readerLimit(n int) *int { return &n } + +func readerPageIDs(page publicops.IssuePage) []string { + out := make([]string, 0, len(page.Items)) + for _, item := range page.Items { + if item == nil || item.Issue == nil { + out = append(out, "") + continue + } + out = append(out, item.ID) + } + return out +} + +func readerDependencyIDs(rows []*types.IssueWithDependencyMetadata) []string { + out := make([]string, 0, len(rows)) + for _, row := range rows { + if row == nil { + out = append(out, "") + continue + } + out = append(out, row.ID) + } + return out +} + +// assertReaderPageNotNil is the half of the page shape every assertion owes: +// Items is never nil for a successful call (reader.go:310-315). +func assertReaderPageNotNil(t *testing.T, what string, page publicops.IssuePage) { + t.Helper() + if page.Items == nil { + t.Errorf("%s returned a nil Items; an empty page is an empty slice", what) + } +} + +// assertReaderPageIDs compares the page in ORDER. Use it only where the request +// named a display order or a sort policy; storage order is not a promise. +func assertReaderPageIDs(t *testing.T, what string, page publicops.IssuePage, want []string) { + t.Helper() + assertReaderPageNotNil(t, what, page) + got := readerPageIDs(page) + if len(want) == 0 && len(got) == 0 { + return + } + if !slices.Equal(got, want) { + t.Errorf("%s returned %v, want %v in that order", what, got, want) + } +} + +// assertReaderPageIDSet compares the page as a SET, for requests whose order the +// contract does not promise. +func assertReaderPageIDSet(t *testing.T, what string, page publicops.IssuePage, want []string) { + t.Helper() + assertReaderPageNotNil(t, what, page) + got := slices.Clone(readerPageIDs(page)) + wantSorted := slices.Clone(want) + slices.Sort(got) + slices.Sort(wantSorted) + if len(got) == 0 && len(wantSorted) == 0 { + return + } + if !slices.Equal(got, wantSorted) { + t.Errorf("%s returned %v, want exactly %v", what, got, wantSorted) + } +} + +// assertReaderPageIsPrefixOf compares a limited page against the order the same +// request answers with UNLIMITED. A limit bounds the page a caller receives, so +// the page it does receive is the front of that order — not the same number of +// rows taken from somewhere else in it. +func assertReaderPageIsPrefixOf(t *testing.T, what string, page publicops.IssuePage, order []string) { + t.Helper() + got := readerPageIDs(page) + if len(got) > len(order) { + t.Errorf("%s returned %v, which is longer than the unlimited answer %v", what, got, order) + return + } + if !slices.Equal(got, order[:len(got)]) { + t.Errorf("%s returned %v, want the first %d of the unlimited order %v", what, got, len(got), order) + } +} + +// assertReaderItemsCarryLabel is the hydration half of a page assertion: every +// row came back with the label the request scoped on. +func assertReaderItemsCarryLabel(t *testing.T, what string, page publicops.IssuePage, label string) { + t.Helper() + for _, item := range page.Items { + if item == nil || item.Issue == nil { + t.Errorf("%s returned a nil row", what) + continue + } + if !slices.Contains(item.Labels, label) { + t.Errorf("%s returned %s with labels %v, want it to carry %q: labels are hydrated on this arm either way", what, item.ID, item.Labels, label) + } + } +} + +func assertReaderCount(t *testing.T, what string, got *int64, want int64) { + t.Helper() + if got == nil { + t.Errorf("%s is nil; the detail view carries counts whether or not the rows were requested", what) + return + } + if *got != want { + t.Errorf("%s = %d, want %d", what, *got, want) + } +} + +// readerCopyReadyRequest and readerCopyListRequest deep-copy the reference +// fields the tripwire watches. A shallow copy would share the same backing +// arrays as the original and compare equal no matter what the implementation +// did to them. +func readerCopyReadyRequest(in publicops.ReadyRequest) publicops.ReadyRequest { + out := in + out.Labels = slices.Clone(in.Labels) + out.LabelsAny = slices.Clone(in.LabelsAny) + out.ExcludeLabels = slices.Clone(in.ExcludeLabels) + out.ExcludeTypes = slices.Clone(in.ExcludeTypes) + out.MetadataFields = readerCopyStringMap(in.MetadataFields) + if in.Limit != nil { + limit := *in.Limit + out.Limit = &limit + } + return out +} + +func readerCopyListRequest(in publicops.ListRequest) publicops.ListRequest { + out := in + out.Labels = slices.Clone(in.Labels) + out.LabelsAny = slices.Clone(in.LabelsAny) + out.ExcludeLabels = slices.Clone(in.ExcludeLabels) + out.ExcludeTypes = slices.Clone(in.ExcludeTypes) + out.MetadataFields = readerCopyStringMap(in.MetadataFields) + if in.Limit != nil { + limit := *in.Limit + out.Limit = &limit + } + return out +} + +func readerCopyStringMap(in map[string]string) map[string]string { + if in == nil { + return nil + } + out := make(map[string]string, len(in)) + for k, v := range in { + out[k] = v + } + return out +} diff --git a/backend/conformance/ready_claimer_contract.go b/backend/conformance/ready_claimer_contract.go new file mode 100644 index 000000000..7b5b0b468 --- /dev/null +++ b/backend/conformance/ready_claimer_contract.go @@ -0,0 +1,765 @@ +package conformance + +import ( + "context" + "errors" + "reflect" + "testing" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// This file holds the semantic contract every implementation of +// publicops.ReadyClaimer must satisfy. There are three accessors answering the +// role — the server-backed store, the embedded store, and the unit-of-work +// provider — but only two BODIES: the first two share +// internal/storage/issueops's ValidateClaimNextRequest and ExecuteClaimNext and +// differ in the transaction wrapper and the engine beneath it, while the +// unit-of-work +// implementation is separate code that reuses the same validator and the same +// workapi.BuildReadyFilter. Wiring all three is still worth it — the third run +// is what catches wrapper and engine divergence, which is where the claim's +// commit message diverged before the role existed — but a case passing three +// times is not three independent votes on the body. +// +// EVERY CASE IS SCOPED BY A LABEL, and that is load-bearing rather than +// stylistic. The ready front is a property of the whole database, not of an id +// prefix, so a claim seeded by one assertion is claimable by the next one. Each +// case therefore seeds rows carrying a label only it uses and asks its question +// through Filter.Labels, which is what lets the whole suite share one database +// — the unit-of-work wiring's one-provider-many-subtests shape depends on it, +// because a fresh provider there boots a real Dolt sql-server. +// +// EVERY CASE NAMES A SORT POLICY. ReadyRequest.Sort's empty value resolves to +// hybrid at the storage layer, which the leaf says no front door may rely on +// (issueops/reader.go:79-83); a contract that relied on it would be pinning the +// fallback instead of the order. +// +// NOT IN THIS CONTRACT: two racing claimers producing exactly one winner. That +// is a transaction property of the persistence boundary, not a promised result +// of the operation, and it belongs per-backend if it is written at all. + +// ReadyClaimerFixture supplies adapter-specific storage access for the +// ready-claim assertions. +type ReadyClaimerFixture struct { + // IssuePrefix namespaces the ids each assertion seeds, so several of them + // can share one database. + IssuePrefix string + Claimer publicops.ReadyClaimer + // Reader is the SAME backend's reader accessor. One case needs it: the + // claim's filter is Reader.Ready's filter in the leaf's words ("the same + // type, not a parallel one shaped like it"), and the only way to observe + // that end to end is to ask both surfaces the one question and compare. + Reader publicops.Reader + // CreateIssue seeds a durable issue in the issues plane. + CreateIssue func(context.Context, *types.Issue, string) error + // CreateWisp seeds an ephemeral issue in the wisps plane. It is a separate + // field rather than an Ephemeral flag on CreateIssue because the three + // adapters reach the two planes through different verbs. + CreateWisp func(context.Context, *types.Issue, string) error + // AddDependency seeds ONE edge. The claim hydrates the row it wins, so a + // case that wants to see a non-zero cardinality has to put one there. + AddDependency func(context.Context, *types.Dependency, string) error + QueryScalar func(context.Context, string, []any, ...any) error + // CountHistory reports the fixture's durable history length, for the "at + // most one entry per call, none when nothing was eligible" clause. Nil + // means the backend cannot observe history: the case whose whole subject is + // that clause then SKIPS with that reason rather than passing quietly, and + // the cases that merely carry a delta check alongside their own subject + // drop the check and keep their subject. It is non-nil on all three + // fixtures today. + CountHistory func(context.Context) (int, error) +} + +// RunReadyClaimerRejectsLimitOffsetAndEmptyActor pins the deterministic +// request-validation refusals — Limit set, Offset set, Actor empty +// (issueops/readyclaimer.go:15-23 and :7-8) — and the state clause that comes +// with them: "a validation failure leaves persistent state unchanged" +// (issueops/readyclaimer.go:56). +// +// Rejecting Limit and Offset is the visible half of a rule about the SCAN. A +// claim delivers one row however large the pool it walked, and the walk has to +// stay unbounded so a window that happens to be unclaimable does not report +// "nothing to claim" while other ready work waits. Accepting the two fields and +// quietly dropping them would be the same behavior with the promise hidden. +// An explicit zero limit is refused with the rest: Limit is a pointer so that +// "unset" and "explicitly unlimited" stay distinguishable +// (issueops/reader.go:85-100), and only the first of those is what this request +// permits. +// +// The claimable row seeded here is the point of the state half: each refusal +// runs against a front that WOULD have yielded it, so an implementation that +// validated after claiming fails on the row rather than on the error. +// +// WHAT IS DELIBERATELY NOT ASSERTED: the result value. The leaf says "Result +// values are unspecified when error is non-nil" (issueops/readyclaimer.go:55), +// so a case checking that the refused call also returned a zero result would be +// pinning today's implementations rather than the contract. The state +// assertions below are the part the contract does promise. +func RunReadyClaimerRejectsLimitOffsetAndEmptyActor(t *testing.T, ctx context.Context, fixture ReadyClaimerFixture) { + t.Helper() + label := fixture.IssuePrefix + "-rcreject" + candidate := fixture.IssuePrefix + "-rcreject-a" + seedReadyClaimerIssue(t, ctx, fixture, readyClaimerIssue(candidate, 1, label)) + + before := readyClaimerHistoryCount(t, ctx, fixture) + limit := 5 + unlimited := 0 + for _, refusal := range []struct { + name string + request publicops.ClaimNextRequest + }{ + {"limit", publicops.ClaimNextRequest{ + Actor: "claimer", + Filter: publicops.ReadyRequest{Labels: []string{label}, Sort: readyClaimerSort, Limit: &limit}, + }}, + {"explicitly unlimited limit", publicops.ClaimNextRequest{ + Actor: "claimer", + Filter: publicops.ReadyRequest{Labels: []string{label}, Sort: readyClaimerSort, Limit: &unlimited}, + }}, + {"offset", publicops.ClaimNextRequest{ + Actor: "claimer", + Filter: publicops.ReadyRequest{Labels: []string{label}, Sort: readyClaimerSort, Offset: 1}, + }}, + {"empty actor", publicops.ClaimNextRequest{ + Filter: publicops.ReadyRequest{Labels: []string{label}, Sort: readyClaimerSort}, + }}, + } { + if _, err := fixture.Claimer.ClaimNext(ctx, refusal.request); !errors.Is(err, storage.ErrValidation) { + t.Errorf("ClaimNext with %s: error = %v, want ErrValidation", refusal.name, err) + } + } + + // Unchanged means unchanged: the row a valid request would have won is + // still open and unassigned, and nothing was written to history. + assertReadyClaimerRowState(t, ctx, fixture, candidate, string(types.StatusOpen), "") + assertReadyClaimerHistoryDelta(t, ctx, fixture, before, 0, "four refused requests") +} + +// RunReadyClaimerEmptyFrontIsNormal pins the outcome most likely to diverge: a +// drained queue answers with a nil Claimed and a NIL ERROR +// (issueops/readyclaimer.go:32-37). An empty front is the steady state of a +// polling agent, and one that had to classify an error to discover it would be +// pattern-matching prose. Nothing is written and no history entry is recorded +// (issueops/readyclaimer.go:35-36, :71-72), so an implementation that commits an +// empty transaction fails here too. +// +// The decoy is what makes the case about the FRONT rather than about an empty +// database: a ready, claimable row exists throughout, it simply does not match +// the filter, and it must still be sitting there afterwards. +func RunReadyClaimerEmptyFrontIsNormal(t *testing.T, ctx context.Context, fixture ReadyClaimerFixture) { + t.Helper() + label := fixture.IssuePrefix + "-rcempty" + decoy := fixture.IssuePrefix + "-rcempty-decoy" + seedReadyClaimerIssue(t, ctx, fixture, readyClaimerIssue(decoy, 0, label+"-other")) + + before := readyClaimerHistoryCount(t, ctx, fixture) + result, err := fixture.Claimer.ClaimNext(ctx, publicops.ClaimNextRequest{ + Actor: "claimer", + Filter: publicops.ReadyRequest{Labels: []string{label}, Sort: readyClaimerSort}, + }) + if err != nil { + t.Fatalf("ClaimNext against an empty ready front: error = %v, want nil — an empty front is a normal outcome, not an error", err) + } + if result.Claimed != nil { + t.Fatalf("ClaimNext against an empty ready front claimed %s, want nil", result.Claimed.ID) + } + + assertReadyClaimerRowState(t, ctx, fixture, decoy, string(types.StatusOpen), "") + assertReadyClaimerHistoryDelta(t, ctx, fixture, before, 0, "a claim that found nothing") +} + +// RunReadyClaimerClaimsTheFrontRowAndReturnsThePostClaimState pins the winning +// path: the first row in the requested order moves to in-progress with the +// assignee set to Actor, and the RETURNED row is the post-claim row rather than +// the pre-claim one (issueops/readyclaimer.go:28-31). +// +// What it does NOT try to prove is the transactional simultaneity itself. That +// selection, the compare-and-set and the hydration share one transaction is not +// black-box observable; what is observable is that the snapshot handed back +// equals the state left in the database, and that the cardinalities are +// populated from real edges rather than zeroed. Both halves of that are here, +// and the seeded edges are why the count assertion can be an equality instead of +// a "not obviously empty". +func RunReadyClaimerClaimsTheFrontRowAndReturnsThePostClaimState(t *testing.T, ctx context.Context, fixture ReadyClaimerFixture) { + t.Helper() + label := fixture.IssuePrefix + "-rcwin" + winner := fixture.IssuePrefix + "-rcwin-a" + runnerUp := fixture.IssuePrefix + "-rcwin-b" + // A CLOSED blocker: it gives the winner a dependency to count without + // taking it off the ready front. + blocker := fixture.IssuePrefix + "-rcwin-blocker" + dependent := fixture.IssuePrefix + "-rcwin-dependent" + + seedReadyClaimerIssue(t, ctx, fixture, readyClaimerIssue(winner, 0, label)) + seedReadyClaimerIssue(t, ctx, fixture, readyClaimerIssue(runnerUp, 1, label)) + closed := readyClaimerIssue(blocker, 1, label+"-blocker") + closed.Status = types.StatusClosed + seedReadyClaimerIssue(t, ctx, fixture, closed) + seedReadyClaimerIssue(t, ctx, fixture, readyClaimerIssue(dependent, 1, label+"-dependent")) + seedReadyClaimerEdge(t, ctx, fixture, winner, blocker) + seedReadyClaimerEdge(t, ctx, fixture, dependent, winner) + + result, err := fixture.Claimer.ClaimNext(ctx, publicops.ClaimNextRequest{ + Actor: "claimer", + Filter: publicops.ReadyRequest{Labels: []string{label}, Sort: readyClaimerSort}, + }) + if err != nil { + t.Fatalf("ClaimNext against a seeded ready front: %v", err) + } + if result.Claimed == nil { + t.Fatal("ClaimNext returned no row against a front holding two claimable issues") + } + if result.Claimed.ID != winner { + t.Fatalf("claimed %s, want %s — the first row of the requested order", result.Claimed.ID, winner) + } + if result.Claimed.Issue == nil { + t.Fatal("claimed row carries a nil Issue") + } + if result.Claimed.Issue.Status != types.StatusInProgress { + t.Errorf("returned status = %q, want %q", result.Claimed.Issue.Status, types.StatusInProgress) + } + if result.Claimed.Issue.Assignee != "claimer" { + t.Errorf("returned assignee = %q, want %q", result.Claimed.Issue.Assignee, "claimer") + } + if result.Claimed.DependencyCount != 1 { + t.Errorf("returned DependencyCount = %d, want 1 — the claim hydrates the row it won", result.Claimed.DependencyCount) + } + if result.Claimed.DependentCount != 1 { + t.Errorf("returned DependentCount = %d, want 1 — the claim hydrates the row it won", result.Claimed.DependentCount) + } + + // The returned snapshot IS the stored state, not a projection of the row + // as it was before the compare-and-set. + assertReadyClaimerRowState(t, ctx, fixture, + winner, string(result.Claimed.Issue.Status), result.Claimed.Issue.Assignee) + assertReadyClaimerRowState(t, ctx, fixture, winner, string(types.StatusInProgress), "claimer") + // One row is won per call, so the runner-up is untouched. + assertReadyClaimerRowState(t, ctx, fixture, runnerUp, string(types.StatusOpen), "") +} + +// RunReadyClaimerClaimsAnEphemeralRowTheFilterAdmits pins the ephemeral half of +// the ready set: "a filter that sets IncludeEphemeral pulls [ephemeral rows] in +// for the claim exactly as it does for the listing: such a row IS claimable" +// (issueops/readyclaimer.go:63-76). The wisp seeded here is ready by every other +// measure and the request opts ephemeral rows in, so the listing offers it — and +// the claim takes it. +// +// The case asserts through Reader.Ready first, and fails there rather than +// silently degenerating, because "the claim took the row the listing offered" is +// only meaningful when the listing offered one. A seed that never reached the +// front would make this a second copy of the winning-path case. +// +// Three things beyond "it returned a row" are asserted, because each is a +// separate way an implementation could plausibly interpret the clause and get it +// wrong: +// - the EPHEMERAL row moved. The claim lands on the row that was offered, not +// on a durable copy of it, so the wisps row carries the actor. +// - no durable row appeared. Claiming an ephemeral row must not promote it. +// - durable history did not move. Ephemeral rows are not versioned, so the +// leaf's "a claim that wins an EPHEMERAL row records none either" is the +// visible consequence a `bd dolt log` reader would otherwise be surprised +// by. This is the ONE ready-claim outcome that mutates state without a +// history entry, which is exactly why it is pinned rather than assumed. +// +// bd-yby99.4 adjudicated this. The case previously asserted the opposite — that +// the claim declines a ready wisp — on the strength of a leaf sentence reading +// "the ready set is the issues plane". All three backends claimed the wisp +// anyway; the owner ruled the implementations right and the sentence wrong, so +// the sentence and this case inverted together. +func RunReadyClaimerClaimsAnEphemeralRowTheFilterAdmits(t *testing.T, ctx context.Context, fixture ReadyClaimerFixture) { + t.Helper() + label := fixture.IssuePrefix + "-rcwisp" + wisp := fixture.IssuePrefix + "-rcwisp-w" + seedReadyClaimerWisp(t, ctx, fixture, readyClaimerIssue(wisp, 0, label)) + + request := publicops.ReadyRequest{ + Labels: []string{label}, + Sort: readyClaimerSort, + IncludeEphemeral: true, + } + page, err := fixture.Reader.Ready(ctx, request) + if err != nil { + t.Fatalf("Reader.Ready over the seeded wisp: %v", err) + } + if !readyClaimerPageHas(page, wisp) { + t.Fatalf("Reader.Ready did not offer the seeded ready wisp %s (page: %v); "+ + "the case cannot say the claim took a row the front never held", wisp, readyClaimerPageIDs(page)) + } + + before := readyClaimerHistoryCount(t, ctx, fixture) + result, err := fixture.Claimer.ClaimNext(ctx, publicops.ClaimNextRequest{Actor: "claimer", Filter: request}) + if err != nil { + t.Fatalf("ClaimNext over a front holding one ready wisp: error = %v, want nil", err) + } + if result.Claimed == nil { + t.Fatal("ClaimNext returned no row against a front holding one ready wisp that IncludeEphemeral admitted") + } + if result.Claimed.ID != wisp { + t.Fatalf("claimed %s, want the ephemeral row %s the filter admitted", result.Claimed.ID, wisp) + } + if result.Claimed.Issue == nil { + t.Fatal("claimed row carries a nil Issue") + } + if result.Claimed.Issue.Status != types.StatusInProgress { + t.Errorf("returned status = %q, want %q", result.Claimed.Issue.Status, types.StatusInProgress) + } + if result.Claimed.Issue.Assignee != "claimer" { + t.Errorf("returned assignee = %q, want %q", result.Claimed.Issue.Assignee, "claimer") + } + + assertReadyClaimerWispState(t, ctx, fixture, wisp, string(types.StatusInProgress), "claimer") + assertReadyClaimerRowAbsent(t, ctx, fixture, "issues", wisp) + assertReadyClaimerHistoryDelta(t, ctx, fixture, before, 0, "a claim that won an ephemeral row") +} + +// RunReadyClaimerLeavesEphemeralRowsOutOfTheDefaultReadySet pins the DEFAULT +// half of the same clause the case above pins the opt-in half of: "Ephemeral +// rows are outside [the ready set] by default, and a filter that sets +// IncludeEphemeral pulls them in for the claim exactly as it does for the +// listing" (issueops/readyclaimer.go:65-67). A request that never mentions +// ephemeral rows never claims one. +// +// The two halves fail independently and only one of them was pinned anywhere. +// The reader contract pins the default gate for the LISTING +// (RunReaderReadyDeferredAndEphemeralGates), not for the claim; and after +// bd-yby99.4 inverted the opt-in case, an implementation that overcorrected +// into always admitting wisps would hand an agent work `bd ready` never offered +// it — the failure that clause exists to prevent — with nothing failing. +// +// The listing probe is what keeps the nil honest. The seeded wisp is ready by +// every other measure, and the ONLY difference between the request that offers +// it and the request that must not claim it is IncludeEphemeral, so a nil +// Claimed here cannot be a mis-seeded row or a label that matches nothing. +func RunReadyClaimerLeavesEphemeralRowsOutOfTheDefaultReadySet(t *testing.T, ctx context.Context, fixture ReadyClaimerFixture) { + t.Helper() + label := fixture.IssuePrefix + "-rcdefault" + wisp := fixture.IssuePrefix + "-rcdefault-w" + seedReadyClaimerWisp(t, ctx, fixture, readyClaimerIssue(wisp, 0, label)) + + admitted := publicops.ReadyRequest{Labels: []string{label}, Sort: readyClaimerSort, IncludeEphemeral: true} + page, err := fixture.Reader.Ready(ctx, admitted) + if err != nil { + t.Fatalf("Reader.Ready over the seeded wisp with IncludeEphemeral: %v", err) + } + if !readyClaimerPageHas(page, wisp) { + t.Fatalf("Reader.Ready did not offer the seeded ready wisp %s even with IncludeEphemeral (page: %v); "+ + "a nil claim below would then say nothing about the default gate", wisp, readyClaimerPageIDs(page)) + } + + before := readyClaimerHistoryCount(t, ctx, fixture) + result, err := fixture.Claimer.ClaimNext(ctx, publicops.ClaimNextRequest{ + Actor: "claimer", + Filter: publicops.ReadyRequest{Labels: []string{label}, Sort: readyClaimerSort}, + }) + if err != nil { + t.Fatalf("ClaimNext with IncludeEphemeral unset: error = %v, want nil — a front holding only ephemeral rows is an EMPTY front, not a failure", err) + } + if result.Claimed != nil { + t.Fatalf("ClaimNext claimed %s with IncludeEphemeral unset; ephemeral rows are outside the default ready set, "+ + "so this hands an agent work the listing never offered it", result.Claimed.ID) + } + + assertReadyClaimerWispState(t, ctx, fixture, wisp, string(types.StatusOpen), "") + assertReadyClaimerHistoryDelta(t, ctx, fixture, before, 0, "a default claim over a front holding one ephemeral row") +} + +// RunReadyClaimerLeasesADurableWinButNotAnEphemeralOne pins both halves of the +// lease clause, in one case, because each half is what makes the other mean +// something. +// +// THE AFFIRMATIVE: "A DURABLE win grants EXACTLY ONE LEASE on the row it won" +// (issueops/readyclaimer.go:78-82). THE NEGATIVE: "An ephemeral win carries NO +// LEASE, which is the sharper of the two consequences because it has no expiry +// to wait out" (readyclaimer.go:84-90). +// +// Asserting the zero alone would be half vacuous: a backend whose leases table +// this fixture cannot reach reports zero for the wisp too, and a backend that +// stopped leasing durable claims entirely would pass. Asserting the one alone +// would say nothing about the recovery story the leaf tells a caller it does +// NOT get for a wisp. Together the pair says the query can see lease rows AND +// that the plane is what decides whether there is one. +// +// The clause's other half — heartbeats refuse an ephemeral row, lease-expiry +// recovery only walks leased durable ones — is a promise about OTHER verbs and +// is not observable through ClaimNext; the lease row is the part this seam can +// see, and it is what makes those two true. +// +// (This was a spec gap, bd-yby99.13: the durable check was a probe rather +// than an assertion; the owner ratified the affirmative and the probe became +// the assertion it already looked like.) +func RunReadyClaimerLeasesADurableWinButNotAnEphemeralOne(t *testing.T, ctx context.Context, fixture ReadyClaimerFixture) { + t.Helper() + ephemeralLabel := fixture.IssuePrefix + "-rclease-eph" + durableLabel := fixture.IssuePrefix + "-rclease-dur" + wisp := fixture.IssuePrefix + "-rclease-w" + durable := fixture.IssuePrefix + "-rclease-d" + seedReadyClaimerWisp(t, ctx, fixture, readyClaimerIssue(wisp, 0, ephemeralLabel)) + seedReadyClaimerIssue(t, ctx, fixture, readyClaimerIssue(durable, 0, durableLabel)) + + won := readyClaimerWin(t, ctx, fixture, publicops.ReadyRequest{ + Labels: []string{ephemeralLabel}, Sort: readyClaimerSort, IncludeEphemeral: true, + }) + if won != wisp { + t.Fatalf("claimed %s, want the ephemeral row %s", won, wisp) + } + assertReadyClaimerWispState(t, ctx, fixture, wisp, string(types.StatusInProgress), "claimer") + if leases := readyClaimerLeaseCount(t, ctx, fixture, wisp); leases != 0 { + t.Errorf("the ephemeral win left %d leases row(s) for %s, want 0 — a leased wisp joins the lease-expiry "+ + "recovery walk, which is the recovery story the leaf tells a caller it does NOT get", leases, wisp) + } + + won = readyClaimerWin(t, ctx, fixture, publicops.ReadyRequest{Labels: []string{durableLabel}, Sort: readyClaimerSort}) + if won != durable { + t.Fatalf("claimed %s, want the durable row %s", won, durable) + } + if leases := readyClaimerLeaseCount(t, ctx, fixture, durable); leases != 1 { + t.Fatalf("the durable win left %d leases row(s) for %s, want exactly 1 — a durable claim with no lease is work "+ + "nothing can take back, because heartbeats have no handle to extend and lease-expiry recovery never sees it", + leases, durable) + } +} + +// RunReadyClaimerAnswersTheQuestionReaderReadyLists pins the filter's +// provenance (issueops/readyclaimer.go:9-14): the claim's predicate is the +// listing's predicate, because the request type IS Reader.Ready's request type +// and there is one builder behind both. Asserting it costs one shared seed and +// it encodes the rule that motivates the whole clause — a claim must not hand an +// agent work the listing never offered it. +// +// The high-priority outsider is the half that makes the agreement mean +// something. It would win an unfiltered claim, so a request whose filter was +// dropped or widened anywhere between the two surfaces takes it instead, and +// this case says so. +func RunReadyClaimerAnswersTheQuestionReaderReadyLists(t *testing.T, ctx context.Context, fixture ReadyClaimerFixture) { + t.Helper() + label := fixture.IssuePrefix + "-rcagree" + selected := fixture.IssuePrefix + "-rcagree-a" + wrongPriority := fixture.IssuePrefix + "-rcagree-b" + outsider := fixture.IssuePrefix + "-rcagree-outsider" + seedReadyClaimerIssue(t, ctx, fixture, readyClaimerIssue(selected, 1, label)) + seedReadyClaimerIssue(t, ctx, fixture, readyClaimerIssue(wrongPriority, 2, label)) + seedReadyClaimerIssue(t, ctx, fixture, readyClaimerIssue(outsider, 0, label+"-outsider")) + + priority := 1 + request := publicops.ReadyRequest{Labels: []string{label}, Priority: &priority, Sort: readyClaimerSort} + page, err := fixture.Reader.Ready(ctx, request) + if err != nil { + t.Fatalf("Reader.Ready: %v", err) + } + if len(page.Items) == 0 { + t.Fatal("Reader.Ready listed nothing for a filter matching a seeded ready issue") + } + listedFirst := page.Items[0].ID + + result, err := fixture.Claimer.ClaimNext(ctx, publicops.ClaimNextRequest{Actor: "claimer", Filter: request}) + if err != nil { + t.Fatalf("ClaimNext: %v", err) + } + if result.Claimed == nil { + t.Fatalf("ClaimNext returned nothing for the filter Reader.Ready answered with %v", readyClaimerPageIDs(page)) + } + if result.Claimed.ID != listedFirst { + t.Errorf("claimed %s but Reader.Ready listed %s first for the same request; "+ + "the claim's predicate and the listing's predicate must be one predicate", result.Claimed.ID, listedFirst) + } + if result.Claimed.ID != selected { + t.Errorf("claimed %s, want %s", result.Claimed.ID, selected) + } + assertReadyClaimerRowState(t, ctx, fixture, outsider, string(types.StatusOpen), "") +} + +// RunReadyClaimerSkipsIneligibleFrontRows makes the unbounded-scan rationale +// (issueops/readyclaimer.go:17-22) observable without a race. The top of the +// ready order is occupied by rows this actor cannot take — they are already +// assigned — and the claim must walk past them to the first row it CAN take +// rather than reporting an empty front. +// +// This is also where the claim's eligibility is narrower than the listing's: +// `bd ready` offers assigned open work, and the claim does not take it. Both +// halves are asserted, so a change that made the claim steal an assigned row +// fails here rather than in production. +func RunReadyClaimerSkipsIneligibleFrontRows(t *testing.T, ctx context.Context, fixture ReadyClaimerFixture) { + t.Helper() + label := fixture.IssuePrefix + "-rcskip" + takenFirst := fixture.IssuePrefix + "-rcskip-a" + takenSecond := fixture.IssuePrefix + "-rcskip-b" + eligible := fixture.IssuePrefix + "-rcskip-c" + + first := readyClaimerIssue(takenFirst, 0, label) + first.Assignee = "other-agent" + second := readyClaimerIssue(takenSecond, 1, label) + second.Assignee = "other-agent" + seedReadyClaimerIssue(t, ctx, fixture, first) + seedReadyClaimerIssue(t, ctx, fixture, second) + seedReadyClaimerIssue(t, ctx, fixture, readyClaimerIssue(eligible, 2, label)) + + request := publicops.ReadyRequest{Labels: []string{label}, Sort: readyClaimerSort} + page, err := fixture.Reader.Ready(ctx, request) + if err != nil { + t.Fatalf("Reader.Ready: %v", err) + } + if !readyClaimerPageHas(page, takenFirst) { + t.Fatalf("Reader.Ready did not offer the assigned row %s (page: %v); "+ + "the case needs an ineligible row AT THE FRONT to have anything to skip", takenFirst, readyClaimerPageIDs(page)) + } + + result, err := fixture.Claimer.ClaimNext(ctx, publicops.ClaimNextRequest{Actor: "claimer", Filter: request}) + if err != nil { + t.Fatalf("ClaimNext over a front whose first rows are ineligible: %v", err) + } + if result.Claimed == nil { + t.Fatal("ClaimNext returned nothing while an eligible row sat behind two ineligible ones") + } + if result.Claimed.ID != eligible { + t.Fatalf("claimed %s, want %s — the first ELIGIBLE row", result.Claimed.ID, eligible) + } + assertReadyClaimerRowState(t, ctx, fixture, takenFirst, string(types.StatusOpen), "other-agent") + assertReadyClaimerRowState(t, ctx, fixture, takenSecond, string(types.StatusOpen), "other-agent") +} + +// RunReadyClaimerRecordsOneHistoryEntryForAWin pins the counting half of "at +// most one durable history entry [per call], and none at all when nothing was +// eligible" (issueops/readyclaimer.go:71-76). The empty-front half lives in +// RunReadyClaimerEmptyFrontIsNormal, where the call that records nothing is the +// subject; the ephemeral half — a win that also records nothing, because +// ephemeral rows are not versioned — lives in +// RunReadyClaimerClaimsAnEphemeralRowTheFilterAdmits; here the subject is the +// DURABLE win, which records exactly one. +// +// It counts a DELTA around the operation rather than reading the top of the +// log: two commits made inside the same second tie on date, and their relative +// order is not something to rely on. What the entry SAYS — the commit-message +// spelling — is deliberately not here; that is single-sourced in +// internal/storage/issueops and pinning it three times would be duplication. +func RunReadyClaimerRecordsOneHistoryEntryForAWin(t *testing.T, ctx context.Context, fixture ReadyClaimerFixture) { + t.Helper() + if fixture.CountHistory == nil { + t.Skip("fixture cannot observe durable history, so the entry-per-call clause is unobservable on this backend") + } + label := fixture.IssuePrefix + "-rchist" + winner := fixture.IssuePrefix + "-rchist-a" + seedReadyClaimerIssue(t, ctx, fixture, readyClaimerIssue(winner, 0, label)) + + before := readyClaimerHistoryCount(t, ctx, fixture) + result, err := fixture.Claimer.ClaimNext(ctx, publicops.ClaimNextRequest{ + Actor: "claimer", + Filter: publicops.ReadyRequest{Labels: []string{label}, Sort: readyClaimerSort}, + }) + if err != nil { + t.Fatalf("ClaimNext: %v", err) + } + if result.Claimed == nil { + t.Fatal("ClaimNext returned nothing against a front holding one claimable issue") + } + assertReadyClaimerHistoryDelta(t, ctx, fixture, before, 1, "a winning claim") +} + +// RunReadyClaimerDoesNotMutateTheCallerRequest is the request-snapshot +// tripwire the leaf promises in so many words: "Implementations never mutate +// caller-owned request values, snapshot the request at method entry, and apply +// validation and normalization only to attempt-local clones" +// (issueops/readyclaimer.go:52-56). +// +// The request is passed by value, so only its REFERENCE members can carry a +// mutation back to the caller — the four label slices, ExcludeTypes, +// MetadataFields and the Priority pointer. Every one of them is populated here +// with a value normalization would want to touch, and the comparison is against +// a second copy built by the same function, so an in-place trim, dedupe, sort, +// alias expansion or write-through fails. +// +// The filter matches nothing on purpose. The promise is about the request, not +// about the outcome, and an empty front is the one outcome that is guaranteed +// not to depend on what the rest of the suite has seeded. +func RunReadyClaimerDoesNotMutateTheCallerRequest(t *testing.T, ctx context.Context, fixture ReadyClaimerFixture) { + t.Helper() + build := func() publicops.ClaimNextRequest { + priority := 2 + return publicops.ClaimNextRequest{ + Actor: "claimer", + Filter: publicops.ReadyRequest{ + IssueType: " Task ", + Labels: []string{fixture.IssuePrefix + "-rcsnap ", fixture.IssuePrefix + "-rcsnap "}, + LabelsAny: []string{" " + fixture.IssuePrefix + "-rcsnap-any"}, + ExcludeLabels: []string{fixture.IssuePrefix + "-rcsnap-not "}, + ExcludeTypes: []string{"mr,epic", " chore "}, + MetadataFields: map[string]string{"team": "conformance"}, + HasMetadataKey: "team", + Priority: &priority, + Sort: readyClaimerSort, + }, + } + } + request := build() + want := build() + + if _, err := fixture.Claimer.ClaimNext(ctx, request); err != nil { + t.Fatalf("ClaimNext with a fully populated filter: %v", err) + } + if !reflect.DeepEqual(request, want) { + t.Errorf("ClaimNext mutated the caller's request:\n got %+v\nwant %+v", request, want) + } +} + +// readyClaimerSort is the order every case names. It is the policy whose SQL is +// a plain "ORDER BY priority, created_at, id", so a seed with distinct +// priorities has one unambiguous front row — hybrid's recency bucket would make +// the winner depend on when the fixture was seeded. +const readyClaimerSort = "priority" + +func readyClaimerIssue(id string, priority int, labels ...string) *types.Issue { + return &types.Issue{ + ID: id, + Title: id, + Status: types.StatusOpen, + Priority: priority, + IssueType: types.TypeTask, + Labels: labels, + } +} + +func seedReadyClaimerIssue(t *testing.T, ctx context.Context, fixture ReadyClaimerFixture, issue *types.Issue) { + t.Helper() + if err := fixture.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatalf("seed issue %s: %v", issue.ID, err) + } +} + +func seedReadyClaimerWisp(t *testing.T, ctx context.Context, fixture ReadyClaimerFixture, issue *types.Issue) { + t.Helper() + issue.Ephemeral = true + if err := fixture.CreateWisp(ctx, issue, "seed"); err != nil { + t.Fatalf("seed wisp %s: %v", issue.ID, err) + } +} + +func seedReadyClaimerEdge(t *testing.T, ctx context.Context, fixture ReadyClaimerFixture, issueID, dependsOnID string) { + t.Helper() + if err := fixture.AddDependency(ctx, &types.Dependency{ + IssueID: issueID, DependsOnID: dependsOnID, Type: types.DepBlocks, + }, "seed"); err != nil { + t.Fatalf("seed edge %s -> %s: %v", issueID, dependsOnID, err) + } +} + +// assertReadyClaimerRowState reads the durable row's status and assignee back +// out of the database. The assignee comes through COALESCE because an unclaimed +// row's column may be NULL or empty depending on how it was seeded, and the +// three fixtures' scan paths do not agree on what a NULL means. +func assertReadyClaimerRowState(t *testing.T, ctx context.Context, fixture ReadyClaimerFixture, id, wantStatus, wantAssignee string) { + t.Helper() + assertReadyClaimerPlaneRowState(t, ctx, fixture, "issues", id, wantStatus, wantAssignee) +} + +func assertReadyClaimerWispState(t *testing.T, ctx context.Context, fixture ReadyClaimerFixture, id, wantStatus, wantAssignee string) { + t.Helper() + assertReadyClaimerPlaneRowState(t, ctx, fixture, "wisps", id, wantStatus, wantAssignee) +} + +// assertReadyClaimerRowAbsent checks that a plane holds no row for id. It +// counts rather than scanning one, so "absent" and "present but unreadable" +// cannot be confused: a failed scan would be a fixture error, an empty count is +// the answer. +func assertReadyClaimerRowAbsent(t *testing.T, ctx context.Context, fixture ReadyClaimerFixture, table, id string) { + t.Helper() + var rows int + //nolint:gosec // G201: table is one of the contract's two hardcoded names. + query := "SELECT COUNT(*) FROM " + table + " WHERE id = ?" + if err := fixture.QueryScalar(ctx, query, []any{id}, &rows); err != nil { + t.Fatalf("count %s rows for %s: %v", table, id, err) + } + if rows != 0 { + t.Errorf("%s holds %d row(s) for %s, want 0", table, rows, id) + } +} + +func assertReadyClaimerPlaneRowState(t *testing.T, ctx context.Context, fixture ReadyClaimerFixture, table, id, wantStatus, wantAssignee string) { + t.Helper() + var status, assignee string + //nolint:gosec // G201: table is one of the contract's two hardcoded names. + query := "SELECT status, COALESCE(assignee, '') FROM " + table + " WHERE id = ?" + if err := fixture.QueryScalar(ctx, query, []any{id}, &status, &assignee); err != nil { + t.Fatalf("read %s row %s: %v", table, id, err) + } + if status != wantStatus || assignee != wantAssignee { + t.Errorf("%s row %s = (status %q, assignee %q), want (%q, %q)", + table, id, status, assignee, wantStatus, wantAssignee) + } +} + +// readyClaimerWin runs one claim that is expected to take a row and reports the +// id it won. A nil Claimed is fatal here rather than a returned empty string, +// because every caller of this helper is asserting something ABOUT the win. +func readyClaimerWin(t *testing.T, ctx context.Context, fixture ReadyClaimerFixture, filter publicops.ReadyRequest) string { + t.Helper() + result, err := fixture.Claimer.ClaimNext(ctx, publicops.ClaimNextRequest{Actor: "claimer", Filter: filter}) + if err != nil { + t.Fatalf("ClaimNext(labels=%v, includeEphemeral=%v): %v", filter.Labels, filter.IncludeEphemeral, err) + } + if result.Claimed == nil { + t.Fatalf("ClaimNext(labels=%v, includeEphemeral=%v) returned no row against a front seeded to hold one", + filter.Labels, filter.IncludeEphemeral) + } + return result.Claimed.ID +} + +// readyClaimerLeaseCount reports how many lease rows the ephemeral leases table +// holds for id. The table is a plain SQL table on every backend +// (internal/storage/schema/cli_migrations.go:108-115), reached here through the +// same QueryScalar the row-state assertions use. +func readyClaimerLeaseCount(t *testing.T, ctx context.Context, fixture ReadyClaimerFixture, id string) int { + t.Helper() + var rows int + if err := fixture.QueryScalar(ctx, "SELECT COUNT(*) FROM leases WHERE issue_id = ?", []any{id}, &rows); err != nil { + t.Fatalf("count leases for %s: %v", id, err) + } + return rows +} + +func readyClaimerHistoryCount(t *testing.T, ctx context.Context, fixture ReadyClaimerFixture) int { + t.Helper() + if fixture.CountHistory == nil { + return -1 + } + entries, err := fixture.CountHistory(ctx) + if err != nil { + t.Fatalf("count history: %v", err) + } + return entries +} + +// assertReadyClaimerHistoryDelta checks how far the durable history moved. +// A fixture that cannot observe history reports -1 from +// readyClaimerHistoryCount and the check is skipped there rather than passing +// on an arithmetic accident. +func assertReadyClaimerHistoryDelta(t *testing.T, ctx context.Context, fixture ReadyClaimerFixture, before, want int, subject string) { + t.Helper() + if before < 0 { + return + } + after := readyClaimerHistoryCount(t, ctx, fixture) + if after-before != want { + t.Errorf("history entries went %d -> %d across %s, want exactly %d more", before, after, subject, want) + } +} + +func readyClaimerPageHas(page publicops.IssuePage, id string) bool { + for _, item := range page.Items { + if item != nil && item.ID == id { + return true + } + } + return false +} + +func readyClaimerPageIDs(page publicops.IssuePage) []string { + ids := make([]string, 0, len(page.Items)) + for _, item := range page.Items { + if item != nil { + ids = append(ids, item.ID) + } + } + return ids +} diff --git a/backend/conformance/relations_contract.go b/backend/conformance/relations_contract.go new file mode 100644 index 000000000..75b620d8b --- /dev/null +++ b/backend/conformance/relations_contract.go @@ -0,0 +1,714 @@ +package conformance + +import ( + "context" + "errors" + "reflect" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// This file holds the neighbor-query contract every implementation of +// publicops.Relations must satisfy. There are three accessors — the direct +// store, the embedded store and the unit-of-work provider — but only TWO +// bodies: dolt and embeddeddolt both call +// storageissueops.ValidateRelatedRequest + ExecuteRelated and differ only in +// the transaction wrapper and the engine underneath, while uow reaches the +// same two queries through its dependency use case. Wiring the contract three +// times is still worth it — the third run catches wrapper and engine +// divergence, which is what the embedded suite has historically caught — but +// it is not three independent votes on the shared body. +// +// WHAT IT PINS is what the leaf doc promises and nothing else: the order, the +// direction split, ErrNotFound-versus-an-empty-page, the wisp plane, the open +// type vocabulary, and the request snapshot. Each case is written to +// issueops/relations.go's stated +// promise rather than to any implementation's current behavior; where an +// implementation disagrees, the case still asserts the doc and the losing +// backend's WIRING file parks it (see bd-yby99). +// +// ONE THING DELIBERATELY ABSENT, recorded here so it reads as a decision +// rather than as an omission: +// +// The EDGE-TYPE TIEBREAK half of the order (relations.go:91-92, "with the edge +// type breaking a tie") is not pinned here because the write path makes the +// state unreachable: two rows for the same (source, target) pair are refused +// per dependency table with a DependencyTypeConflictError +// (internal/storage/issueops/dependencies.go:258-264, confirmed by running it +// on the dolt fixture), and the two tables are source-routed, so one anchor's +// answer can never carry the same neighbor id twice. The tiebreak is defensive +// code in the shared FinishRelatedPage and is pinned where it is reachable, as +// a unit test of that function +// (internal/storage/issueops/edge_role_requests_test.go:293-322). What this +// contract pins instead is the half a database CAN produce: ascending neighbor +// id across BOTH dependency planes, which is the artifact the doc names. +// +// TWO CLAUSES HERE WERE SILENCES IN THE LEAF (bd-yby99.14 and bd-yby99.15) +// until the owner ruled on them. Both were measured on all three fixtures +// before a sentence was written, both were adopted into the leaf, and both are +// now pinned — by RunRelationsLeavesAnExternalTargetOutOfTheAnswer and +// RunRelationsResolvesTheAnchorIDExactly respectively. + +// RelationsFixture supplies adapter-specific storage access for the +// neighbor-query assertions. +type RelationsFixture struct { + // IssuePrefix namespaces the ids each assertion seeds, so several of them + // can share one database. + IssuePrefix string + Relations publicops.Relations + // CreateIssue seeds a durable issue in the issues plane. + CreateIssue func(context.Context, *types.Issue, string) error + // CreateWisp seeds an ephemeral issue in the wisps plane. It is a separate + // field rather than an Ephemeral flag on CreateIssue because the three + // adapters reach the two planes through different verbs. + CreateWisp func(context.Context, *types.Issue, string) error + // AddDependency seeds ONE edge through the backend's own dependency verb, + // so a case sets its graph up without going through the role it is + // checking. The edge is routed to the plane its SOURCE lives in. + AddDependency func(context.Context, *types.Dependency, string) error + // QueryScalar runs a single-row query and scans it. Relations writes + // nothing, so this is not here to check a state transition: it is here so + // the cross-plane ordering case can prove its seed really did straddle the + // two dependency tables, instead of quietly degenerating into a + // single-plane case if the routing rules move. + QueryScalar func(context.Context, string, []any, ...any) error +} + +// RunRelationsAnswersInThePinnedOrder pins the order the role answers in: +// ascending by the neighbor's id (relations.go:91-95). The edges are seeded in +// DESCENDING id order so an implementation that returned insertion order — or +// the query's natural order — fails rather than coincides. +// +// It also pins the ROW, not just the sequence: relations.go:9-10 says a result +// row carries the edge's type alongside the issue's own fields, so an answer +// in the right order whose rows carry the wrong type is still wrong. +func RunRelationsAnswersInThePinnedOrder(t *testing.T, ctx context.Context, fixture RelationsFixture) { + t.Helper() + anchor := fixture.IssuePrefix + "-ord-anchor" + first := fixture.IssuePrefix + "-ord-n1" + second := fixture.IssuePrefix + "-ord-n2" + third := fixture.IssuePrefix + "-ord-n3" + seedRelationsIssue(t, ctx, fixture, anchor) + seedRelationsIssue(t, ctx, fixture, first) + seedRelationsIssue(t, ctx, fixture, second) + seedRelationsIssue(t, ctx, fixture, third) + + seedRelationsEdge(t, ctx, fixture, anchor, third, publicops.DepWaitsFor) + seedRelationsEdge(t, ctx, fixture, anchor, second, publicops.DepRelated) + seedRelationsEdge(t, ctx, fixture, anchor, first, publicops.DepBlocks) + + items := relationsPage(t, ctx, fixture, publicops.RelatedRequest{ID: anchor, Direction: publicops.RelationOut}) + assertRelationsPage(t, items, []string{ + first + ":" + string(publicops.DepBlocks), + second + ":" + string(publicops.DepRelated), + third + ":" + string(publicops.DepWaitsFor), + }, "out neighbors of an anchor whose edges were written in descending id order") + + // The issue's own fields travel with the edge type. The seeds title each + // issue with its own id, so one comparison covers the whole row's identity. + for _, item := range items { + if item.Title != item.ID { + t.Errorf("neighbor %s carries Title %q, want the seeded issue's own field %q", item.ID, item.Title, item.ID) + } + } +} + +// RunRelationsOrdersNeighborsFromBothPlanesTogether is the load-bearing half +// of the order. The doc's reason for pinning it is that the rows come from +// "two dependency tables read in sequence" (relations.go:92-95), so the case +// that matters is the one whose neighbors are split across those two tables +// with their ids INTERLEAVED: read plane-by-plane the answer would be +// b, d, a, c, and the contract says a, b, c, d. +// +// Incoming is the direction that can straddle the planes at all. An edge is +// routed by its SOURCE, so one anchor's outgoing edges always share a table, +// while its dependents may be durable issues (dependencies) or wisps +// (wisp_dependencies) in any mixture. +func RunRelationsOrdersNeighborsFromBothPlanesTogether(t *testing.T, ctx context.Context, fixture RelationsFixture) { + t.Helper() + anchor := fixture.IssuePrefix + "-plane-anchor" + wispA := fixture.IssuePrefix + "-plane-a" + issueB := fixture.IssuePrefix + "-plane-b" + wispC := fixture.IssuePrefix + "-plane-c" + issueD := fixture.IssuePrefix + "-plane-d" + seedRelationsIssue(t, ctx, fixture, anchor) + seedRelationsWisp(t, ctx, fixture, wispA) + seedRelationsIssue(t, ctx, fixture, issueB) + seedRelationsWisp(t, ctx, fixture, wispC) + seedRelationsIssue(t, ctx, fixture, issueD) + + // Descending again, so neither insertion order nor plane order can be + // mistaken for the pinned order. + seedRelationsEdge(t, ctx, fixture, issueD, anchor, publicops.DepBlocks) + seedRelationsEdge(t, ctx, fixture, wispC, anchor, publicops.DepWaitsFor) + seedRelationsEdge(t, ctx, fixture, issueB, anchor, publicops.DepRelated) + seedRelationsEdge(t, ctx, fixture, wispA, anchor, publicops.DepBlocks) + + // The seed really is cross-plane, and stays that way if the routing rules + // move: without this the case could silently become a single-plane one. + assertRelationsEdgeInPlane(t, ctx, fixture, "wisp_dependencies", wispA, anchor) + assertRelationsEdgeInPlane(t, ctx, fixture, "wisp_dependencies", wispC, anchor) + assertRelationsEdgeInPlane(t, ctx, fixture, "dependencies", issueB, anchor) + assertRelationsEdgeInPlane(t, ctx, fixture, "dependencies", issueD, anchor) + + items := relationsPage(t, ctx, fixture, publicops.RelatedRequest{ID: anchor, Direction: publicops.RelationIn}) + assertRelationsPage(t, items, []string{ + wispA + ":" + string(publicops.DepBlocks), + issueB + ":" + string(publicops.DepRelated), + wispC + ":" + string(publicops.DepWaitsFor), + issueD + ":" + string(publicops.DepBlocks), + }, "in neighbors interleaved across the durable and wisp dependency tables") +} + +// RunRelationsAnswersAWispTargetInTheOutDirection pins that a neighbor's PLANE +// does not decide whether it is answered: RelationOut is "the issues the anchor +// depends on" (relations.go:34-35) and a result row is "one issue on the far end +// of an edge" (relations.go:9-10), neither of which admits an exception for the +// ephemeral plane. +// +// It exists because the OUT read reaches a target through a different column +// than any other case does. An edge is routed by its SOURCE, so a durable +// anchor's outgoing edges all live in `dependencies` — but the target's own +// class picks the typed column that holds it, and a wisp target lands in +// depends_on_wisp_id. Every other seed in this file puts durable ids there, and +// the cross-plane order case (RunRelationsOrdersNeighborsFromBothPlanesTogether) +// reaches its wisps as edge SOURCES matched by issue_id, so the wisp-target +// column path was unread. An implementation that resolved out-targets from +// depends_on_issue_id alone would silently drop wisp dependencies from `bd dep +// list` and pass every other case here. +// +// The two column probes are what make that specific. Without them the case +// would still pass if the routing rules moved the wisp edge somewhere else, and +// it would no longer be reading the branch it was written for. +func RunRelationsAnswersAWispTargetInTheOutDirection(t *testing.T, ctx context.Context, fixture RelationsFixture) { + t.Helper() + anchor := fixture.IssuePrefix + "-wout-anchor" + first := fixture.IssuePrefix + "-wout-a" + wisp := fixture.IssuePrefix + "-wout-b" + third := fixture.IssuePrefix + "-wout-c" + seedRelationsIssue(t, ctx, fixture, anchor) + seedRelationsIssue(t, ctx, fixture, first) + seedRelationsWisp(t, ctx, fixture, wisp) + seedRelationsIssue(t, ctx, fixture, third) + + // Descending again, and the wisp sits in the MIDDLE of the pinned order, so + // an implementation that appended cross-plane targets rather than sorting + // them in fails on the sequence as well as on the membership. + seedRelationsEdge(t, ctx, fixture, anchor, third, publicops.DepWaitsFor) + seedRelationsEdge(t, ctx, fixture, anchor, wisp, publicops.DepRelated) + seedRelationsEdge(t, ctx, fixture, anchor, first, publicops.DepBlocks) + + assertRelationsEdgeInPlane(t, ctx, fixture, "dependencies", anchor, wisp) + assertRelationsTargetColumn(t, ctx, fixture, "depends_on_wisp_id", anchor, wisp) + assertRelationsTargetColumn(t, ctx, fixture, "depends_on_issue_id", anchor, first) + + items := relationsPage(t, ctx, fixture, publicops.RelatedRequest{ID: anchor, Direction: publicops.RelationOut}) + assertRelationsPage(t, items, []string{ + first + ":" + string(publicops.DepBlocks), + wisp + ":" + string(publicops.DepRelated), + third + ":" + string(publicops.DepWaitsFor), + }, "out neighbors of an anchor whose middle dependency is a wisp") + + // The wisp neighbor is hydrated from its own plane, not left as a bare id. + for _, item := range items { + if item.Title != item.ID { + t.Errorf("neighbor %s carries Title %q, want the seeded issue's own field %q", item.ID, item.Title, item.ID) + } + } +} + +// RunRelationsRefusesTheZeroDirection pins the rule the direction type exists +// for (relations.go:27-30, 55-57): the zero value is refused rather than +// defaulted, and there is no implicit "both". Out and in answer inverse +// questions with identical shapes, so a caller handed the wrong one has +// nothing to notice. +// +// The anchor is seeded so a passing implementation cannot be one that refused +// the request for the wrong reason. +func RunRelationsRefusesTheZeroDirection(t *testing.T, ctx context.Context, fixture RelationsFixture) { + t.Helper() + anchor := fixture.IssuePrefix + "-dirnone-anchor" + seedRelationsIssue(t, ctx, fixture, anchor) + + for _, test := range []struct { + name string + direction publicops.RelationDirection + }{ + {"the zero direction", ""}, + {"an invented both", publicops.RelationDirection("both")}, + } { + _, err := fixture.Relations.Related(ctx, publicops.RelatedRequest{ID: anchor, Direction: test.direction}) + if !errors.Is(err, publicops.ErrValidation) { + t.Errorf("Related with %s (%q) error = %v, want ErrValidation", test.name, test.direction, err) + } + } +} + +// RunRelationsSeparatesNoNeighborsFromNoSuchIssue pins relations.go:50-53 and +// :97 together, because each is only meaningful with the other: "this issue +// has no dependencies" and "there is no such issue" are different facts, and +// an implementation that answered both with an empty page would pass either +// assertion alone. +func RunRelationsSeparatesNoNeighborsFromNoSuchIssue(t *testing.T, ctx context.Context, fixture RelationsFixture) { + t.Helper() + lonely := fixture.IssuePrefix + "-lonely" + absent := fixture.IssuePrefix + "-absent" + seedRelationsIssue(t, ctx, fixture, lonely) + + items, err := fixture.Relations.Related(ctx, publicops.RelatedRequest{ID: lonely, Direction: publicops.RelationOut}) + if err != nil { + t.Fatalf("Related on a seeded issue with no edges: %v", err) + } + if items == nil { + t.Error("Related returned nil for a successful call, want an empty slice a caller marshals as [] rather than null") + } + if len(items) != 0 { + t.Errorf("neighbors of an edgeless issue = %v, want none", relationsPageKeys(items)) + } + + if _, err := fixture.Relations.Related(ctx, publicops.RelatedRequest{ + ID: absent, Direction: publicops.RelationOut, + }); !errors.Is(err, publicops.ErrNotFound) { + t.Errorf("Related on an id that names neither plane error = %v, want ErrNotFound and not an empty page", err) + } +} + +// RunRelationsResolvesAWispAnchor pins the other half of "both planes are +// searched" (relations.go:50-51). The edgeless wisp is the sharper of the two +// probes: an existence check that looked only at the issues plane would report +// ErrNotFound for it, and no neighbor read would ever run. +func RunRelationsResolvesAWispAnchor(t *testing.T, ctx context.Context, fixture RelationsFixture) { + t.Helper() + wisp := fixture.IssuePrefix + "-wisp-anchor" + target := fixture.IssuePrefix + "-wisp-target" + bare := fixture.IssuePrefix + "-wisp-bare" + seedRelationsWisp(t, ctx, fixture, wisp) + seedRelationsWisp(t, ctx, fixture, bare) + seedRelationsIssue(t, ctx, fixture, target) + seedRelationsEdge(t, ctx, fixture, wisp, target, publicops.DepBlocks) + + items := relationsPage(t, ctx, fixture, publicops.RelatedRequest{ID: wisp, Direction: publicops.RelationOut}) + assertRelationsPage(t, items, []string{target + ":" + string(publicops.DepBlocks)}, + "out neighbors of a wisp anchor") + + empty, err := fixture.Relations.Related(ctx, publicops.RelatedRequest{ID: bare, Direction: publicops.RelationOut}) + if err != nil { + t.Fatalf("Related on a wisp with no edges: %v — the anchor probe missed the wisps plane", err) + } + if empty == nil || len(empty) != 0 { + t.Errorf("neighbors of an edgeless wisp = %v (nil=%v), want an empty non-nil page", relationsPageKeys(empty), empty == nil) + } +} + +// RunRelationsFiltersByAnOpenTypeVocabulary pins relations.go:58-65: the type +// vocabulary is OPEN, so a workspace's own type has to be able to filter. An +// implementation that validated Types against the Dep* constants would break +// every workspace that spelled one of its own, and this is the case that +// catches it. +// +// The empty-result probe at the end is the companion to :77: a usable type no +// edge happens to carry is an empty non-nil page, not an error — it is only an +// UNUSABLE entry that must be refused, which is the next case. +func RunRelationsFiltersByAnOpenTypeVocabulary(t *testing.T, ctx context.Context, fixture RelationsFixture) { + t.Helper() + const invented = types.DependencyType("workspace-invented") + const unused = types.DependencyType("workspace-unused") + anchor := fixture.IssuePrefix + "-filter-anchor" + blocker := fixture.IssuePrefix + "-filter-n1" + related := fixture.IssuePrefix + "-filter-n2" + custom := fixture.IssuePrefix + "-filter-n3" + seedRelationsIssue(t, ctx, fixture, anchor) + seedRelationsIssue(t, ctx, fixture, blocker) + seedRelationsIssue(t, ctx, fixture, related) + seedRelationsIssue(t, ctx, fixture, custom) + seedRelationsEdge(t, ctx, fixture, anchor, blocker, publicops.DepBlocks) + seedRelationsEdge(t, ctx, fixture, anchor, related, publicops.DepRelated) + seedRelationsEdge(t, ctx, fixture, anchor, custom, invented) + + for _, test := range []struct { + name string + types []publicops.DependencyType + want []string + }{ + { + name: "no filter answers every type", + want: []string{ + blocker + ":" + string(publicops.DepBlocks), + related + ":" + string(publicops.DepRelated), + custom + ":" + string(invented), + }, + }, + { + name: "a workspace-invented type filters", + types: []publicops.DependencyType{invented}, + want: []string{custom + ":" + string(invented)}, + }, + { + name: "several types narrow to their union, still in the pinned order", + types: []publicops.DependencyType{publicops.DepRelated, publicops.DepBlocks}, + want: []string{ + blocker + ":" + string(publicops.DepBlocks), + related + ":" + string(publicops.DepRelated), + }, + }, + { + name: "a usable type no edge carries is an empty page, not an error", + types: []publicops.DependencyType{unused}, + want: nil, + }, + } { + items := relationsPage(t, ctx, fixture, publicops.RelatedRequest{ + ID: anchor, Direction: publicops.RelationOut, Types: test.types, + }) + if items == nil { + t.Errorf("%s: Related returned nil for a successful call, want an empty slice", test.name) + continue + } + assertRelationsPage(t, items, test.want, test.name) + } +} + +// RunRelationsRefusesAnUnusableTypeFilter pins the refusal half of +// relations.go:61-65: an entry that is not a value at all is ErrValidation, +// "rather than a filter that quietly matches nothing". +// +// Both entries here are unusable under every reading of the clause. The +// boundary itself — an entry longer than the type COLUMN — is its own case +// below, so a failure there does not take these two with it. +func RunRelationsRefusesAnUnusableTypeFilter(t *testing.T, ctx context.Context, fixture RelationsFixture) { + t.Helper() + anchor := fixture.IssuePrefix + "-badfilter-anchor" + seedRelationsIssue(t, ctx, fixture, anchor) + + for _, test := range []struct { + name string + depType publicops.DependencyType + }{ + {"an empty entry", ""}, + {"an entry past every length bound", publicops.DependencyType(strings.Repeat("x", 51))}, + } { + _, err := fixture.Relations.Related(ctx, publicops.RelatedRequest{ + ID: anchor, + Direction: publicops.RelationOut, + Types: []publicops.DependencyType{test.depType}, + }) + if !errors.Is(err, publicops.ErrValidation) { + t.Errorf("Related with %s (%d chars) error = %v, want ErrValidation", test.name, len(test.depType), err) + } + } +} + +// RunRelationsRefusesATypeFilterOverTheColumnLength pins the clause's own +// yardstick: an entry is usable when it is "non-empty, within the COLUMN's +// length" (relations.go:61-62). Both dependency planes store the type in a +// VARCHAR(32) (migrations 0002:4 and 0021:14), so a 40-character type is one +// no edge can ever carry — the insert fails with "string ... is too large for +// column 'type'" — and accepting it as a filter is exactly the quiet +// match-nothing the clause forbids. +// +// The shared validator bounds a type at types.MaxDependencyTypeLen, which is +// that column width (bd-yby99.3 narrowed it from a looser 50), so the refusal +// arrives from one place ahead of every backend. +func RunRelationsRefusesATypeFilterOverTheColumnLength(t *testing.T, ctx context.Context, fixture RelationsFixture) { + t.Helper() + anchor := fixture.IssuePrefix + "-longfilter-anchor" + seedRelationsIssue(t, ctx, fixture, anchor) + + overLong := publicops.DependencyType(strings.Repeat("x", 40)) + _, err := fixture.Relations.Related(ctx, publicops.RelatedRequest{ + ID: anchor, + Direction: publicops.RelationOut, + Types: []publicops.DependencyType{overLong}, + }) + if !errors.Is(err, publicops.ErrValidation) { + t.Errorf("Related with a %d-character type — longer than the VARCHAR(32) the planes store — error = %v, want ErrValidation", + len(overLong), err) + } +} + +// RunRelationsDirectionSelectsTheInverseGraph pins relations.go:34-38 against +// ONE seed graph read both ways: out is what the anchor depends on, in is what +// depends on the anchor. Asserting the two directions separately, on separate +// graphs, is what lets an inversion hide — and an inversion is the failure the +// zero-value direction rule exists to prevent, so the contract has to be able +// to see it. +func RunRelationsDirectionSelectsTheInverseGraph(t *testing.T, ctx context.Context, fixture RelationsFixture) { + t.Helper() + anchor := fixture.IssuePrefix + "-dir-anchor" + // The anchor depends on its blocker; its dependent depends on the anchor. + blocker := fixture.IssuePrefix + "-dir-blocker" + dependent := fixture.IssuePrefix + "-dir-dependent" + seedRelationsIssue(t, ctx, fixture, anchor) + seedRelationsIssue(t, ctx, fixture, blocker) + seedRelationsIssue(t, ctx, fixture, dependent) + seedRelationsEdge(t, ctx, fixture, anchor, blocker, publicops.DepBlocks) + seedRelationsEdge(t, ctx, fixture, dependent, anchor, publicops.DepBlocks) + + out := relationsPage(t, ctx, fixture, publicops.RelatedRequest{ID: anchor, Direction: publicops.RelationOut}) + assertRelationsPage(t, out, []string{blocker + ":" + string(publicops.DepBlocks)}, + "out neighbors, which are what the anchor depends on") + + in := relationsPage(t, ctx, fixture, publicops.RelatedRequest{ID: anchor, Direction: publicops.RelationIn}) + assertRelationsPage(t, in, []string{dependent + ":" + string(publicops.DepBlocks)}, + "in neighbors, which are what depends on the anchor") +} + +// RunRelationsLeavesTheCallersRequestAlone is the request-snapshot tripwire for +// relations.go:83-87: implementations never mutate caller-owned request values +// and normalize only attempt-local clones. +// +// RelatedRequest travels by value, so Types is the only member that can carry a +// write back to the caller, and it is populated here with exactly what an +// in-place normalizer would reach for — a duplicate entry, in descending order. +// Both bodies read it into a set today, so this is a tripwire rather than a bug +// report: it fails the day a sort or a dedupe is written against the caller's +// own backing array instead of a clone. +// +// The request answers a real page rather than an empty one, because a filter +// matching nothing can be short-circuited before the type set is ever built — +// the path where no mutation would happen anyway. +func RunRelationsLeavesTheCallersRequestAlone(t *testing.T, ctx context.Context, fixture RelationsFixture) { + t.Helper() + anchor := fixture.IssuePrefix + "-snap-anchor" + blocker := fixture.IssuePrefix + "-snap-n1" + related := fixture.IssuePrefix + "-snap-n2" + seedRelationsIssue(t, ctx, fixture, anchor) + seedRelationsIssue(t, ctx, fixture, blocker) + seedRelationsIssue(t, ctx, fixture, related) + seedRelationsEdge(t, ctx, fixture, anchor, blocker, publicops.DepBlocks) + seedRelationsEdge(t, ctx, fixture, anchor, related, publicops.DepRelated) + + build := func() publicops.RelatedRequest { + return publicops.RelatedRequest{ + ID: anchor, + Direction: publicops.RelationOut, + Types: []publicops.DependencyType{ + publicops.DepRelated, + publicops.DepBlocks, + publicops.DepRelated, + }, + } + } + request := build() + want := build() + + items := relationsPage(t, ctx, fixture, request) + assertRelationsPage(t, items, []string{ + blocker + ":" + string(publicops.DepBlocks), + related + ":" + string(publicops.DepRelated), + }, "out neighbors under a duplicated, descending type filter") + + if !reflect.DeepEqual(request, want) { + t.Errorf("Related mutated the caller's request:\n got %#v\nwant %#v", request, want) + } +} + +// RunRelationsLeavesAnExternalTargetOutOfTheAnswer pins what a row's own type +// decides: "It is an ISSUE and can be nothing else ... Related leaves it out, +// with no placeholder row and no error" (relations.go:12-17). +// +// The two seeds are the two shapes issueops.IsExternalDepTarget names — an +// "external:" reference and a target whose id prefix belongs to another +// repository — because each reaches depends_on_external by a different rule and +// a backend can implement one and miss the other, which is exactly what +// bd-ocrn7 was. DependencyEditor accepts both +// (RunDependencyEditorAcceptsAnExternalTarget, ...AcceptsAForeignRepoTarget), +// which is what makes an unanswerable edge a state a workspace really reaches +// rather than a hypothetical. +// +// The resolvable neighbor is what keeps the case from passing vacuously: an +// implementation that answered nothing at all would satisfy an assertion about +// absence alone. The column probes are what keep it reading the branch it was +// written for — without them a routing change could quietly turn both seeds +// into ordinary durable targets, and the case would still pass while asserting +// something else entirely. +// +// The ErrNotFound at the end is the same fact from the other side: an id this +// database holds no row for is not an ANCHOR either (relations.go:50-53), so +// there is no direction from which the external edge becomes visible through +// this role. +func RunRelationsLeavesAnExternalTargetOutOfTheAnswer(t *testing.T, ctx context.Context, fixture RelationsFixture) { + t.Helper() + anchor := fixture.IssuePrefix + "-ext-anchor" + neighbor := fixture.IssuePrefix + "-ext-n" + external := "external:" + fixture.IssuePrefix + "-ext-tracker" + const foreign = "otherrig-9001" + seedRelationsIssue(t, ctx, fixture, anchor) + seedRelationsIssue(t, ctx, fixture, neighbor) + + seedRelationsEdge(t, ctx, fixture, anchor, neighbor, publicops.DepBlocks) + seedRelationsEdge(t, ctx, fixture, anchor, external, publicops.DepRelated) + seedRelationsEdge(t, ctx, fixture, anchor, foreign, publicops.DepWaitsFor) + + assertRelationsTargetColumn(t, ctx, fixture, "depends_on_external", anchor, external) + assertRelationsTargetColumn(t, ctx, fixture, "depends_on_external", anchor, foreign) + assertRelationsTargetColumn(t, ctx, fixture, "depends_on_issue_id", anchor, neighbor) + + items := relationsPage(t, ctx, fixture, publicops.RelatedRequest{ID: anchor, Direction: publicops.RelationOut}) + assertRelationsPage(t, items, []string{neighbor + ":" + string(publicops.DepBlocks)}, + "out neighbors of an anchor with three edges, two of which point outside this database") + + for _, id := range []string{external, foreign} { + if _, err := fixture.Relations.Related(ctx, publicops.RelatedRequest{ + ID: id, Direction: publicops.RelationIn, + }); !errors.Is(err, publicops.ErrNotFound) { + t.Errorf("Related anchored on %s error = %v, want ErrNotFound: an id neither plane holds is not an anchor", id, err) + } + } +} + +// RunRelationsResolvesTheAnchorIDExactly pins the anchor clause's promise half +// (relations.go:42-48): "EXACT is a promise the role keeps rather than an +// obligation it puts on the caller", so a case variant, an id carrying +// surrounding whitespace, a prefix of a real id and a real id with a suffix are +// all ErrNotFound. +// +// The case variant is the entry that earns the case. The other three are +// different STRINGS and would miss under any equality; a case variant is the +// same string under a case-insensitive collation, so this is the one spelling +// whose answer today comes from the ENGINE rather than from anything the role +// does — validation checks only that the id is non-empty +// (internal/storage/issueops/relations.go:27-29) and resolution is then a +// `WHERE id = ?` per plane. All three backends run a binary collation and refuse +// it, which is why the promise could be adopted; this case is what holds a +// backend on a case-insensitive collation to it, where an anchor typed in the +// wrong case would otherwise be answered as though it were the right one. +// +// The exact spelling is asserted first and answers a real neighbor, so a body +// that refused every request would fail here rather than pass the refusals. +func RunRelationsResolvesTheAnchorIDExactly(t *testing.T, ctx context.Context, fixture RelationsFixture) { + t.Helper() + anchor := fixture.IssuePrefix + "-exact-anchor" + neighbor := fixture.IssuePrefix + "-exact-n" + seedRelationsIssue(t, ctx, fixture, anchor) + seedRelationsIssue(t, ctx, fixture, neighbor) + seedRelationsEdge(t, ctx, fixture, anchor, neighbor, publicops.DepBlocks) + + items := relationsPage(t, ctx, fixture, publicops.RelatedRequest{ID: anchor, Direction: publicops.RelationOut}) + assertRelationsPage(t, items, []string{neighbor + ":" + string(publicops.DepBlocks)}, + "out neighbors of the anchor spelled exactly") + + for _, test := range []struct{ what, id string }{ + {"a case variant", strings.ToUpper(anchor)}, + {"a trailing space", anchor + " "}, + {"a leading space", " " + anchor}, + {"a prefix of the id", anchor[:len(anchor)-2]}, + {"the id with a suffix", anchor + "x"}, + } { + got, err := fixture.Relations.Related(ctx, publicops.RelatedRequest{ID: test.id, Direction: publicops.RelationOut}) + if !errors.Is(err, publicops.ErrNotFound) { + t.Errorf("Related with %s (%q) = (%v, %v), want ErrNotFound: this role resolves the stored spelling only", + test.what, test.id, relationsPageKeys(got), err) + } + } +} + +func seedRelationsIssue(t *testing.T, ctx context.Context, fixture RelationsFixture, id string) { + t.Helper() + if err := fixture.CreateIssue(ctx, relationsSeed(id, false), "seed"); err != nil { + t.Fatalf("seed issue %s: %v", id, err) + } +} + +func seedRelationsWisp(t *testing.T, ctx context.Context, fixture RelationsFixture, id string) { + t.Helper() + if err := fixture.CreateWisp(ctx, relationsSeed(id, true), "seed"); err != nil { + t.Fatalf("seed wisp %s: %v", id, err) + } +} + +func seedRelationsEdge(t *testing.T, ctx context.Context, fixture RelationsFixture, from, to string, depType types.DependencyType) { + t.Helper() + if err := fixture.AddDependency(ctx, &types.Dependency{IssueID: from, DependsOnID: to, Type: depType}, "seed"); err != nil { + t.Fatalf("seed edge %s -%s-> %s: %v", from, depType, to, err) + } +} + +// relationsSeed titles each issue with its own id, so a case can check that a +// result row carries the issue's own fields with one comparison. +func relationsSeed(id string, ephemeral bool) *types.Issue { + return &types.Issue{ + ID: id, + Title: id, + Status: types.StatusOpen, + Priority: 2, + IssueType: types.TypeTask, + Ephemeral: ephemeral, + } +} + +// relationsPage runs one request that is expected to succeed. +func relationsPage(t *testing.T, ctx context.Context, fixture RelationsFixture, request publicops.RelatedRequest) []*publicops.RelatedIssue { + t.Helper() + items, err := fixture.Relations.Related(ctx, request) + if err != nil { + t.Fatalf("Related(%s, %s, types=%v): %v", request.ID, request.Direction, request.Types, err) + } + return items +} + +// relationsPageKeys renders a page as "id:type" strings IN THE ORDER the role +// answered, so a comparison against a literal compares the pinned order and +// not a set. +func relationsPageKeys(items []*publicops.RelatedIssue) []string { + keys := make([]string, 0, len(items)) + for _, item := range items { + keys = append(keys, item.ID+":"+string(item.DependencyType)) + } + return keys +} + +func assertRelationsPage(t *testing.T, items []*publicops.RelatedIssue, want []string, describe string) { + t.Helper() + got := relationsPageKeys(items) + if len(got) != len(want) { + t.Errorf("%s = %v, want %v", describe, got, want) + return + } + for i := range got { + if got[i] != want[i] { + t.Errorf("%s = %v, want %v", describe, got, want) + return + } + } +} + +// assertRelationsEdgeInPlane checks that the seeded edge from source to target +// landed in the named dependency table. The target is matched through the +// resolved target expression because a target's own class decides which typed +// column holds it, independently of the source routing under test. +func assertRelationsEdgeInPlane(t *testing.T, ctx context.Context, fixture RelationsFixture, table, source, target string) { + t.Helper() + var got int + //nolint:gosec // G201: table is one of the contract's two hardcoded names. + query := "SELECT COUNT(*) FROM " + table + + " WHERE issue_id = ? AND COALESCE(depends_on_issue_id, depends_on_wisp_id, depends_on_external) = ?" + if err := fixture.QueryScalar(ctx, query, []any{source, target}, &got); err != nil { + t.Fatalf("count %s edges %s -> %s: %v", table, source, target, err) + } + if got != 1 { + t.Fatalf("%s edges %s -> %s = %d, want 1 — the cross-plane seed is no longer cross-plane", table, source, target, got) + } +} + +// assertRelationsTargetColumn checks WHICH typed target column of the durable +// dependency table holds the seeded edge's target. assertRelationsEdgeInPlane +// resolves the target through a COALESCE over all three, so it cannot tell a +// wisp target from a durable one; a case whose whole subject is the column path +// the read walks needs the column named. +func assertRelationsTargetColumn(t *testing.T, ctx context.Context, fixture RelationsFixture, column, source, target string) { + t.Helper() + var got int + //nolint:gosec // G201: column is one of the contract's hardcoded target-column names. + query := "SELECT COUNT(*) FROM dependencies WHERE issue_id = ? AND " + column + " = ?" + if err := fixture.QueryScalar(ctx, query, []any{source, target}, &got); err != nil { + t.Fatalf("count dependencies edges %s -> %s held in %s: %v", source, target, column, err) + } + if got != 1 { + t.Fatalf("dependencies edges %s -> %s held in %s = %d, want 1 — the seed no longer exercises that column path", + source, target, column, got) + } +} diff --git a/claim.go b/claim.go index 4a3dd754a..380e90186 100644 --- a/claim.go +++ b/claim.go @@ -9,13 +9,17 @@ import ( // ClaimConflict describes why a claim failed, recovered from the claim error. // -// The engine's conditional-UPDATE claim path returns no typed conflict result: -// on ErrAlreadyClaimed it embeds the current assignee in the message -// ("issue already claimed by "), and on ErrNotClaimable it embeds the -// current status ("issue not claimable: status "). ClaimConflict -// carries whichever of those was recoverable; the other stays empty. This is a -// deliberately string-coupled shim — a typed conflict result would require -// changing the internal claim signature, which this surface deliberately avoids. +// The engine's claim path embeds the conflicting state in the message: on +// ErrAlreadyClaimed the current assignee ("issue already claimed by +// "), on ErrNotClaimable the current status ("issue not claimable: +// status "). ClaimConflict carries whichever of those was recoverable; +// the other stays empty. This is a deliberately string-coupled shim. +// +// A CALLER ON THE LIBRARY CONTRACT DOES NOT NEED IT. The claim path now returns +// issueops.ClaimConflictError, which carries the assignee and status as typed +// fields read inside the attempt that lost, so errors.As recovers them without +// parsing anything. This shim stays for callers holding a claim error from +// somewhere else, and because it is public API. type ClaimConflict struct { // CurrentAssignee is the actor currently holding the issue. Set when the // error wraps ErrAlreadyClaimed and the assignee was parseable. diff --git a/cmd/bd/close.go b/cmd/bd/close.go index 8c67f2b92..d654b6299 100644 --- a/cmd/bd/close.go +++ b/cmd/bd/close.go @@ -2,7 +2,6 @@ package main import ( "context" - "errors" "fmt" "os" "strings" @@ -109,89 +108,57 @@ the flags appear in the command line.`, // cleanup closes the routed handle. Deduped by pointer. mutatedStores := map[storage.DoltStorage][]string{} - // Direct mode + // Pick a store for post-close work (--suggest-next, --continue, --claim-next). + // All three flags are documented as single-issue paths; for the multi-id case + // we use the first resolved ID's store, which matches the common case where + // every ID routes to the same place. + postCloseStore := store + if len(results) > 0 && results[0].Store != nil { + postCloseStore = results[0].Store + } + + // THE BATCH. The CLI's own close policy runs first and read-only, then + // every id it passed goes to the BatchCloser role as one request per + // store: one transaction, one Dolt commit over N ids, and an id the + // batch refuses skipped while the survivors commit. --claim-next rides + // inside that transaction, and the engine's own is_blocked guard runs + // there too (GH#962), so there is no read-then-write TOCTOU window + // between the check and the close. + plan := closeDirectPreflight(results, resolvedIDs, reasons, force) + outcomes, claimedNext := closeDirectRun(opsCtx, closeDirectBatches(plan.items), len(resolvedIDs), + session, force, postCloseStore, closeClaimNextRequest(claimNext, continueFlag)) + + // Report and follow up on every argument, in the order it was typed. closedIssues := []*types.Issue{} closedCount := 0 alreadyClosed := 0 firstSettledID := "" for i, id := range resolvedIDs { - result := results[i] - activeStore := result.Store + res := outcomes[i] + if res == nil { + // The CLI's own close policy refused this argument, so the + // batch never saw it. + fmt.Fprintln(os.Stderr, plan.refusals[i]) + continue + } + if res.Err != nil { + fmt.Fprintln(os.Stderr, closeDirectRefusal(id, res.Err)) + continue + } + + // Open children only survive to here when --force waived the + // engine's refusal. Say so, so orphaned children are never silent. + if res.OpenChildren > 0 { + fmt.Fprintf(os.Stderr, "warning: closing %s with %d open child issue(s) still active\n", id, res.OpenChildren) + } + + activeStore := results[i].Store reason := reasonForCloseIndex(reasons, i) - // Get issue for checks (nil issue is handled by validateIssueClosable) - issue := result.Issue + // Pre-close snapshot, for the audit entry's old status and the + // success line's title. + issue := results[i].Issue - // Close validation guards a state change; a row already at literal - // StatusClosed has none to guard, so skip it and let the re-close reach - // the engine as the idempotent no-op it has always been (ga-ktn9pe.4.8). - // Without this, a forced close of a boolean-pinned bead leaves - // pinned=true (closeIssueInTx never touches the column — deliberately, - // it is the deletion-protection flag bd gc/purge/cleanup honor) and the - // plain retry hits NotPinned and exits nonzero, which strands the - // molecule auto-close re-drive documented on the !res.Changed branch - // below. Only a literal closed status qualifies: reaching a configured - // done status is still a real close, mirroring the engine's isClosedInTx. - // The snapshot only decides whether validation runs, never what is - // written — the engine's in-transaction `status != closed` guard remains - // the authority on whether the close is a no-op, so a concurrent close - // still converges. Mirrored in closeProxiedOne. - if issue == nil || issue.Status != types.StatusClosed { - if err := validateIssueClosable(id, issue, actor, force); err != nil { - fmt.Fprintf(os.Stderr, "%s\n", err) - continue - } - } - - // Open-children close guard: prevent closing any issue with open - // parent-child dependents (GH#3681). With --force the close proceeds - // but a warning is emitted so orphaned children are never silent. - if issue != nil { - openChildren := countOpenChildren(ctx, activeStore, id) - if openChildren > 0 { - if force { - fmt.Fprintf(os.Stderr, "warning: closing %s with %d open child issue(s) still active\n", id, openChildren) - } else { - fmt.Fprintf(os.Stderr, "cannot close %s: %d open child issue(s); close children first or use --force to override\n", id, openChildren) - continue - } - } - } - - // Check gate satisfaction for machine-checkable gates (GH#1467) - if !force { - if err := checkGateSatisfaction(issue); err != nil { - fmt.Fprintf(os.Stderr, "cannot close %s: %s\n", id, err) - continue - } - } - - // Delegate the is_blocked guard to the engine (GH#962). The close - // operation runs the guard and the close in ONE transaction, so there is - // no read-then-write TOCTOU window between the check and the close. - // --force bypasses the guard; ExpectedVersion is unused on this path. - ops, err := writeOps(activeStore) - if err != nil { - fmt.Fprintf(os.Stderr, "Error closing %s: %v\n", id, err) - continue - } - res, err := ops.Close(opsCtx, issueops.CloseRequest{ - Actor: actor, - IssueID: id, - Reason: reason, - Session: session, - Force: force, - }) - if err != nil { - if errors.Is(err, storage.ErrCloseBlocked) { - // The guard refused atomically; ErrCloseBlocked's message names the - // blockers. Preserve the actionable hint. - fmt.Fprintf(os.Stderr, "%v (use --force to override)\n", err) - } else { - fmt.Fprintf(os.Stderr, "Error closing %s: %v\n", id, err) - } - continue - } if !res.Changed { // Already closed: an idempotent no-op on the step's stored state. The // old CloseIssue path also returned nil here and still reported the @@ -286,15 +253,6 @@ the flags appear in the command line.`, SetLastTouchedID(firstSettledID) } - // Pick a store for post-close work (--suggest-next, --continue, --claim-next). - // All three flags are documented as single-issue paths; for the multi-id case - // we use the first resolved ID's store, which matches the common case where - // every ID routes to the same place. - postCloseStore := store - if len(results) > 0 && results[0].Store != nil { - postCloseStore = results[0].Store - } - if suggestNext && len(resolvedIDs) == 1 && closedForCommand { unblocked, err := postCloseStore.GetNewlyUnblockedByClose(ctx, resolvedIDs[0]) if err == nil && len(unblocked) > 0 { @@ -341,31 +299,21 @@ the flags appear in the command line.`, } } - // Handle --claim-next flag + // Report --claim-next. The claim itself already happened, inside the + // batch's own transaction and only when something landed, so what is + // left here is the report and the last-touched hand-off. Register the + // claimed store anyway: the batch committed the claim, but the sweep + // below still has to name it if a molecule auto-close made the store + // dirty again. var claimedNextIssue *types.Issue if claimNext && closedForCommand && !continueFlag { - readyIssues, err := postCloseStore.GetReadyWork(ctx, types.WorkFilter{ - Status: "open", - Limit: 1, - SortPolicy: types.SortPolicy("priority"), - }) - if err != nil { - fmt.Fprintf(os.Stderr, "Warning: could not get ready issues: %v\n", err) - } else if len(readyIssues) > 0 { - nextIssue := readyIssues[0] - err := postCloseStore.ClaimIssue(ctx, nextIssue.ID, actor) - if err == nil { - claimedNextIssue = nextIssue - mutatedStores[postCloseStore] = append(mutatedStores[postCloseStore], nextIssue.ID) - if jsonOutput { - // JSON handled below - } else { - debug.PrintNormal("%s Auto-claimed next ready issue: %s (P%d)\n", ui.RenderPass("✓"), formatFeedbackID(nextIssue.ID, nextIssue.Title), nextIssue.Priority) - } - SetLastTouchedID(nextIssue.ID) - } else { - fmt.Fprintf(os.Stderr, "Warning: could not claim next issue %s: %v\n", nextIssue.ID, err) + if claimedNext != nil { + claimedNextIssue = claimedNext.Issue + mutatedStores[postCloseStore] = append(mutatedStores[postCloseStore], claimedNextIssue.ID) + if !jsonOutput { + debug.PrintNormal("%s Auto-claimed next ready issue: %s (P%d)\n", ui.RenderPass("✓"), formatFeedbackID(claimedNextIssue.ID, claimedNextIssue.Title), claimedNextIssue.Priority) } + SetLastTouchedID(claimedNextIssue.ID) } else if !jsonOutput { debug.PrintNormal("\n%s No ready issues available to claim.\n", ui.RenderWarn("✨")) } @@ -531,6 +479,25 @@ func reasonForCloseIndex(reasons []string, i int) string { return reasons[i] } +// closeClaimNextRequest is --claim-next as the batch expresses it. BOTH of +// `bd close`'s routes build it here, so the claim asks one question no matter +// which door it came through. +// +// The role runs it inside the closes' transaction and only when at least one +// item landed, which is the rule each route used to enforce by hand; --continue +// still wins, because the two flags have always been mutually exclusive here. +// +// It asks for priority order and no limit. The old two-step read the single top +// ready row and warned if that one row happened to be taken; the role's claim +// walks the ready order and takes the first row it can win, so a race with +// another agent now claims the next candidate instead of claiming nothing. +func closeClaimNextRequest(claimNext, continueOn bool) *issueops.ReadyRequest { + if !claimNext || continueOn { + return nil + } + return &issueops.ReadyRequest{Sort: string(types.SortPolicyPriority)} +} + func validateCloseReasons(reasons []string) error { closeValidation := config.GetString("validation.on-close") if closeValidation != "error" && closeValidation != "warn" { @@ -777,22 +744,3 @@ func resolveCloseTargets(ctx context.Context, localStore storage.DoltStorage, id } return results, cleanup, nil } - -// countOpenChildren returns the number of open (non-closed) parent-child -// dependents for any issue (epics, tasks, etc.). -// Uses GetDependentsWithMetadata to find parent-child relationships. -// Takes an explicit store so callers can route to the store actually holding the issue -// (relevant for contributor auto-routing where the issue lives in the planning repo). -func countOpenChildren(ctx context.Context, s storage.DoltStorage, issueID string) int { - dependents, err := s.GetDependentsWithMetadata(ctx, issueID) - if err != nil { - return 0 - } - count := 0 - for _, dep := range dependents { - if dep.DependencyType == types.DepParentChild && dep.Issue.Status != types.StatusClosed { - count++ - } - } - return count -} diff --git a/cmd/bd/close_direct.go b/cmd/bd/close_direct.go new file mode 100644 index 000000000..635212500 --- /dev/null +++ b/cmd/bd/close_direct.go @@ -0,0 +1,221 @@ +package main + +import ( + "context" + "errors" + "fmt" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" +) + +// closeDirectItem is one argument that survived `bd close`'s own close policy, +// paired with the store that actually owns it. arg is the argument position, so +// an outcome can be folded back onto the list the caller typed. +type closeDirectItem struct { + arg int + id string + reason string + store storage.DoltStorage +} + +// closeDirectPlan is the argument list after the CLI's own close policy has +// run: the items the batch is handed, and the refusal each rejected argument +// earned. +// +// refusals is indexed by ARGUMENT position rather than by item so a refusal +// decided here and one decided by the batch still print in the order the ids +// were typed. An entry is non-empty exactly when that argument never became an +// item. +type closeDirectPlan struct { + items []closeDirectItem + refusals []string +} + +// closeDirectPreflight applies `bd close`'s own close policy to every resolved +// argument, and hands the batch only the items that survived. +// +// Neither check is library policy — the template/pin/assignee fence and gate +// satisfaction read the issue and nothing else, and the role has no vocabulary +// for either — which is why they stay in cmd/bd. It is closeProxiedRunPreflight's +// job on this route. +// +// The open-children guard is NOT here, and that is the point: the engine +// enforces it inside the close's own transaction, refusing with a +// CloseOpenChildrenError whose message is the one this route used to compose +// by hand. Keeping a copy here would be a second implementation of a rule the +// role already states, and a read-then-write window besides — one that made +// `bd close ` depend on argument order. +func closeDirectPreflight(results []*RoutedResult, resolvedIDs, reasons []string, force bool) closeDirectPlan { + plan := closeDirectPlan{refusals: make([]string, len(resolvedIDs))} + for i, id := range resolvedIDs { + if refusal := closeDirectCheckOne(id, results[i].Issue, force); refusal != "" { + plan.refusals[i] = refusal + continue + } + plan.items = append(plan.items, closeDirectItem{ + arg: i, + id: id, + reason: reasonForCloseIndex(reasons, i), + store: results[i].Store, + }) + } + return plan +} + +// closeDirectCheckOne returns one argument's refusal, or "" when it may go to +// the batch. +func closeDirectCheckOne(id string, issue *types.Issue, force bool) string { + // Close validation guards a state change; a row already at literal + // StatusClosed has none to guard, so skip it and let the re-close reach the + // engine as the idempotent no-op it has always been (ga-ktn9pe.4.8). + // Without this, a forced close of a boolean-pinned bead leaves pinned=true + // (the close write never touches the column — deliberately, it is the + // deletion-protection flag bd gc/purge/cleanup honor) and the plain retry + // hits NotPinned and exits nonzero, which strands the molecule auto-close + // the unchanged branch re-drives. Only a literal closed status qualifies: + // reaching a configured done status is still a real close, mirroring the + // engine's isClosedInTx. The snapshot only decides whether validation runs, + // never what is written — the engine's in-transaction `status != closed` + // guard remains the authority on whether the close is a no-op, so a + // concurrent close still converges. Mirrored in closeProxiedCheckOne. + if issue == nil || issue.Status != types.StatusClosed { + if err := validateIssueClosable(id, issue, actor, force); err != nil { + return err.Error() + } + } + + // Gate satisfaction for machine-checkable gates (GH#1467). + if !force { + if err := checkGateSatisfaction(issue); err != nil { + return fmt.Sprintf("cannot close %s: %s", id, err) + } + } + + return "" +} + +// closeDirectBatch is one store's slice of the argument list. +type closeDirectBatch struct { + store storage.DoltStorage + items []closeDirectItem +} + +// closeDirectBatches groups the surviving items by the store that owns them, +// keeping both the order the stores first appear and the argument order within +// each store. +// +// One request per store rather than one per id is the whole point of the role: +// the REQUEST is the transaction boundary, so N ids on one store land as one +// transaction with one Dolt commit and one history entry instead of N. A second +// store is a second boundary because a transaction cannot span two databases — +// `bd close` reaches one only when its ids route to another repo. +func closeDirectBatches(items []closeDirectItem) []closeDirectBatch { + var batches []closeDirectBatch + at := make(map[storage.DoltStorage]int, len(items)) + for _, item := range items { + i, ok := at[item.store] + if !ok { + i = len(batches) + at[item.store] = i + batches = append(batches, closeDirectBatch{store: item.store}) + } + batches[i].items = append(batches[i].items, item) + } + return batches +} + +// closeDirectRequest is one store's slice as the BatchCloser role expresses it. +// It is the same request closeProxiedServer builds from the same flags: the +// per-item reasons `bd close a b c -r x -r y -r z` has always mapped +// positionally, one request-wide session, one request-wide --force. +// +// claimNext rides on the batch of claimStore and no other, because --claim-next +// hands out ONE claim however many stores the ids spanned. +func closeDirectRequest(batch closeDirectBatch, session string, force bool, claimStore storage.DoltStorage, claimNext *issueops.ReadyRequest) issueops.CloseBatchRequest { + request := issueops.CloseBatchRequest{ + Actor: actor, + Items: make([]issueops.BatchCloseItem, 0, len(batch.items)), + Session: session, + Force: force, + } + if claimNext != nil && batch.store == claimStore { + request.ClaimNext = claimNext + } + for _, item := range batch.items { + request.Items = append(request.Items, issueops.BatchCloseItem{IssueID: item.id, Reason: item.reason}) + } + return request +} + +// closeDirectRun hands each store's slice to that store's BatchCloser and folds +// the outcomes back onto the argument list. A nil entry in the returned slice is +// an argument the batch never saw, either because the CLI's own policy refused +// it or because it was never an argument at all. +// +// A batch-level error means the batch never ran — request validation, +// cancellation or infrastructure — so every id in it is reported the way a +// single failed close has always been reported here, and the remaining stores' +// batches still run. That is the same skip-and-continue the per-id loop had: +// one store's outage does not silently drop another store's closes. +func closeDirectRun(ctx context.Context, batches []closeDirectBatch, argCount int, session string, force bool, claimStore storage.DoltStorage, claimNext *issueops.ReadyRequest) ([]*issueops.CloseOutcome, *types.IssueWithCounts) { + outcomes := make([]*issueops.CloseOutcome, argCount) + var claimed *types.IssueWithCounts + + for _, batch := range batches { + result, err := closeDirectCloseBatch(ctx, batch.store, closeDirectRequest(batch, session, force, claimStore, claimNext)) + if err != nil { + for _, item := range batch.items { + refused := issueops.CloseOutcome{IssueID: item.id, Err: err} + outcomes[item.arg] = &refused + } + continue + } + // Outcomes mirror Items index for index, which is what lets a per-id + // report be walked against the caller's own argument list. + for j := range result.Outcomes { + outcome := result.Outcomes[j] + outcomes[batch.items[j].arg] = &outcome + } + if result.ClaimedNext != nil { + claimed = result.ClaimedNext + } + } + + return outcomes, claimed +} + +// closeDirectCloseBatch reaches the role through the store's OWN accessor, the +// same two-step proxiedBatchCloser performs on the other route and for the same +// reason: the accessor is where each storage decorator adds its layer, so a +// closer built any other way would be missing the hooks and telemetry the store +// itself carries. +func closeDirectCloseBatch(ctx context.Context, st storage.DoltStorage, request issueops.CloseBatchRequest) (issueops.CloseBatchResult, error) { + closer, err := st.BatchCloser() + if err != nil { + return issueops.CloseBatchResult{}, err + } + return closer.CloseBatch(ctx, request) +} + +// closeDirectRefusal spells one item's typed refusal the way this route has +// always spelled it. The vocabulary is matched with errors.Is rather than by +// reading the message, which is the point of the outcome carrying a typed error +// at all. +// +// Both close-policy refusals print BARE, because each error already names its +// own subject: ErrCloseBlocked names the blockers and gets the --force hint +// appended, and CloseOpenChildrenError's message is character for character the +// line this route used to compose before the guard moved into the transaction. +// Everything else is an unexpected failure and is reported against the id. +func closeDirectRefusal(id string, err error) string { + switch { + case errors.Is(err, storage.ErrCloseBlocked): + return fmt.Sprintf("%v (use --force to override)", err) + case errors.Is(err, storage.ErrCloseOpenChildren): + return err.Error() + default: + return fmt.Sprintf("Error closing %s: %v", id, err) + } +} diff --git a/cmd/bd/close_embedded_test.go b/cmd/bd/close_embedded_test.go index 3ed1e0b63..4f5614338 100644 --- a/cmd/bd/close_embedded_test.go +++ b/cmd/bd/close_embedded_test.go @@ -221,6 +221,60 @@ func TestEmbeddedClose(t *testing.T) { } }) + // The direct route's mirror of the proxied route's + // single_transaction_dolt_commit oracle. N ids are ONE request, and the + // request is the transaction boundary, so they land as one transaction with + // one Dolt commit whose message names every id that landed. Before `bd close` + // moved onto the BatchCloser role this route wrote one commit per id, each + // titled "bd: close issue". + t.Run("close_multiple_ids_single_dolt_commit", func(t *testing.T) { + // Isolated store so the commit count is deterministic, mirroring + // close_already_closed_claim_next. + sdir, sbeads, _ := bdInit(t, bd, "--prefix", "sb") + readLog := func() (int, string) { + dataDir := filepath.Join(sbeads, "embeddeddolt") + cfg, _ := configfile.Load(sbeads) + database := "" + if cfg != nil { + database = cfg.GetDoltDatabase() + } + db, cleanup, err := embeddeddolt.OpenSQL(t.Context(), dataDir, database, "main") + if err != nil { + t.Fatalf("OpenSQL: %v", err) + } + defer cleanup() + var count int + if err := db.QueryRowContext(t.Context(), "SELECT COUNT(*) FROM dolt_log").Scan(&count); err != nil { + t.Fatalf("query dolt_log: %v", err) + } + var message string + if err := db.QueryRowContext(t.Context(), "SELECT message FROM dolt_log ORDER BY date DESC LIMIT 1").Scan(&message); err != nil { + t.Fatalf("query latest dolt_log message: %v", err) + } + return count, message + } + + a := bdCreate(t, bd, sdir, "Batch commit A", "--type", "task") + b := bdCreate(t, bd, sdir, "Batch commit B", "--type", "task") + c := bdCreate(t, bd, sdir, "Batch commit C", "--type", "task") + + before, _ := readLog() + bdClose(t, bd, sdir, a.ID, b.ID, c.ID) + after, message := readLog() + + if got := after - before; got != 1 { + t.Errorf("dolt commits for a 3-id close = %d, want 1: the request is the transaction boundary", got) + } + if !strings.HasPrefix(message, "bd: close ") { + t.Errorf("commit message = %q, want it to start with %q", message, "bd: close ") + } + for _, id := range []string{a.ID, b.ID, c.ID} { + if !strings.Contains(message, id) { + t.Errorf("commit message %q should name %s: the entry names what landed", message, id) + } + } + }) + t.Run("close_already_closed_continue_advances", func(t *testing.T) { // Isolated store so molecule progress and the Dolt commit count are // deterministic, mirroring close_already_closed_claim_next. @@ -319,21 +373,25 @@ func TestEmbeddedClose(t *testing.T) { next := bdCreate(t, bd, cdir, "Reclose claim next", "--type", "task") bdClose(t, bd, cdir, target.ID) // real close; `next` is now the only ready issue - // Re-close the already-closed target with --claim-next: the retry-safe claim - // must still fire and claim the next ready issue. + // Re-close the already-closed target with --claim-next. The claim does NOT + // fire: bd-yby99.19 adjudicated that a batch whose items were all already + // closed mutated nothing, so it earns no claim and mints no commit + // (issueops/batchcloser.go, "CHANGED IS THE TEST"). This subtest used to + // assert the opposite as a retry-safety property — a crashed agent + // re-running `bd close X --claim-next` got its next work item — and that + // property is what the adjudication traded away; bd-yby99.30 carries it. beforeCommits := countCommits() _ = bdClose(t, bd, cdir, target.ID, "--claim-next") got := bdShow(t, bd, cdir, next.ID) - if got.Status != types.StatusInProgress || got.Assignee == "" { - t.Errorf("expected next issue %s claimed (in_progress, assigned) after already-closed --claim-next, got status=%s assignee=%q", + if got.Status != types.StatusOpen || got.Assignee != "" { + t.Errorf("next issue %s = (status=%s assignee=%q) after an already-closed --claim-next, want it untouched: the re-close closed nothing, so the claim was never earned", next.ID, got.Status, got.Assignee) } - // The claim is a real mutation, so the already-closed re-close must still - // persist it with a Dolt commit — not leave it dangling in the working set - // (the close itself is a no-op, so only the claim drives the commit). - if afterCommits := countCommits(); afterCommits <= beforeCommits { - t.Errorf("expected a Dolt commit for the --claim-next claim on an already-closed re-close: before=%d after=%d", + // Nothing landed, so nothing is committed either — the shape the + // adjudication names, a commit that changed nothing. + if afterCommits := countCommits(); afterCommits != beforeCommits { + t.Errorf("dolt_log went %d -> %d across an already-closed re-close that claimed nothing, want no commit", beforeCommits, afterCommits) } }) diff --git a/cmd/bd/close_proxied_server.go b/cmd/bd/close_proxied_server.go index a7ffcd06b..a2b02665e 100644 --- a/cmd/bd/close_proxied_server.go +++ b/cmd/bd/close_proxied_server.go @@ -17,6 +17,7 @@ import ( "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" "github.com/steveyegge/beads/internal/workapi" + "github.com/steveyegge/beads/issueops" ) type closeProxiedInput struct { @@ -29,6 +30,23 @@ type closeProxiedInput struct { jsonOut bool } +// closeProxiedPreflight is the CLI's own close policy, decided before the +// batch runs: the template/pin/assignee fence, the epic open-children refusal +// and machine-checkable gates. None of the three is library policy — they are +// `bd close`'s, they read the issue and nothing else, and the role has no +// vocabulary for them — so they stay here and the batch is handed only the +// items that survived them. +// +// errors is indexed by ARGUMENT position, not by item, so a refusal reported +// here and one reported by the batch still print in the order the caller typed +// the ids. +type closeProxiedPreflight struct { + items []issueops.BatchCloseItem + itemArgs []int + before map[string]*types.Issue + errors []string +} + type closeProxiedOutcome struct { id string before *types.Issue @@ -38,15 +56,13 @@ type closeProxiedOutcome struct { auditReason string } -type closeProxiedTxResult struct { - outcomes []closeProxiedOutcome - reasons []string - unblocked []*types.Issue - continueResult *ContinueResult - claimedNextIssue *types.Issue - errors []string - warnings []string - autoClosedMol *types.Issue +// closeProxiedPostClose is the work `bd close` does AFTER the closes have +// landed: molecule auto-close, --suggest-next and --continue. +type closeProxiedPostClose struct { + unblocked []*types.Issue + continueResult *ContinueResult + autoClosedMol *types.Issue + warnings []string } func runCloseProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error { @@ -76,64 +92,47 @@ func runCloseProxiedServer(cmd *cobra.Command, ctx context.Context, args []strin return HandleError("proxied-server UOW provider not initialized") } - res, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (closeProxiedTxResult, string, error) { - var result closeProxiedTxResult - - for i, id := range args { - reason := reasonForCloseIndex(reasons, i) - outcome, ok := closeProxiedOne(ctx, uw, id, reason, in, &result.errors) - if ok { - mol := autoCloseProxiedCompletedMolecule(ctx, uw, id, actor, in.session, &result.warnings) - if mol != nil { - result.autoClosedMol = mol - } - result.outcomes = append(result.outcomes, outcome) - result.reasons = append(result.reasons, reason) - } - } - - if in.suggestNext && len(args) == 1 && len(result.outcomes) > 0 { - unblocked, warn := closeProxiedSuggestNext(ctx, uw, args[0]) - result.unblocked = unblocked - if warn != "" { - result.warnings = append(result.warnings, warn) - } - } - - if in.continueOn && len(args) == 1 && len(result.outcomes) > 0 { - cont, warn := closeProxiedContinue(ctx, uw, args[0], !in.noAuto) - result.continueResult = cont - if warn != "" { - result.warnings = append(result.warnings, warn) - } - } - - if in.claimNext && len(result.outcomes) > 0 && !in.continueOn { - claimed, warn := closeProxiedClaimNext(ctx, uw) - result.claimedNextIssue = claimed - if warn != "" { - result.warnings = append(result.warnings, warn) - } - } - - if len(result.outcomes) == 0 { - return result, "", nil - } - - return result, closeProxiedCommitMessage(result.outcomes, result.claimedNextIssue, result.continueResult), nil - }) + pre, err := closeProxiedRunPreflight(ctx, args, reasons, in) if err != nil { return HandleErrorRespectJSON("%v", err) } - for _, e := range res.errors { - fmt.Fprintln(os.Stderr, e) + // THE BATCH. One request, one transaction, one Dolt commit over N ids — + // and the request is the only thing that says where the transaction ends, + // because the role hands out no handle to hold open. The commit message is + // the role's, and it names what LANDED, which is what this route's own + // message did: a skipped id stays out of the log. + var result issueops.CloseBatchResult + if len(pre.items) > 0 { + closer, cerr := proxiedBatchCloser() + if cerr != nil { + return HandleErrorRespectJSON("%v", cerr) + } + result, err = closer.CloseBatch(ctx, issueops.CloseBatchRequest{ + Actor: actor, + Items: pre.items, + Session: in.session, + Force: in.force, + ClaimNext: closeClaimNextRequest(in.claimNext, in.continueOn), + }) + if err != nil { + return HandleErrorRespectJSON("%v", err) + } } - for _, w := range res.warnings { + + outcomes, closeReasons := closeProxiedOutcomes(&pre, result) + post := closeProxiedRunPostClose(ctx, args, in, outcomes) + + for _, e := range pre.errors { + if e != "" { + fmt.Fprintln(os.Stderr, e) + } + } + for _, w := range post.warnings { fmt.Fprintf(os.Stderr, "Warning: %s\n", w) } - for i, o := range res.outcomes { + for i, o := range outcomes { if o.closed { audit.LogFieldChange(o.id, "status", o.auditOld, "closed", actor, o.auditReason) if err := fireProxiedCloseHooks(ctx, o.before, o.after); err != nil { @@ -141,48 +140,53 @@ func runCloseProxiedServer(cmd *cobra.Command, ctx context.Context, args []strin } } if !in.jsonOut { - fmt.Printf("%s Closed %s: %s\n", ui.RenderPass("✓"), formatFeedbackID(o.after.ID, o.after.Title), res.reasons[i]) + fmt.Printf("%s Closed %s: %s\n", ui.RenderPass("✓"), formatFeedbackID(o.after.ID, o.after.Title), closeReasons[i]) } } + var claimedNextIssue *types.Issue + if result.ClaimedNext != nil { + claimedNextIssue = result.ClaimedNext.Issue + } + if !in.jsonOut { - if res.autoClosedMol != nil { - fmt.Printf("%s Auto-closed completed molecule %s\n", ui.RenderPass("✓"), formatFeedbackID(res.autoClosedMol.ID, res.autoClosedMol.Title)) + if post.autoClosedMol != nil { + fmt.Printf("%s Auto-closed completed molecule %s\n", ui.RenderPass("✓"), formatFeedbackID(post.autoClosedMol.ID, post.autoClosedMol.Title)) } - if len(res.unblocked) > 0 { + if len(post.unblocked) > 0 { fmt.Printf("\nNewly unblocked:\n") - for _, issue := range res.unblocked { + for _, issue := range post.unblocked { fmt.Printf(" • %s (P%d)\n", formatFeedbackID(issue.ID, issue.Title), issue.Priority) } } - if res.continueResult != nil { - PrintContinueResult(res.continueResult) + if post.continueResult != nil { + PrintContinueResult(post.continueResult) } - if res.claimedNextIssue != nil { - fmt.Printf("%s Auto-claimed next ready issue: %s (P%d)\n", ui.RenderPass("✓"), formatFeedbackID(res.claimedNextIssue.ID, res.claimedNextIssue.Title), res.claimedNextIssue.Priority) - } else if in.claimNext && len(res.outcomes) > 0 && !in.continueOn { + if claimedNextIssue != nil { + fmt.Printf("%s Auto-claimed next ready issue: %s (P%d)\n", ui.RenderPass("✓"), formatFeedbackID(claimedNextIssue.ID, claimedNextIssue.Title), claimedNextIssue.Priority) + } else if in.claimNext && len(outcomes) > 0 && !in.continueOn { fmt.Printf("\n%s No ready issues available to claim.\n", ui.RenderWarn("✨")) } } - if in.jsonOut && len(res.outcomes) > 0 { - closedIssues := make([]*types.Issue, len(res.outcomes)) - for i, o := range res.outcomes { + if in.jsonOut && len(outcomes) > 0 { + closedIssues := make([]*types.Issue, len(outcomes)) + for i, o := range outcomes { closedIssues[i] = o.after } switch { - case len(res.unblocked) > 0: - _ = outputJSON(map[string]interface{}{"closed": closedIssues, "unblocked": res.unblocked}) - case res.continueResult != nil: - _ = outputJSON(map[string]interface{}{"closed": closedIssues, "continue": res.continueResult}) - case res.claimedNextIssue != nil: - _ = outputJSON(map[string]interface{}{"closed": closedIssues, "claimed": res.claimedNextIssue}) + case len(post.unblocked) > 0: + _ = outputJSON(map[string]interface{}{"closed": closedIssues, "unblocked": post.unblocked}) + case post.continueResult != nil: + _ = outputJSON(map[string]interface{}{"closed": closedIssues, "continue": post.continueResult}) + case claimedNextIssue != nil: + _ = outputJSON(map[string]interface{}{"closed": closedIssues, "claimed": claimedNextIssue}) default: _ = outputJSON(closedIssues) } } - if len(args) > 0 && len(res.outcomes) == 0 { + if len(args) > 0 && len(outcomes) == 0 { return SilentExit() } return nil @@ -203,97 +207,200 @@ func gatherCloseProxiedInput(cmd *cobra.Command) closeProxiedInput { return in } -func closeProxiedOne(ctx context.Context, uw uow.UnitOfWork, id, reason string, in closeProxiedInput, errs *[]string) (closeProxiedOutcome, bool) { - current, isWisp, err := workapi.GetIssueOrWisp(ctx, workapi.NewUOWDetailSource(uw), id) +// proxiedBatchCloser hands back the guarded close-many surface for the +// proxied-server provider, through the provider's OWN capability accessor — +// the same two-step proxiedIssueReader performs, and for the same reason: the +// accessor is where each layer is added, so a command that reached for the +// constructor would get an unlayered closer. +func proxiedBatchCloser() (issueops.BatchCloser, error) { + if uowProvider == nil { + return nil, errors.New("proxied-server UOW provider not initialized") + } + src, ok := uowProvider.(uow.BatchCloserSource) + if !ok { + return nil, fmt.Errorf("proxied-server provider %T does not offer the batch-close surface", uowProvider) + } + return src.BatchCloser() +} + +// closeProxiedRunPreflight resolves every argument and applies the CLI's own +// close policy to it, in one read-only unit of work. +func closeProxiedRunPreflight(ctx context.Context, args, reasons []string, in closeProxiedInput) (closeProxiedPreflight, error) { + pre := closeProxiedPreflight{ + errors: make([]string, len(args)), + before: make(map[string]*types.Issue, len(args)), + } + _, err := uow.RunTxRead(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (struct{}, error) { + for i, id := range args { + refusal, current := closeProxiedCheckOne(ctx, uw, id, in) + if refusal != "" { + pre.errors[i] = refusal + continue + } + pre.before[id] = current + pre.items = append(pre.items, issueops.BatchCloseItem{IssueID: id, Reason: reasonForCloseIndex(reasons, i)}) + pre.itemArgs = append(pre.itemArgs, i) + } + return struct{}{}, nil + }) + return pre, err +} + +// closeProxiedCheckOne returns one id's refusal, or "" and the resolved +// pre-close issue. +func closeProxiedCheckOne(ctx context.Context, uw uow.UnitOfWork, id string, in closeProxiedInput) (string, *types.Issue) { + current, _, err := workapi.GetIssueOrWisp(ctx, workapi.NewUOWDetailSource(uw), id) if errors.Is(err, storage.ErrNotFound) { - *errs = append(*errs, fmt.Sprintf("Issue %s not found", id)) - return closeProxiedOutcome{}, false + return fmt.Sprintf("Issue %s not found", id), nil } if err != nil { - *errs = append(*errs, fmt.Sprintf("Error resolving %s: %v", id, err)) - return closeProxiedOutcome{}, false + return fmt.Sprintf("Error resolving %s: %v", id, err), nil } - // Mirrors the ordering in cmd/bd/close.go (ga-ktn9pe.4.8): a row already at + // Mirrors the ordering in closeDirectCheckOne (ga-ktn9pe.4.8): a row already at // literal StatusClosed has no state change for close validation to guard, so // the re-close skips it and reaches the engine as the idempotent no-op it has // always been. Both close paths must agree here — diverging is the defect // class #5217 closed. if current.Status != types.StatusClosed { if err := validateIssueClosable(id, current, actor, in.force); err != nil { - *errs = append(*errs, err.Error()) - return closeProxiedOutcome{}, false + return err.Error(), nil } } - if !in.force && current.IssueType == types.TypeEpic { - var openChildren int - var cerr error - if isWisp { - openChildren, cerr = uw.IssueUseCase().CountOpenWispChildren(ctx, id) - } else { - openChildren, cerr = uw.IssueUseCase().CountOpenChildren(ctx, id) - } - if cerr == nil && openChildren > 0 { - *errs = append(*errs, fmt.Sprintf("cannot close epic %s: %d open child issue(s); close children first or use --force to override", id, openChildren)) - return closeProxiedOutcome{}, false - } - } + // The open-children guard is deliberately NOT pre-checked here. It lives in + // the close transaction, which is the only place it can be race-free, and + // it answers for every parent rather than only epics — this pre-check was + // epic-only, so a non-epic parent got a different refusal on this route + // than on the direct one. closeDirectCheckOne dropped its copy for the same + // reason; closeProxiedRefusal surfaces the engine's CloseOpenChildrenError + // unprefixed, so both routes now spell one refusal one way. if !in.force { if err := checkGateSatisfaction(current); err != nil { - *errs = append(*errs, fmt.Sprintf("cannot close %s: %s", id, err)) - return closeProxiedOutcome{}, false + return fmt.Sprintf("cannot close %s: %s", id, err), nil } } - params := domain.CloseIssueParams{Reason: reason, Session: in.session} - var res domain.CloseIssueResult - // The is_blocked guard lives in the library's checked close, so the embedded - // and proxied paths converge on storage.ErrCloseBlocked and its message. The - // guard and the close share this unit-of-work transaction. - if isWisp { - res, err = uw.IssueUseCase().CloseWispChecked(ctx, id, params, actor, in.force) - } else { - res, err = uw.IssueUseCase().CloseIssueChecked(ctx, id, params, actor, in.force) - } - if err != nil { - if errors.Is(err, storage.ErrCloseBlocked) { - *errs = append(*errs, fmt.Sprintf("%v (use --force to override)", err)) - } else { - *errs = append(*errs, fmt.Sprintf("Error closing %s: %v", id, err)) - } - return closeProxiedOutcome{}, false - } - - oldStatus := string(current.Status) - if oldStatus == "" { - oldStatus = "open" - } - - return closeProxiedOutcome{ - id: id, - before: current, - after: res.Issue, - closed: res.Closed, - auditOld: oldStatus, - auditReason: reason, - }, true + return "", current } -func closeProxiedCommitMessage(outcomes []closeProxiedOutcome, claimed *types.Issue, cont *ContinueResult) string { - ids := make([]string, 0, len(outcomes)) - for _, o := range outcomes { - ids = append(ids, o.id) +// closeProxiedOutcomes folds the batch's per-item outcomes back onto the +// argument list: a refusal lands in its argument's own error slot so the +// stderr report stays in typed order, and the survivors keep the shape the +// display block has always consumed. +func closeProxiedOutcomes(pre *closeProxiedPreflight, result issueops.CloseBatchResult) ([]closeProxiedOutcome, []string) { + var outcomes []closeProxiedOutcome + var reasons []string + for j, outcome := range result.Outcomes { + item := pre.items[j] + if outcome.Err != nil { + pre.errors[pre.itemArgs[j]] = closeProxiedRefusal(item.IssueID, outcome.Err) + continue + } + before := pre.before[item.IssueID] + oldStatus := "open" + if before != nil && before.Status != "" { + oldStatus = string(before.Status) + } + after := outcome.Issue + if after != nil { + // `bd close` has never printed dependency records, on either + // route: the direct route drops them from the operation's own + // snapshot for exactly this reason. + after.Dependencies = nil + } + outcomes = append(outcomes, closeProxiedOutcome{ + id: item.IssueID, + before: before, + after: after, + closed: outcome.Changed, + auditOld: oldStatus, + auditReason: item.Reason, + }) + reasons = append(reasons, item.Reason) } - msg := "bd: close " + strings.Join(ids, ", ") - if cont != nil && cont.AutoAdvanced && cont.NextStep != nil { - msg += "; advance to " + cont.NextStep.ID + return outcomes, reasons +} + +// closeProxiedRefusal spells one item's typed refusal the way this route has +// always spelled it. The vocabulary is matched with errors.Is rather than by +// reading the message, which is the point of the outcome carrying a typed +// error at all. +func closeProxiedRefusal(id string, err error) string { + switch { + case errors.Is(err, storage.ErrCloseBlocked): + return fmt.Sprintf("%v (use --force to override)", err) + // The open-children refusal is already a complete sentence naming the + // issue and its count, so it passes through unprefixed — exactly as + // closeDirectRefusal spells it. Without this arm the two routes answer the + // same refusal differently, which is the drift this branch exists to + // remove; it became newly reachable here when the guard moved into the + // transaction. + case errors.Is(err, storage.ErrCloseOpenChildren): + return err.Error() + case errors.Is(err, storage.ErrNotFound): + return fmt.Sprintf("Issue %s not found", id) + default: + return fmt.Sprintf("Error closing %s: %v", id, err) } - if claimed != nil { - msg += "; claim " + claimed.ID +} + +// closeProxiedRunPostClose runs molecule auto-close, --suggest-next and +// --continue once the closes have committed. +// +// They are outside the batch's transaction because they are outside its +// contract, and outside is where the direct route has always run them: it +// calls autoCloseCompletedMolecule and AdvanceToNextStep after ops.Close +// returns, each in its own write. The visible consequence is a SECOND Dolt +// commit when a molecule actually auto-closes or --continue actually advances. +// A plain close writes nothing in this pass, names no commit message, and +// therefore still produces exactly one commit for the command. +func closeProxiedRunPostClose(ctx context.Context, args []string, in closeProxiedInput, outcomes []closeProxiedOutcome) closeProxiedPostClose { + if len(outcomes) == 0 { + return closeProxiedPostClose{} } - return msg + + post, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (closeProxiedPostClose, string, error) { + var out closeProxiedPostClose + var wrote []string + + for _, o := range outcomes { + mol := autoCloseProxiedCompletedMolecule(ctx, uw, o.id, actor, in.session, &out.warnings) + if mol != nil { + out.autoClosedMol = mol + wrote = append(wrote, "auto-close "+mol.ID) + } + } + + if in.suggestNext && len(args) == 1 { + unblocked, warn := closeProxiedSuggestNext(ctx, uw, args[0]) + out.unblocked = unblocked + if warn != "" { + out.warnings = append(out.warnings, warn) + } + } + + if in.continueOn && len(args) == 1 { + cont, warn := closeProxiedContinue(ctx, uw, args[0], !in.noAuto) + out.continueResult = cont + if warn != "" { + out.warnings = append(out.warnings, warn) + } + if cont != nil && cont.AutoAdvanced && cont.NextStep != nil { + wrote = append(wrote, "advance to "+cont.NextStep.ID) + } + } + + if len(wrote) == 0 { + return out, "", nil + } + return out, "bd: " + strings.Join(wrote, "; "), nil + }) + if err != nil { + post.warnings = append(post.warnings, fmt.Sprintf("post-close work failed: %v", err)) + } + return post } func fireProxiedCloseHooks(ctx context.Context, before, after *types.Issue) error { @@ -326,26 +433,6 @@ func closeProxiedSuggestNext(ctx context.Context, uw uow.UnitOfWork, closedID st return unblocked, "" } -func closeProxiedClaimNext(ctx context.Context, uw uow.UnitOfWork) (*types.Issue, string) { - page, err := uw.IssueUseCase().GetReadyWork(ctx, types.WorkFilter{ - Status: "open", - Limit: 1, - SortPolicy: types.SortPolicy("priority"), - }) - if err != nil { - return nil, fmt.Sprintf("could not get ready issues: %v", err) - } - if len(page.Items) == 0 { - return nil, "" - } - - nextIssue := page.Items[0] - if _, err := uw.IssueUseCase().ClaimIssue(ctx, nextIssue.ID, actor); err != nil { - return nil, fmt.Sprintf("could not claim next issue %s: %v", nextIssue.ID, err) - } - return nextIssue, "" -} - func closeProxiedContinue(ctx context.Context, uw uow.UnitOfWork, closedID string, autoClaim bool) (*ContinueResult, string) { result, err := AdvanceToNextStep(ctx, newUOWMolWriter(uw), closedID, autoClaim, actor) if err != nil { diff --git a/cmd/bd/comment.go b/cmd/bd/comment.go index cd8a3c049..6f5aed876 100644 --- a/cmd/bd/comment.go +++ b/cmd/bd/comment.go @@ -96,7 +96,7 @@ Examples: return HandleErrorRespectJSON("%s", err) } - comment, err := issueStore.AddIssueComment(ctx, result.ResolvedID, author, commentText) + comment, err := addCommentDirect(ctx, issueStore, result.ResolvedID, author, commentText) if err != nil { return HandleErrorRespectJSON("adding comment: %v", err) } diff --git a/cmd/bd/comments.go b/cmd/bd/comments.go index 5b3ef7cbf..5e0de6362 100644 --- a/cmd/bd/comments.go +++ b/cmd/bd/comments.go @@ -1,14 +1,17 @@ package main import ( + "context" "fmt" "os" "strings" "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/metrics" + "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/uimd" + "github.com/steveyegge/beads/issueops" ) // validateCommentsArgs runs as cobra's Args validation for the parent @@ -236,7 +239,7 @@ Examples: defer result.Close() issueID = result.ResolvedID - comment, err := result.Store.AddIssueComment(ctx, issueID, author, commentText) + comment, err := addCommentDirect(ctx, result.Store, issueID, author, commentText) if err != nil { return HandleErrorRespectJSON("adding comment: %v", err) } @@ -256,6 +259,50 @@ Examples: }, } +// addCommentDirect appends one comment through the Commenter role and returns +// the stored comment. It is the direct-route sibling of addCommentProxied and +// builds the SAME request, so the two front doors ask the storage layer one +// question. +// +// The role is reached through the STORE's own accessor, never a constructor: +// that accessor is where the store's decorator stack — hooks, telemetry — adds +// its layer, so a comment written here fires the same hook a comment written +// through the provider does. The store is the caller's rather than the global +// one, because a prefix-routed write has to reach the role through the store +// that actually holds the issue. +// +// The RESOLVE stays with the caller. On this route it is fuzzy, prefix-routed +// and cross-repo, none of which belongs on a contract an unattended client also +// calls, and the caller has already produced the canonical id. The role runs +// the issue-then-wisp fallback itself, so the comment lands on the plane the id +// actually names. +// +// The auto-commit policy is applied HERE rather than by each caller. The role +// creates its Dolt version commit inside the storage layer, so +// `--dolt-auto-commit batch` can only defer it by saying so on the context — +// the reason issueOpsContext exists — and a caller that forgets writes exactly +// the per-write commit batch mode is there to avoid. Both comment commands come +// through this function, so the policy is stated once. +func addCommentDirect(ctx context.Context, st storage.DoltStorage, issueID, author, text string) (*types.Comment, error) { + opsCtx, err := issueOpsContext(ctx) + if err != nil { + return nil, err + } + commenter, err := st.Commenter() + if err != nil { + return nil, err + } + result, err := commenter.AddComment(opsCtx, issueops.AddCommentRequest{ + Author: author, + IssueID: issueID, + Text: text, + }) + if err != nil { + return nil, err + } + return result.Comment, nil +} + func init() { commentsCmd.AddCommand(commentsMisplacedListCmd) commentsCmd.AddCommand(commentsAddCmd) diff --git a/cmd/bd/comments_proxied_server.go b/cmd/bd/comments_proxied_server.go index 451160666..aa84e0911 100644 --- a/cmd/bd/comments_proxied_server.go +++ b/cmd/bd/comments_proxied_server.go @@ -16,6 +16,7 @@ import ( "github.com/steveyegge/beads/internal/ui" "github.com/steveyegge/beads/internal/uimd" "github.com/steveyegge/beads/internal/workapi" + "github.com/steveyegge/beads/issueops" ) func runCommentsProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error { @@ -154,42 +155,70 @@ func runCommentsAddProxiedServer(cmd *cobra.Command, ctx context.Context, args [ return nil } -type addCommentProxiedResult struct { - comment *types.Comment - issue *types.Issue +// proxiedCommenter hands back the guarded add-comment surface for the +// proxied-server provider, through the provider's OWN capability accessor — +// the same two-step proxiedIssueReader performs, and for the same reason: the +// accessor is where each layer is added. +func proxiedCommenter() (issueops.Commenter, error) { + if uowProvider == nil { + return nil, errors.New("proxied-server UOW provider not initialized") + } + src, ok := uowProvider.(uow.CommenterSource) + if !ok { + return nil, fmt.Errorf("proxied-server provider %T does not offer the add-comment surface", uowProvider) + } + return src.Commenter() } +// addCommentProxied appends one comment through the Commenter role and returns +// it with the issue it landed on. +// +// The RESOLVE stays here, in a read-only pre-flight, for the reason the +// proxied close keeps its own policy pre-flight: `bd comment` refuses a +// template, and refusing a template is not library policy. The pre-flight is +// also where the TITLE comes from — the confirmation line prints it, and a +// result type carrying presentation for one front door is a result type that +// grows one field per front door. The role is handed the canonical id the +// pre-flight resolved, exactly as `bd show` hands Reader.Get one. func addCommentProxied(ctx context.Context, id, author, text string) (*types.Comment, *types.Issue, error) { - if uowProvider == nil { - return nil, nil, HandleError("proxied-server UOW provider not initialized") - } - res, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (addCommentProxiedResult, string, error) { - issue, isWisp, rerr := workapi.GetIssueOrWisp(ctx, workapi.NewUOWDetailSource(uw), id) - if errors.Is(rerr, storage.ErrNotFound) { - return addCommentProxiedResult{}, "", fmt.Errorf("issue %s not found", id) - } - if rerr != nil { - return addCommentProxiedResult{}, "", fmt.Errorf("resolving %s: %w", id, rerr) - } - if err := validateIssueUpdatable(id, issue); err != nil { - return addCommentProxiedResult{}, "", err - } - var ( - comment *types.Comment - cerr error - ) - if isWisp { - comment, cerr = uw.CommentUseCase().AddCommentToWisp(ctx, issue.ID, author, text) - } else { - comment, cerr = uw.CommentUseCase().AddCommentToIssue(ctx, issue.ID, author, text) - } - if cerr != nil { - return addCommentProxiedResult{}, "", fmt.Errorf("adding comment: %w", cerr) - } - return addCommentProxiedResult{comment: comment, issue: issue}, fmt.Sprintf("bd: comment %s", issue.ID), nil - }) + issue, err := resolveCommentTargetProxied(ctx, id) if err != nil { return nil, nil, err } - return res.comment, res.issue, nil + commenter, err := proxiedCommenter() + if err != nil { + return nil, nil, err + } + result, err := commenter.AddComment(ctx, issueops.AddCommentRequest{ + Author: author, + IssueID: issue.ID, + Text: text, + }) + if err != nil { + return nil, nil, fmt.Errorf("adding comment: %w", err) + } + return result.Comment, issue, nil +} + +// resolveCommentTargetProxied resolves the anchor and applies the CLI's own +// pre-flight policy. It reads in a unit of work of its own and writes nothing, +// so the role's request stays the whole of the transaction. +func resolveCommentTargetProxied(ctx context.Context, id string) (*types.Issue, error) { + uw, err := proxiedOpenReadUOW(ctx) + if err != nil { + return nil, err + } + defer uw.Close(ctx) + + issue, _, err := workapi.GetIssueOrWisp(ctx, workapi.NewUOWDetailSource(uw), id) + if errors.Is(err, storage.ErrNotFound) { + return nil, fmt.Errorf("issue %s not found", id) + } + if err != nil { + return nil, fmt.Errorf("resolving %s: %w", id, err) + } + if err := validateIssueUpdatable(id, issue); err != nil { + return nil, err + } + return issue, nil } diff --git a/cmd/bd/create_deps.go b/cmd/bd/create_deps.go index 222449193..f62dbece0 100644 --- a/cmd/bd/create_deps.go +++ b/cmd/bd/create_deps.go @@ -182,8 +182,8 @@ func canonicalDependencyType(t types.DependencyType) types.DependencyType { // commands stay in lockstep. func validateDependencyType(t types.DependencyType) error { if !t.IsValid() { - return fmt.Errorf("invalid dependency type %q (must be non-empty, max 50 chars); valid types: %s", - t, createDepsAcceptedTypeList()) + return fmt.Errorf("invalid dependency type %q (must be non-empty, max %d chars); valid types: %s", + t, types.MaxDependencyTypeLen, createDepsAcceptedTypeList()) } if !t.IsWellKnown() { return fmt.Errorf("unknown dependency type %q; valid types: %s", diff --git a/cmd/bd/dep.go b/cmd/bd/dep.go index 812b26608..0aa07e659 100644 --- a/cmd/bd/dep.go +++ b/cmd/bd/dep.go @@ -14,12 +14,37 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage" - "github.com/steveyegge/beads/internal/storage/domain" - "github.com/steveyegge/beads/internal/storage/issueops" + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" + "github.com/steveyegge/beads/issueops" ) +// addDependencyEdgesDirect asserts edges through the DependencyEditor role on +// st — the store that owns the source issue. +// +// It is addDependencyEdgesProxied's twin, and reaches the role the same way: +// through the ACCESSOR, never a constructor, because the accessor is where each +// storage decorator adds its layer. Built per write site rather than once per +// command, for the reason writeOps gives — a routed source hands back an editor +// carrying its own stack. +// +// skipPerEdgeCycleCheck is a separate argument from the --no-cycle-check flag +// for the reason the proxied twin states: only the bulk path trades the +// per-edge probe away. +func addDependencyEdgesDirect(ctx context.Context, st storage.DoltStorage, edges []issueops.DependencyEdge, skipPerEdgeCycleCheck bool) error { + editor, err := st.DependencyEditor() + if err != nil { + return err + } + _, err = editor.AddDependencies(ctx, issueops.AddDependenciesRequest{ + Actor: actor, + Edges: edges, + SkipPerEdgeCycleCheck: skipPerEdgeCycleCheck, + }) + return err +} + // exactDependencyTarget returns the depends_on_id of a raw dependency edge on // issueID that equals rawTarget exactly. Used by `bd dep remove` so a bare // slug that was stored verbatim (pre-GH#5005 create --deps bug) is removed @@ -218,13 +243,12 @@ Examples: return HandleErrorRespectJSON("cannot add dependency: %s is already a child of %s. Children inherit dependency on parent completion via hierarchy. Adding an explicit dependency would create a deadlock", fromID, toID) } - dep := &types.Dependency{ - IssueID: fromID, - DependsOnID: toID, - Type: types.DependencyType(depType), + opsCtx, err := issueOpsContext(ctx) + if err != nil { + return HandleErrorRespectJSON("%v", err) } - - if err := fromStore.AddDependencyWithOptions(ctx, dep, actor, storage.DependencyAddOptions{EmitEvent: true}); err != nil { + edge := issueops.DependencyEdge{IssueID: fromID, DependsOnID: toID, Type: types.DependencyType(depType)} + if err := addDependencyEdgesDirect(opsCtx, fromStore, []issueops.DependencyEdge{edge}, false); err != nil { return HandleErrorRespectJSON("%v", err) } @@ -407,13 +431,12 @@ Examples: return HandleErrorRespectJSON("%v", err) } - dep := &types.Dependency{ - IssueID: fromID, - DependsOnID: toID, - Type: dt, + opsCtx, err := issueOpsContext(ctx) + if err != nil { + return HandleErrorRespectJSON("%v", err) } - - if err := fromStore.AddDependencyWithOptions(ctx, dep, actor, storage.DependencyAddOptions{EmitEvent: true}); err != nil { + edge := issueops.DependencyEdge{IssueID: fromID, DependsOnID: toID, Type: dt} + if err := addDependencyEdgesDirect(opsCtx, fromStore, []issueops.DependencyEdge{edge}, false); err != nil { return HandleErrorRespectJSON("%v", err) } @@ -452,28 +475,6 @@ type bulkDepInput struct { DependsOnID string `json:"depends_on_id"` } -// newCycleThroughEdges runs a whole-graph cycle check inside the bulk-add -// transaction and returns a rendered scheduling-cycle path when a cycle actually -// traverses one of the edges being added, or "" when none does. Endpoint -// membership is not enough: an issue sitting in a pre-existing committed -// cycle must not block unrelated bulk wiring that merely touches it -// (bd-578h9.9). Only blocks, conditional-blocks, and parent-child edges -// participate. A failed check returns an error — the bulk add must roll back -// rather than commit unverified edges (bd-6dnrw.8). -func newCycleThroughEdges(ctx context.Context, tx storage.Transaction, edges []bulkDepEdge) (string, error) { - pairs := make([][2]string, 0, len(edges)) - for _, edge := range edges { - if edge.Type != types.DepBlocks && edge.Type != types.DepConditionalBlocks && edge.Type != types.DepParentChild { - continue - } - pairs = append(pairs, [2]string{edge.IssueID, edge.DependsOnID}) - } - if len(pairs) == 0 { - return "", nil - } - return tx.CycleThroughEdges(ctx, pairs) -} - type bulkDepEdge struct { Line int IssueID string @@ -514,10 +515,27 @@ func addBulkDependencies(cmd *cobra.Command, file string, defaultType string) er } noCycleCheck, _ := cmd.Flags().GetBool("no-cycle-check") - commitMsg := fmt.Sprintf("dependency: add %d edges", len(resolved)) - if err := transact(rootCtx, targetStore, commitMsg, func(tx storage.Transaction) error { - return addBulkDependenciesInTx(rootCtx, tx, resolved, noCycleCheck, actor) - }); err != nil { + depEdges := make([]issueops.DependencyEdge, 0, len(resolved)) + for _, edge := range resolved { + depEdges = append(depEdges, issueops.DependencyEdge{ + IssueID: edge.IssueID, + DependsOnID: edge.DependsOnID, + Type: edge.Type, + }) + } + + // One request, one transaction, one history entry. The role's + // all-or-nothing contract is what the hand-rolled bulk transaction used to + // spell out here, down to the parent-child-first ordering and the + // whole-graph gate that runs even when the per-edge probe is off — so the + // request replaces it rather than wrapping it. The version commit comes + // with the role, which is why there is no transact() and no + // commitPendingIfEmbedded around this call. + opsCtx, err := issueOpsContext(rootCtx) + if err != nil { + return err + } + if err := addDependencyEdgesDirect(opsCtx, targetStore, depEdges, noCycleCheck); err != nil { return err } @@ -545,37 +563,6 @@ func addBulkDependencies(cmd *cobra.Command, file string, defaultType string) er return nil } -func addBulkDependenciesInTx(ctx context.Context, tx storage.Transaction, edges []bulkDepEdge, noCycleCheck bool, actor string) error { - // Make the complete planned hierarchy visible before validating any - // blocking edge, independent of input-file order. - for phase := 0; phase < 2; phase++ { - parentPhase := phase == 0 - for _, edge := range edges { - if (edge.Type == types.DepParentChild) != parentPhase { - continue - } - dep := &types.Dependency{IssueID: edge.IssueID, DependsOnID: edge.DependsOnID, Type: edge.Type} - if err := tx.AddDependencyWithOptions(ctx, dep, actor, storage.DependencyAddOptions{SkipCycleCheck: noCycleCheck, EmitEvent: true}); err != nil { - return fmt.Errorf("line %d: %w", edge.Line, err) - } - } - } - // Always merge both transaction snapshots before commit. Per-edge checks - // cannot see uncommitted paths split across regular and wisp storage. - cyclePath, cycleErr := newCycleThroughEdges(ctx, tx, edges) - if cycleErr != nil { - return fmt.Errorf("final cycle check failed (no edges added): %w", cycleErr) - } - if cyclePath != "" { - // Type this rejection so callers can errors.Is(err, domain.ErrDependencyCycle), - // matching the proxied/domain bulk final gate. NewCycleError renders the - // message verbatim (no sentinel text appended), so the user-facing string - // is unchanged. - return domain.NewCycleError("dependency cycle would be created: %s (no edges added; run 'bd dep cycles' for analysis)", cyclePath) - } - return nil -} - func readBulkDepEdges(file string, defaultType string) ([]bulkDepEdge, error) { var r io.Reader var f *os.File @@ -822,6 +809,12 @@ Examples: } }() + // The multi-id edge listing is a different question with a different + // answer shape — raw edge records keyed by source, printed per source — + // and no role describes it: Relations is anchored on ONE issue and + // answers with the issues on the far end of its edges, not with the + // edges themselves. It keeps the batched records read, exactly as the + // proxied route keeps its own unit of work for the same question. if len(resolved) > 1 && direction == "down" { allSameStore := true firstStore := resolved[0].store @@ -872,33 +865,36 @@ Examples: } } - var allIssues []*types.IssueWithDependencyMetadata + // The neighbor query is on the Relations role: one call per anchor, each + // with an explicit direction, because the role refuses to guess one. The + // accessor is taken per resolved anchor rather than once for the command + // — a routed anchor answers from its own store, carrying its own + // decorator stack. + request := issueops.RelatedRequest{Direction: issueops.RelationOut} + if direction == "up" { + request.Direction = issueops.RelationIn + } + if typeFilter != "" { + request.Types = []types.DependencyType{types.DependencyType(typeFilter)} + } + + var allIssues []*issueops.RelatedIssue for _, r := range resolved { - var issues []*types.IssueWithDependencyMetadata - var err error - if direction == "up" { - issues, err = r.store.GetDependentsWithMetadata(ctx, r.fullID) - } else { - issues, err = r.store.GetDependenciesWithMetadata(ctx, r.fullID) - } + rel, err := r.store.IssueRelations() if err != nil { return HandleErrorRespectJSON("%v", err) } - if typeFilter != "" { - var filtered []*types.IssueWithDependencyMetadata - for _, iss := range issues { - if string(iss.DependencyType) == typeFilter { - filtered = append(filtered, iss) - } - } - issues = filtered + request.ID = r.fullID + issues, err := rel.Related(ctx, request) + if err != nil { + return HandleErrorRespectJSON("%v", err) } allIssues = append(allIssues, issues...) } if jsonOutput { if allIssues == nil { - allIssues = []*types.IssueWithDependencyMetadata{} + allIssues = []*issueops.RelatedIssue{} } return outputJSON(allIssues) } @@ -1004,9 +1000,27 @@ var depRemoveCmd = &cobra.Command{ fullFromID := fromID fullToID := toID - // Explicit dep verb: record a dependency_removed history event (parity - // with bd dep add's EmitEvent and the proxied bd dep remove path). - if err := fromStore.RemoveDependencyWithOptions(ctx, fullFromID, fullToID, actor, storage.DependencyRemoveOptions{EmitEvent: true}); err != nil { + // Explicit dep verb: the role records a dependency_removed history entry + // for a genuine removal, matching bd dep add's edge event and the + // proxied bd dep remove path. + // + // The role's Removed verdict is not printed, for the reason the proxied + // route gives: `bd dep remove` has always confirmed the same way whether + // or not an edge was there, and reporting the difference now would + // change what every existing script reads. + editor, err := fromStore.DependencyEditor() + if err != nil { + return HandleErrorRespectJSON("%v", err) + } + opsCtx, err := issueOpsContext(ctx) + if err != nil { + return HandleErrorRespectJSON("%v", err) + } + if _, err := editor.RemoveDependency(opsCtx, issueops.RemoveDependencyRequest{ + Actor: actor, + IssueID: fullFromID, + DependsOnID: fullToID, + }); err != nil { return HandleErrorRespectJSON("%v", err) } @@ -1134,7 +1148,7 @@ node count is checked afterward (post-hoc), not during the walk.`, return err } if treeMaxRows > 0 && len(tree) > treeMaxRows { - if capErr := handleMaxRowsError(&issueops.ErrTooManyRows{ + if capErr := handleMaxRowsError(&storageissueops.ErrTooManyRows{ Found: len(tree), Cap: treeMaxRows, Source: treeMaxRowsSource, diff --git a/cmd/bd/dep_bulk_role_test.go b/cmd/bd/dep_bulk_role_test.go new file mode 100644 index 000000000..9f81c9cac --- /dev/null +++ b/cmd/bd/dep_bulk_role_test.go @@ -0,0 +1,186 @@ +//go:build cgo + +package main + +import ( + "context" + "errors" + "path/filepath" + "testing" + "time" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/storage/dolt" + "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" +) + +// The bulk `bd dep add --file` route asserts its edges through the +// DependencyEditor role, so the invariants the hand-rolled bulk transaction +// used to carry are pinned here against the role the route now calls — entered +// through the store's own accessor, exactly as addDependencyEdgesDirect enters +// it. + +// bd-wg7ve: parent-child edges are applied before blocking ones regardless of +// request order, so the complete planned hierarchy is visible when a blocking +// edge is validated against it. +// +// The ordering is what decides the ANSWER here. Applied hierarchy-first, the +// grandparent is an ancestor of the child by the time `child blocks grand` is +// checked, so the whole request is refused and nothing is written. Applied in +// request order, that blocking edge lands before any hierarchy exists, nothing +// notices, and all three edges commit. +func TestBulkDepAddRoleAppliesHierarchyBeforeBlockingEdges(t *testing.T) { + t.Parallel() + tmpDir := t.TempDir() + s := newTestStore(t, filepath.Join(tmpDir, ".beads", "beads.db")) + ctx := context.Background() + + const grand, parent, child = "test-bulk-order-grand", "test-bulk-order-parent", "test-bulk-order-child" + seedBulkRoleIssues(ctx, t, s, grand, parent, child) + + editor, err := s.DependencyEditor() + if err != nil { + t.Fatalf("DependencyEditor(): %v", err) + } + _, err = editor.AddDependencies(ctx, issueops.AddDependenciesRequest{ + Actor: "tester", + Edges: []issueops.DependencyEdge{ + {IssueID: child, DependsOnID: grand, Type: types.DepBlocks}, + {IssueID: child, DependsOnID: parent, Type: types.DepParentChild}, + {IssueID: parent, DependsOnID: grand, Type: types.DepParentChild}, + }, + }) + var conflict *domain.DependencyHierarchyConflictError + if !errors.As(err, &conflict) { + t.Fatalf("error = %v, want *domain.DependencyHierarchyConflictError: the hierarchy is applied first", err) + } + if !conflict.BlockerIsAncestor { + t.Fatalf("conflict = %#v, want the blocker reported as the child's ancestor", conflict) + } + + for _, id := range []string{child, parent} { + deps, err := s.GetDependencyRecords(ctx, id) + if err != nil { + t.Fatalf("GetDependencyRecords(%s): %v", id, err) + } + if len(deps) != 0 { + t.Fatalf("%s edges after a refused request = %#v, want none: the request is all-or-nothing", id, deps) + } + } +} + +// bd-6dnrw.8: with the per-edge probe off the whole-graph gate is the check +// that actually holds the invariant. Its refusal must roll the request back — +// no cycle may ever commit — and must render the message the bulk route has +// always printed while still matching the typed sentinel. +func TestBulkDepAddRoleWholeGraphGateRollsBack(t *testing.T) { + t.Parallel() + tmpDir := t.TempDir() + s := newTestStore(t, filepath.Join(tmpDir, ".beads", "beads.db")) + ctx := context.Background() + + const a, b = "test-cyc-a", "test-cyc-b" + seedBulkRoleIssues(ctx, t, s, a, b) + if err := s.AddDependency(ctx, &types.Dependency{ + IssueID: a, DependsOnID: b, Type: types.DepBlocks, + }, "test"); err != nil { + t.Fatalf("seed dependency: %v", err) + } + + editor, err := s.DependencyEditor() + if err != nil { + t.Fatalf("DependencyEditor(): %v", err) + } + _, err = editor.AddDependencies(ctx, issueops.AddDependenciesRequest{ + Actor: "tester", + SkipPerEdgeCycleCheck: true, + Edges: []issueops.DependencyEdge{ + {IssueID: b, DependsOnID: a, Type: types.DepBlocks}, + }, + }) + if !errors.Is(err, domain.ErrDependencyCycle) { + t.Fatalf("final gate error = %v, want errors.Is domain.ErrDependencyCycle", err) + } + // Typing must not alter the rendered text: no sentinel string appended. + const wantMsg = "dependency cycle would be created: test-cyc-b → test-cyc-a → test-cyc-b (no edges added; run 'bd dep cycles' for analysis)" + if err.Error() != wantMsg { + t.Fatalf("final gate message = %q, want byte-identical %q", err.Error(), wantMsg) + } + + deps, err := s.GetDependencyRecords(ctx, b) + if err != nil { + t.Fatalf("GetDependencyRecords: %v", err) + } + if len(deps) != 0 { + t.Fatalf("cycle edge was committed despite gate: %#v", deps) + } +} + +// bd-578h9.9: a pre-existing committed cycle touching an endpoint of the +// request must not block unrelated bulk wiring — only cycles that traverse a +// new edge gate the commit. +func TestBulkDepAddRoleIgnoresPreexistingCycleAtEndpoint(t *testing.T) { + t.Parallel() + tmpDir := t.TempDir() + s := newTestStore(t, filepath.Join(tmpDir, ".beads", "beads.db")) + ctx := context.Background() + + const a, b, c = "test-pre-a", "test-pre-b", "test-pre-c" + seedBulkRoleIssues(ctx, t, s, a, b, c) + + // Commit the cycle a <-> b first (SkipCycleCheck stands in for legacy data + // that predates cycle validation). + if err := s.RunInTransaction(ctx, "test: seed cycle", func(tx storage.Transaction) error { + for _, pair := range [][2]string{{a, b}, {b, a}} { + dep := &types.Dependency{IssueID: pair[0], DependsOnID: pair[1], Type: types.DepBlocks} + if err := tx.AddDependencyWithOptions(ctx, dep, "test", storage.DependencyAddOptions{SkipCycleCheck: true}); err != nil { + return err + } + } + return nil + }); err != nil { + t.Fatalf("seed cycle: %v", err) + } + + editor, err := s.DependencyEditor() + if err != nil { + t.Fatalf("DependencyEditor(): %v", err) + } + if _, err := editor.AddDependencies(ctx, issueops.AddDependenciesRequest{ + Actor: "tester", + Edges: []issueops.DependencyEdge{ + {IssueID: a, DependsOnID: c, Type: types.DepBlocks}, + }, + }); err != nil { + t.Fatalf("unrelated bulk edge was blocked: %v", err) + } + + deps, err := s.GetDependencyRecords(ctx, a) + if err != nil { + t.Fatalf("GetDependencyRecords: %v", err) + } + var foundC bool + for _, dep := range deps { + if dep.DependsOnID == c { + foundC = true + } + } + if !foundC { + t.Fatalf("edge a -> c did not commit: %#v", deps) + } +} + +func seedBulkRoleIssues(ctx context.Context, t *testing.T, s *dolt.DoltStore, ids ...string) { + t.Helper() + for _, id := range ids { + issue := &types.Issue{ + ID: id, Title: id, Status: types.StatusOpen, + Priority: 1, IssueType: types.TypeTask, CreatedAt: time.Now(), + } + if err := s.CreateIssue(ctx, issue, "test"); err != nil { + t.Fatalf("create %s: %v", id, err) + } + } +} diff --git a/cmd/bd/dep_embedded_test.go b/cmd/bd/dep_embedded_test.go index 35739b5e3..b196334b6 100644 --- a/cmd/bd/dep_embedded_test.go +++ b/cmd/bd/dep_embedded_test.go @@ -11,6 +11,9 @@ import ( "strings" "sync" "testing" + + "github.com/steveyegge/beads/internal/configfile" + "github.com/steveyegge/beads/internal/storage/embeddeddolt" ) // bdDep runs "bd dep" with the given args and returns raw stdout. @@ -576,3 +579,110 @@ func TestEmbeddedDepBulkNoCycleCheckKeepsWholeGraphGate(t *testing.T) { t.Fatalf("expected rolled-back bulk add to leave the graph acyclic, got: %s", cycles) } } + +// TestEmbeddedDepAddWispSource is the front-door test for a wisp-sourced +// dependency edge: `bd dep add ` on the real CLI against a +// real embedded store. Coverage of source routing otherwise stops at the +// storage role's own contract, and the behaviour this pins is the user-visible +// one — pinning an edge's source to the issues plane refused every one of +// these with "issue not found", because a wisp has no row there. +// +// It also discharges the CHANGELOG's staging claim: every edge here is +// wisp-sourced, so all of them land in the dolt-ignored wisp plane, nothing +// versioned is staged, and the adds must record no Dolt commit and leave the +// working set clean. +func TestEmbeddedDepAddWispSource(t *testing.T) { + if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" { + t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests") + } + t.Parallel() + + bd := buildEmbeddedBD(t) + dir, beadsDir, _ := bdInit(t, bd, "--prefix", "dws") + + // --ephemeral is the front door's route to a wisp: the row lands in the + // dolt-ignored `wisps` table, which is what the routing probe reads. + wispA := bdCreate(t, bd, dir, "Wisp dep source", "--ephemeral").ID + wispB := bdCreate(t, bd, dir, "Wisp dep target", "--ephemeral").ID + wispC := bdCreate(t, bd, dir, "Wisp dep source two", "--ephemeral").ID + issue := bdCreate(t, bd, dir, "Issue dep target", "--type", "task").ID + + // Baseline AFTER the fixtures, so a commit or a dirty table left by + // creation cannot be misread as one the dependency adds produced. + beforeCommits, beforeDirty := embeddedLogCountAndDirtyTables(t, beadsDir) + if len(beforeDirty) != 0 { + t.Fatalf("fixture setup left a dirty working set, so later state cannot be attributed: %v", beforeDirty) + } + + t.Run("wisp_to_wisp", func(t *testing.T) { + out := bdDep(t, bd, dir, "add", wispA, wispB) + if !strings.Contains(out, "Added dependency") { + t.Fatalf("expected wisp-sourced dep add to succeed, got: %s", out) + } + if list := bdDep(t, bd, dir, "list", wispA); !strings.Contains(list, wispB) { + t.Errorf("expected %s in dep list of wisp %s, got: %s", wispB, wispA, list) + } + }) + + t.Run("wisp_to_issue", func(t *testing.T) { + out := bdDep(t, bd, dir, "add", wispC, issue) + if !strings.Contains(out, "Added dependency") { + t.Fatalf("expected wisp->issue dep add to succeed, got: %s", out) + } + if list := bdDep(t, bd, dir, "list", wispC); !strings.Contains(list, issue) { + t.Errorf("expected %s in dep list of wisp %s, got: %s", issue, wispC, list) + } + // The edge lives on the wisp's plane, so walking up from the issue + // finds it only if the reverse read scans wisp_dependencies too. + if up := bdDep(t, bd, dir, "list", issue, "--direction", "up"); !strings.Contains(up, wispC) { + t.Errorf("expected wisp dependent %s walking up from %s, got: %s", wispC, issue, up) + } + }) + + // Both adds were wisp-sourced. ChangedTables drops the wisp tables, so the + // staged set was empty each time and the auto-commit had nothing to write. + afterCommits, afterDirty := embeddedLogCountAndDirtyTables(t, beadsDir) + if afterCommits != beforeCommits { + t.Errorf("wisp-sourced dep adds recorded %d Dolt commit(s); the wisp plane is dolt-ignored and must record none", + afterCommits-beforeCommits) + } + if len(afterDirty) != 0 { + t.Errorf("wisp-sourced dep adds left versioned tables dirty: %v", afterDirty) + } +} + +// embeddedLogCountAndDirtyTables reports the embedded store's Dolt commit +// count and the tables its working set currently reports as changed. +func embeddedLogCountAndDirtyTables(t *testing.T, beadsDir string) (commits int, dirty []string) { + t.Helper() + cfg, _ := configfile.Load(beadsDir) + database := "" + if cfg != nil { + database = cfg.GetDoltDatabase() + } + db, cleanup, err := embeddeddolt.OpenSQL(t.Context(), filepath.Join(beadsDir, "embeddeddolt"), database, "main") + if err != nil { + t.Fatalf("OpenSQL: %v", err) + } + defer cleanup() + + if err := db.QueryRowContext(t.Context(), "SELECT COUNT(*) FROM dolt_log").Scan(&commits); err != nil { + t.Fatalf("query dolt_log: %v", err) + } + rows, err := db.QueryContext(t.Context(), "SELECT table_name, status FROM dolt_status") + if err != nil { + t.Fatalf("query dolt_status: %v", err) + } + defer func() { _ = rows.Close() }() + for rows.Next() { + var table, status string + if err := rows.Scan(&table, &status); err != nil { + t.Fatalf("scan dolt_status: %v", err) + } + dirty = append(dirty, table+":"+status) + } + if err := rows.Err(); err != nil { + t.Fatalf("iterate dolt_status: %v", err) + } + return commits, dirty +} diff --git a/cmd/bd/dep_proxied_server.go b/cmd/bd/dep_proxied_server.go index 2f111930e..c66617620 100644 --- a/cmd/bd/dep_proxied_server.go +++ b/cmd/bd/dep_proxied_server.go @@ -2,6 +2,7 @@ package main import ( "context" + "errors" "fmt" "os" "strings" @@ -12,6 +13,7 @@ import ( "github.com/steveyegge/beads/internal/storage/uow" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" + "github.com/steveyegge/beads/issueops" ) type depAddResult struct { @@ -21,6 +23,91 @@ type depAddResult struct { cycleErr error } +// proxiedDependencyEditor hands back the guarded dependency-edge surface for +// the proxied-server provider, through the provider's OWN capability accessor +// — the same two-step proxiedIssueReader and proxiedBatchCloser perform, and +// for the same reason: the accessor is where each layer is added, so a command +// that reached for the constructor would get an unlayered editor. +func proxiedDependencyEditor() (issueops.DependencyEditor, error) { + if uowProvider == nil { + return nil, errors.New("proxied-server UOW provider not initialized") + } + src, ok := uowProvider.(uow.DependencyEditorSource) + if !ok { + return nil, fmt.Errorf("proxied-server provider %T does not offer the dependency-edge surface", uowProvider) + } + return src.DependencyEditor() +} + +// proxiedIssueRelations hands back the guarded neighbor-query surface for the +// proxied-server provider, through the provider's own capability accessor. +func proxiedIssueRelations() (issueops.Relations, error) { + if uowProvider == nil { + return nil, errors.New("proxied-server UOW provider not initialized") + } + src, ok := uowProvider.(uow.RelationsSource) + if !ok { + return nil, fmt.Errorf("proxied-server provider %T does not offer the neighbor-query surface", uowProvider) + } + return src.IssueRelations() +} + +// addDependencyEdgesProxied asserts edges through the DependencyEditor role. +// +// skipPerEdgeCycleCheck is a separate argument from the --no-cycle-check flag +// on purpose. That flag has never turned the per-edge probe off for a single +// edge on either route — it turns off the whole-graph sweep this command +// prints warnings from. Only the bulk path trades the per-edge probe away, and +// only because it always has. +func addDependencyEdgesProxied(ctx context.Context, edges []issueops.DependencyEdge, skipPerEdgeCycleCheck bool) error { + editor, err := proxiedDependencyEditor() + if err != nil { + return err + } + _, err = editor.AddDependencies(ctx, issueops.AddDependenciesRequest{ + Actor: actor, + Edges: edges, + SkipPerEdgeCycleCheck: skipPerEdgeCycleCheck, + }) + return err +} + +// depEdgeFeedback gathers the cycle sweep and the titles the confirmation line +// wants, in a second READ-ONLY unit of work once the edges have landed. +// +// Neither belongs in the write. The role's request IS the transaction, and a +// cycle warning computed inside a transaction that has not committed describes +// a graph nobody else can see; a title is presentation. Failing to open the +// unit of work cannot fail the command either — the edges are already durable +// — so it is reported the way a failed sweep already was. +func depEdgeFeedback(ctx context.Context, fromID, toID string, checkCycles bool) depAddResult { + var res depAddResult + if fromID == "" && toID == "" && !checkCycles { + return res + } + if uowProvider == nil { + res.cycleErr = errors.New("proxied-server UOW provider not initialized") + return res + } + uw, err := uowProvider.NewUOW(ctx) + if err != nil { + res.cycleErr = fmt.Errorf("open unit of work: %w", err) + return res + } + defer uw.Close(ctx) + + if fromID != "" { + res.fromTitle = proxiedLookupTitle(ctx, uw, fromID) + } + if toID != "" { + res.toTitle = proxiedLookupTitle(ctx, uw, toID) + } + if checkCycles { + res.cycles, res.cycleErr = uw.DependencyUseCase().DetectCycles(ctx) + } + return res +} + func proxiedLookupTitle(ctx context.Context, uw uow.UnitOfWork, id string) string { if IsExternalRef(id) { return "" @@ -70,38 +157,13 @@ func runDepBlocksProxiedServer(cmd *cobra.Command, ctx context.Context, blockerI return HandleErrorRespectJSON("cannot add dependency: %s is already a child of %s. Children inherit dependency on parent completion via hierarchy. Adding an explicit dependency would create a deadlock", blockedID, blockerID) } - if uowProvider == nil { - return HandleErrorRespectJSON("proxied-server UOW provider not initialized") - } - noCycleCheck, _ := cmd.Flags().GetBool("no-cycle-check") - res, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (depAddResult, string, error) { - dep := &types.Dependency{ - IssueID: blockedID, - DependsOnID: blockerID, - Type: types.DepBlocks, - } - if _, err := uw.DependencyUseCase().AddDependencies(ctx, []*types.Dependency{dep}, actor, domain.BulkAddDepsOpts{}); err != nil { - return depAddResult{}, "", err - } - - var cycles [][]*types.Issue - var cycleErr error - if !noCycleCheck { - cycles, cycleErr = uw.DependencyUseCase().DetectCycles(ctx) - } - - return depAddResult{ - fromTitle: proxiedLookupTitle(ctx, uw, blockedID), - toTitle: proxiedLookupTitle(ctx, uw, blockerID), - cycles: cycles, - cycleErr: cycleErr, - }, fmt.Sprintf("bd: dep add %s %s", blockedID, blockerID), nil - }) - if err != nil { + edge := issueops.DependencyEdge{IssueID: blockedID, DependsOnID: blockerID, Type: types.DepBlocks} + if err := addDependencyEdgesProxied(ctx, []issueops.DependencyEdge{edge}, false); err != nil { return HandleErrorRespectJSON("%v", err) } + res := depEdgeFeedback(ctx, blockedID, blockerID, !noCycleCheck) printCycleDetectionError(res.cycleErr) printCycleWarnings(res.cycles) @@ -164,34 +226,13 @@ func runDepAddProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri return HandleErrorRespectJSON("%v", err) } - if uowProvider == nil { - return HandleErrorRespectJSON("proxied-server UOW provider not initialized") - } - noCycleCheck, _ := cmd.Flags().GetBool("no-cycle-check") - res, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (depAddResult, string, error) { - dep := &types.Dependency{IssueID: fromID, DependsOnID: toID, Type: dt} - if _, err := uw.DependencyUseCase().AddDependencies(ctx, []*types.Dependency{dep}, actor, domain.BulkAddDepsOpts{}); err != nil { - return depAddResult{}, "", err - } - - var cycles [][]*types.Issue - var cycleErr error - if !noCycleCheck { - cycles, cycleErr = uw.DependencyUseCase().DetectCycles(ctx) - } - - return depAddResult{ - fromTitle: proxiedLookupTitle(ctx, uw, fromID), - toTitle: proxiedLookupTitle(ctx, uw, toID), - cycles: cycles, - cycleErr: cycleErr, - }, fmt.Sprintf("bd: dep add %s %s", fromID, toID), nil - }) - if err != nil { + edge := issueops.DependencyEdge{IssueID: fromID, DependsOnID: toID, Type: dt} + if err := addDependencyEdgesProxied(ctx, []issueops.DependencyEdge{edge}, false); err != nil { return HandleErrorRespectJSON("%v", err) } + res := depEdgeFeedback(ctx, fromID, toID, !noCycleCheck) printCycleDetectionError(res.cycleErr) printCycleWarnings(res.cycles) @@ -223,7 +264,7 @@ func runDepAddBulkProxied(cmd *cobra.Command, ctx context.Context, file, default return HandleErrorRespectJSON("no dependency edges found") } - deps := make([]*types.Dependency, 0, len(edges)) + depEdges := make([]issueops.DependencyEdge, 0, len(edges)) for _, edge := range edges { if isDisallowedHierarchicalDependency(edge.IssueID, edge.DependsOnID, edge.Type) { return HandleErrorRespectJSON("line %d: cannot add dependency: %s is already a child of %s", edge.Line, edge.IssueID, edge.DependsOnID) @@ -233,62 +274,41 @@ func runDepAddBulkProxied(cmd *cobra.Command, ctx context.Context, file, default return HandleErrorRespectJSON("line %d: %v", edge.Line, err) } } - deps = append(deps, &types.Dependency{ + depEdges = append(depEdges, issueops.DependencyEdge{ IssueID: edge.IssueID, DependsOnID: edge.DependsOnID, Type: edge.Type, }) } - if uowProvider == nil { - return HandleErrorRespectJSON("proxied-server UOW provider not initialized") - } - noCycleCheck, _ := cmd.Flags().GetBool("no-cycle-check") - type bulkResult struct { - cycles [][]*types.Issue - cycleErr error - } - res, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (bulkResult, string, error) { - if _, err := uw.DependencyUseCase().AddDependencies(ctx, deps, actor, domain.BulkAddDepsOpts{ - SkipPerEdgeCycleCheck: noCycleCheck, - }); err != nil { - return bulkResult{}, "", err - } - - var r bulkResult - if !noCycleCheck { - r.cycles, r.cycleErr = uw.DependencyUseCase().DetectCycles(ctx) - } - - return r, fmt.Sprintf("dependency: add %d edges", len(deps)), nil - }) - if err != nil { + if err := addDependencyEdgesProxied(ctx, depEdges, noCycleCheck); err != nil { return HandleErrorRespectJSON("%v", err) } + res := depEdgeFeedback(ctx, "", "", !noCycleCheck) printCycleDetectionError(res.cycleErr) printCycleWarnings(res.cycles) if jsonOutput { - out := make([]map[string]interface{}, 0, len(deps)) - for _, dep := range deps { + out := make([]map[string]interface{}, 0, len(depEdges)) + for _, edge := range depEdges { out = append(out, map[string]interface{}{ - "issue_id": dep.IssueID, - "depends_on_id": dep.DependsOnID, - "type": string(dep.Type), + "issue_id": edge.IssueID, + "depends_on_id": edge.DependsOnID, + "type": string(edge.Type), }) } _ = outputJSON(map[string]interface{}{ "status": "added", - "count": len(deps), + "count": len(depEdges), "dependencies": out, }) return nil } - fmt.Printf("%s Added %d dependencies\n", ui.RenderPass("✓"), len(deps)) + fmt.Printf("%s Added %d dependencies\n", ui.RenderPass("✓"), len(depEdges)) return nil } @@ -301,22 +321,21 @@ func runDepRemoveProxiedServer(_ *cobra.Command, ctx context.Context, args []str } } - if uowProvider == nil { - return HandleErrorRespectJSON("proxied-server UOW provider not initialized") - } - - res, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (depAddResult, string, error) { - if err := uw.DependencyUseCase().RemoveDependency(ctx, fromID, toID, actor); err != nil { - return depAddResult{}, "", err - } - return depAddResult{ - fromTitle: proxiedLookupTitle(ctx, uw, fromID), - toTitle: proxiedLookupTitle(ctx, uw, toID), - }, fmt.Sprintf("bd: dep remove %s %s", fromID, toID), nil - }) + editor, err := proxiedDependencyEditor() if err != nil { return HandleErrorRespectJSON("%v", err) } + // The role's Removed verdict is not printed. `bd dep remove` has always + // confirmed the same way whether or not an edge was there, and reporting + // the difference now would change what every existing script reads. + if _, err := editor.RemoveDependency(ctx, issueops.RemoveDependencyRequest{ + Actor: actor, + IssueID: fromID, + DependsOnID: toID, + }); err != nil { + return HandleErrorRespectJSON("%v", err) + } + res := depEdgeFeedback(ctx, fromID, toID, false) if jsonOutput { _ = outputJSON(map[string]interface{}{ @@ -341,80 +360,41 @@ func runDepListProxiedServer(cmd *cobra.Command, ctx context.Context, args []str direction = "down" } - if uowProvider == nil { - return HandleErrorRespectJSON("proxied-server UOW provider not initialized") - } - uw, err := uowProvider.NewUOW(ctx) - if err != nil { - return HandleErrorRespectJSON("open unit of work: %v", err) - } - defer uw.Close(ctx) - - depUC := uw.DependencyUseCase() - + // The multi-id edge listing is a different question with a different + // answer shape — raw edge records keyed by source, printed per source — + // and no role describes it. It keeps its own unit of work. if len(args) > 1 && direction == "down" { - depMap, err := depUC.GetIssueDependencyRecords(ctx, args) - if err != nil { - return HandleErrorRespectJSON("%v", err) - } - var allDeps []*types.Dependency - for _, id := range args { - for _, dep := range depMap[id] { - if typeFilter == "" || string(dep.Type) == typeFilter { - allDeps = append(allDeps, dep) - } - } - } - if jsonOutput { - if allDeps == nil { - allDeps = []*types.Dependency{} - } - _ = outputJSON(allDeps) - return nil - } - for _, id := range args { - deps := depMap[id] - if len(deps) == 0 { - fmt.Printf("\n%s has no dependencies\n", id) - continue - } - fmt.Printf("\n%s %s depends on:\n\n", ui.RenderAccent("📋"), id) - for _, dep := range deps { - if typeFilter != "" && string(dep.Type) != typeFilter { - continue - } - fmt.Printf(" %s via %s\n", dep.DependsOnID, dep.Type) - } - } - fmt.Println() - return nil + return runDepListRecordsProxiedServer(ctx, args, typeFilter) } - var allIssues []*types.IssueWithDependencyMetadata - listDirection := domain.DepDirectionOut - if direction == "up" { - listDirection = domain.DepDirectionIn + // Everything else is the neighbor query, and it is on the Relations role: + // one call per anchor, each with an explicit direction, because the role + // refuses to guess one. + rel, err := proxiedIssueRelations() + if err != nil { + return HandleErrorRespectJSON("%v", err) } + request := issueops.RelatedRequest{Direction: issueops.RelationOut} + if direction == "up" { + request.Direction = issueops.RelationIn + } + if typeFilter != "" { + request.Types = []types.DependencyType{types.DependencyType(typeFilter)} + } + + var allIssues []*issueops.RelatedIssue for _, id := range args { - issues, err := depUC.ListWithIssueMetadata(ctx, id, domain.DepListFilter{Direction: listDirection}) + request.ID = id + issues, err := rel.Related(ctx, request) if err != nil { return HandleErrorRespectJSON("%v", err) } - if typeFilter != "" { - filtered := issues[:0] - for _, iss := range issues { - if string(iss.DependencyType) == typeFilter { - filtered = append(filtered, iss) - } - } - issues = filtered - } allIssues = append(allIssues, issues...) } if jsonOutput { if allIssues == nil { - allIssues = []*types.IssueWithDependencyMetadata{} + allIssues = []*issueops.RelatedIssue{} } _ = outputJSON(allIssues) return nil @@ -454,6 +434,52 @@ func runDepListProxiedServer(cmd *cobra.Command, ctx context.Context, args []str return nil } +// runDepListRecordsProxiedServer answers `bd dep list a b c` with raw edge +// records grouped by source. It is off the Relations role deliberately: the +// role answers with the ISSUES on the far end of an anchor's edges, and this +// prints the edges themselves, per source, for several sources at once. +// Routing it through the role would mean N anchor probes and a hydration of +// every neighbor this output never shows. +func runDepListRecordsProxiedServer(ctx context.Context, args []string, typeFilter string) error { + uw, err := proxiedOpenReadUOW(ctx) + if err != nil { + return err + } + defer uw.Close(ctx) + + depMap, err := uw.DependencyUseCase().GetIssueDependencyRecords(ctx, args) + if err != nil { + return HandleErrorRespectJSON("%v", err) + } + if jsonOutput { + allDeps := []*types.Dependency{} + for _, id := range args { + for _, dep := range depMap[id] { + if typeFilter == "" || string(dep.Type) == typeFilter { + allDeps = append(allDeps, dep) + } + } + } + return outputJSON(allDeps) + } + for _, id := range args { + deps := depMap[id] + if len(deps) == 0 { + fmt.Printf("\n%s has no dependencies\n", id) + continue + } + fmt.Printf("\n%s %s depends on:\n\n", ui.RenderAccent("📋"), id) + for _, dep := range deps { + if typeFilter != "" && string(dep.Type) != typeFilter { + continue + } + fmt.Printf(" %s via %s\n", dep.DependsOnID, dep.Type) + } + } + fmt.Println() + return nil +} + func runDepTreeProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error { fullID := args[0] showAllPaths, _ := cmd.Flags().GetBool("show-all-paths") diff --git a/cmd/bd/dep_test.go b/cmd/bd/dep_test.go index 4d1cd2b69..2eba0db21 100644 --- a/cmd/bd/dep_test.go +++ b/cmd/bd/dep_test.go @@ -6,7 +6,6 @@ import ( "bytes" "context" "encoding/json" - "errors" "fmt" "io" "os" @@ -15,9 +14,7 @@ import ( "testing" "time" - "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/storage/dolt" - "github.com/steveyegge/beads/internal/storage/domain" "github.com/steveyegge/beads/internal/types" ) @@ -1689,225 +1686,3 @@ func TestDepListCrossRigRouting(t *testing.T) { t.Log("Successfully resolved cross-rig dependencies via routing") } - -type fakeCycleTx struct { - storage.Transaction - gotEdges [][2]string - path string - err error - added []*types.Dependency - addOpts []storage.DependencyAddOptions -} - -func (f *fakeCycleTx) CycleThroughEdges(_ context.Context, edges [][2]string) (string, error) { - f.gotEdges = edges - return f.path, f.err -} - -func (f *fakeCycleTx) AddDependencyWithOptions(_ context.Context, dep *types.Dependency, _ string, opts storage.DependencyAddOptions) error { - cp := *dep - f.added = append(f.added, &cp) - f.addOpts = append(f.addOpts, opts) - return nil -} - -func TestAddBulkDependenciesInTxOrdersHierarchyAndAlwaysRunsFinalGate(t *testing.T) { - t.Parallel() - tx := &fakeCycleTx{path: "child → grand → child"} - edges := []bulkDepEdge{ - {Line: 1, IssueID: "child", DependsOnID: "grand", Type: types.DepBlocks}, - {Line: 2, IssueID: "child", DependsOnID: "parent", Type: types.DepParentChild}, - {Line: 3, IssueID: "parent", DependsOnID: "grand", Type: types.DepParentChild}, - } - - err := addBulkDependenciesInTx(context.Background(), tx, edges, false, "tester") - if err == nil || !strings.Contains(err.Error(), "dependency cycle would be created") { - t.Fatalf("normal-mode final gate error = %v, want rejection", err) - } - // The embedded bulk final gate must type its rejection identically to the - // proxied/domain bulk gate so callers can errors.Is it regardless of plumbing. - if !errors.Is(err, domain.ErrDependencyCycle) { - t.Fatalf("final gate error must errors.Is domain.ErrDependencyCycle, got %v", err) - } - // Typing must not alter the rendered text: no sentinel string appended. - const wantMsg = "dependency cycle would be created: child → grand → child (no edges added; run 'bd dep cycles' for analysis)" - if err.Error() != wantMsg { - t.Fatalf("final gate message = %q, want byte-identical %q", err.Error(), wantMsg) - } - if len(tx.added) != 3 { - t.Fatalf("added dependencies = %d, want 3", len(tx.added)) - } - for i := 0; i < 2; i++ { - if tx.added[i].Type != types.DepParentChild { - t.Fatalf("added[%d].Type = %s, want parent-child before blocking edge", i, tx.added[i].Type) - } - } - if tx.added[2].Type != types.DepBlocks { - t.Fatalf("added[2].Type = %s, want blocks last", tx.added[2].Type) - } - for i, opts := range tx.addOpts { - if opts.SkipCycleCheck { - t.Fatalf("added[%d] unexpectedly skipped per-edge cycle check", i) - } - } - if len(tx.gotEdges) != 3 { - t.Fatalf("final gate saw %d edges, want all 3 scheduling edges", len(tx.gotEdges)) - } -} - -// bd-6dnrw.8 / bd-578h9.9: the bulk-add cycle gate must pass only scheduling -// edge types to the in-tx check, skip the check when none are present, and -// propagate check failures. -func TestNewCycleThroughEdges(t *testing.T) { - t.Parallel() - ctx := context.Background() - edges := []bulkDepEdge{ - {IssueID: "bd-a", DependsOnID: "bd-b", Type: types.DepBlocks}, - {IssueID: "bd-pc", DependsOnID: "bd-parent", Type: types.DepParentChild}, - {IssueID: "bd-c", DependsOnID: "bd-d", Type: types.DependencyType("related")}, - } - - tx := &fakeCycleTx{path: "bd-a → bd-b → bd-a"} - path, err := newCycleThroughEdges(ctx, tx, edges) - if err != nil || path != "bd-a → bd-b → bd-a" { - t.Errorf("cycle through new edge: got (%q, %v), want rendered path", path, err) - } - if len(tx.gotEdges) != 2 || tx.gotEdges[0] != [2]string{"bd-a", "bd-b"} || tx.gotEdges[1] != [2]string{"bd-pc", "bd-parent"} { - t.Errorf("edges passed to check = %v, want blocks and parent-child edges", tx.gotEdges) - } - - tx = &fakeCycleTx{} - path, err = newCycleThroughEdges(ctx, tx, []bulkDepEdge{ - {IssueID: "bd-c", DependsOnID: "bd-d", Type: types.DependencyType("related")}, - }) - if err != nil || path != "" { - t.Errorf("non-blocking-only batch: got (%q, %v), want gate skipped", path, err) - } - if tx.gotEdges != nil { - t.Errorf("non-blocking-only batch ran the check with edges %v", tx.gotEdges) - } - - _, err = newCycleThroughEdges(ctx, &fakeCycleTx{err: fmt.Errorf("boom")}, edges) - if err == nil { - t.Error("check failure must propagate as error, not pass the gate") - } -} - -// bd-578h9.9: a pre-existing committed cycle touching an endpoint of the -// batch must not block unrelated bulk wiring — only cycles that traverse a -// new edge gate the commit. -func TestBulkDepAddCycleGateIgnoresPreexistingCycleAtEndpoint(t *testing.T) { - t.Parallel() - tmpDir := t.TempDir() - s := newTestStore(t, filepath.Join(tmpDir, ".beads", "beads.db")) - ctx := context.Background() - - for _, id := range []string{"test-pre-a", "test-pre-b", "test-pre-c"} { - issue := &types.Issue{ - ID: id, Title: id, Status: types.StatusOpen, - Priority: 1, IssueType: types.TypeTask, CreatedAt: time.Now(), - } - if err := s.CreateIssue(ctx, issue, "test"); err != nil { - t.Fatalf("create %s: %v", id, err) - } - } - // Commit the cycle a <-> b first (SkipCycleCheck stands in for legacy - // data that predates cycle validation). - if err := s.RunInTransaction(ctx, "test: seed cycle", func(tx storage.Transaction) error { - for _, pair := range [][2]string{{"test-pre-a", "test-pre-b"}, {"test-pre-b", "test-pre-a"}} { - dep := &types.Dependency{IssueID: pair[0], DependsOnID: pair[1], Type: types.DepBlocks} - if err := tx.AddDependencyWithOptions(ctx, dep, "test", storage.DependencyAddOptions{SkipCycleCheck: true}); err != nil { - return err - } - } - return nil - }); err != nil { - t.Fatalf("seed cycle: %v", err) - } - - // Bulk-add the unrelated edge a -> c through the same gate the CLI uses. - edges := []bulkDepEdge{{IssueID: "test-pre-a", DependsOnID: "test-pre-c", Type: types.DepBlocks}} - err := s.RunInTransaction(ctx, "test: bulk unrelated edge", func(tx storage.Transaction) error { - dep := &types.Dependency{IssueID: "test-pre-a", DependsOnID: "test-pre-c", Type: types.DepBlocks} - if err := tx.AddDependencyWithOptions(ctx, dep, "test", storage.DependencyAddOptions{SkipCycleCheck: true}); err != nil { - return err - } - cyclePath, cycleErr := newCycleThroughEdges(ctx, tx, edges) - if cycleErr != nil { - return cycleErr - } - if cyclePath != "" { - return fmt.Errorf("dependency cycle would be created: %s", cyclePath) - } - return nil - }) - if err != nil { - t.Fatalf("unrelated bulk edge was blocked: %v", err) - } - - deps, err := s.GetDependencyRecords(ctx, "test-pre-a") - if err != nil { - t.Fatalf("GetDependencyRecords: %v", err) - } - var foundC bool - for _, dep := range deps { - if dep.DependsOnID == "test-pre-c" { - foundC = true - } - } - if !foundC { - t.Fatalf("edge a -> c did not commit: %#v", deps) - } -} - -// bd-6dnrw.8: with SkipCycleCheck the per-edge guard is off, so the in-tx -// whole-graph check must catch the cycle and the transaction roll back — -// no cycle may ever commit. -func TestBulkDepAddCycleGateRollsBack(t *testing.T) { - t.Parallel() - tmpDir := t.TempDir() - s := newTestStore(t, filepath.Join(tmpDir, ".beads", "beads.db")) - ctx := context.Background() - - for _, id := range []string{"test-cyc-a", "test-cyc-b"} { - issue := &types.Issue{ - ID: id, Title: id, Status: types.StatusOpen, - Priority: 1, IssueType: types.TypeTask, CreatedAt: time.Now(), - } - if err := s.CreateIssue(ctx, issue, "test"); err != nil { - t.Fatalf("create %s: %v", id, err) - } - } - if err := s.AddDependency(ctx, &types.Dependency{ - IssueID: "test-cyc-a", DependsOnID: "test-cyc-b", Type: types.DependencyType("blocks"), - }, "test"); err != nil { - t.Fatalf("seed dependency: %v", err) - } - - edges := []bulkDepEdge{{IssueID: "test-cyc-b", DependsOnID: "test-cyc-a", Type: types.DepBlocks}} - err := s.RunInTransaction(ctx, "test: bulk cycle gate", func(tx storage.Transaction) error { - dep := &types.Dependency{IssueID: "test-cyc-b", DependsOnID: "test-cyc-a", Type: types.DependencyType("blocks")} - if err := tx.AddDependencyWithOptions(ctx, dep, "test", storage.DependencyAddOptions{SkipCycleCheck: true}); err != nil { - return err - } - cyclePath, cycleErr := newCycleThroughEdges(ctx, tx, edges) - if cycleErr != nil { - return cycleErr - } - if cyclePath == "" { - return fmt.Errorf("in-tx check missed the cycle created by the uncommitted edge") - } - return fmt.Errorf("dependency cycle would be created: %s", cyclePath) - }) - if err == nil || !strings.Contains(err.Error(), "dependency cycle would be created") { - t.Fatalf("expected cycle-gate error, got: %v", err) - } - - deps, err := s.GetDependencyRecords(ctx, "test-cyc-b") - if err != nil { - t.Fatalf("GetDependencyRecords: %v", err) - } - if len(deps) != 0 { - t.Fatalf("cycle edge was committed despite gate: %#v", deps) - } -} diff --git a/cmd/bd/link.go b/cmd/bd/link.go index 8f91510be..772a88d91 100644 --- a/cmd/bd/link.go +++ b/cmd/bd/link.go @@ -68,7 +68,7 @@ Examples: } if !dt.IsValid() { - return HandleErrorRespectJSON("invalid dependency type %q: must be non-empty and at most 50 characters", depType) + return HandleErrorRespectJSON("invalid dependency type %q: must be non-empty and at most %d characters", depType, types.MaxDependencyTypeLen) } dep := &types.Dependency{ diff --git a/cmd/bd/link_proxied_server.go b/cmd/bd/link_proxied_server.go index ef101c3cb..cce94cb2e 100644 --- a/cmd/bd/link_proxied_server.go +++ b/cmd/bd/link_proxied_server.go @@ -23,7 +23,7 @@ func runLinkProxiedServer(cmd *cobra.Command, ctx context.Context, args []string } if !dt.IsValid() { - return HandleErrorRespectJSON("invalid dependency type %q: must be non-empty and at most 50 characters", depType) + return HandleErrorRespectJSON("invalid dependency type %q: must be non-empty and at most %d characters", depType, types.MaxDependencyTypeLen) } if uowProvider == nil { @@ -32,6 +32,9 @@ func runLinkProxiedServer(cmd *cobra.Command, ctx context.Context, args []string res, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (depAddResult, string, error) { dep := &types.Dependency{IssueID: id1, DependsOnID: id2, Type: dt} + // Source-routed, like the direct twin's store.AddDependencyWithOptions: + // `bd link` takes whatever id the caller names, and a wisp source has no + // row in the issues plane for the edge to hang off. if _, err := uw.DependencyUseCase().AddDependencies(ctx, []*types.Dependency{dep}, actor, domain.BulkAddDepsOpts{}); err != nil { return depAddResult{}, "", err } diff --git a/cmd/bd/ready.go b/cmd/bd/ready.go index 3064209d3..f596e0128 100644 --- a/cmd/bd/ready.go +++ b/cmd/bd/ready.go @@ -130,20 +130,30 @@ This is useful for agents executing molecules to see which steps can run next.`, } if claimReady { - claimed, err := activeStore.ClaimReadyIssue(ctx, filter, actor) + // The claim is on the ReadyClaimer role, through the store's own + // accessor, so selection, the compare-and-set and the hydration + // that feeds --json all share one transaction. The listing below + // is not on a role and still builds the filter, for the reasons + // issueops.Reader's doc comment gives. + claimer, err := activeStore.ReadyClaimer() if err != nil { - if capErr := handleMaxRowsError(err); capErr != nil { - return capErr - } return HandleErrorRespectJSON("%v", err) } - if claimed == nil { + res, err := claimer.ClaimNext(ctx, claimNextRequest(in)) + if err != nil { + // No handleMaxRowsError here, unlike the listing below: the + // request carries no cap, so ErrTooManyRows cannot come back. + // See claimNextRequest for why the cap never applied. + return HandleErrorRespectJSON("%v", err) + } + if res.Claimed == nil { if jsonOutput { return outputJSON([]*types.IssueWithCounts{}) } fmt.Printf("\n%s No ready work to claim\n\n", ui.RenderWarn("○")) return nil } + claimed := res.Claimed if err := commitPendingIfEmbedded(ctx, activeStore, actor, doltAutoCommitParams{ Command: "ready", IssueIDs: []string{claimed.ID}, @@ -152,7 +162,7 @@ This is useful for agents executing molecules to see which steps can run next.`, } SetLastTouchedID(claimed.ID) if jsonOutput { - return outputJSON(buildReadyIssueOutput(ctx, activeStore, []*types.Issue{claimed})) + return outputJSON([]*types.IssueWithCounts{claimed}) } fmt.Printf("%s Claimed issue: %s\n", ui.RenderPass("✓"), formatFeedbackID(claimed.ID, claimed.Title)) return nil @@ -402,47 +412,6 @@ func displayReadyList(issues []*types.Issue, parentEpicMap map[string]string) { fmt.Println("Status: ○ open ◐ in_progress ● blocked ✓ closed ❄ deferred") } -func buildReadyIssueOutput(ctx context.Context, s storage.DoltStorage, issues []*types.Issue) []*types.IssueWithCounts { - if issues == nil { - issues = []*types.Issue{} - } - issueIDs := make([]string, len(issues)) - for i, issue := range issues { - issueIDs[i] = issue.ID - } - - depCounts, _ := s.GetDependencyCounts(ctx, issueIDs) - allDeps, _ := s.GetDependencyRecordsForIssues(ctx, issueIDs) - commentCounts, _ := s.GetCommentCounts(ctx, issueIDs) - - for _, issue := range issues { - issue.Dependencies = allDeps[issue.ID] - } - - issuesWithCounts := make([]*types.IssueWithCounts, len(issues)) - for i, issue := range issues { - counts := depCounts[issue.ID] - if counts == nil { - counts = &types.DependencyCounts{DependencyCount: 0, DependentCount: 0} - } - var parent *string - for _, dep := range allDeps[issue.ID] { - if dep.Type == types.DepParentChild { - parent = &dep.DependsOnID - break - } - } - issuesWithCounts[i] = &types.IssueWithCounts{ - Issue: issue, - DependencyCount: counts.DependencyCount, - DependentCount: counts.DependentCount, - CommentCount: commentCounts[issue.ID], - Parent: parent, - } - } - return issuesWithCounts -} - // readyExplainFilter is the filter both --explain routes run, derived from the // same builder the listing uses so the set `bd ready --explain` explains cannot // drift from the set `bd ready` shows (bd-3fs.3). diff --git a/cmd/bd/ready_input.go b/cmd/bd/ready_input.go index fffb177ef..877eb4172 100644 --- a/cmd/bd/ready_input.go +++ b/cmd/bd/ready_input.go @@ -200,3 +200,36 @@ func gatherReadyInput(cmd *cobra.Command, resolveCap func(*cobra.Command) (int, return in, nil } + +// claimNextRequest is `bd ready --claim`'s request to the ReadyClaimer role. +// Both routes build it here, so the claim asks one question no matter which +// door it came through — and it is the SAME issueops.ReadyRequest the listing +// builds its filter from, so the claim's predicate cannot drift from the set +// `bd ready` shows. +// +// The two things the filter carries that the request does not: +// +// - The --max-rows cap. It never applied to a claim in the first place: +// ClaimReadyIssueInTx clears MaxRows, MaxRowsSource and Limit before it +// scans, because a cap sized for bulk reads must not make a single-row +// claim report an empty front. Dropping it here is visible only in that +// the role has no field to ignore. +// - The directory-label default. The listing puts it on the built filter +// verbatim; here it goes on the request, where it is normalized along with +// every other label. That differs only for a directory.labels value +// carrying stray whitespace. The emptiness test is unchanged — read off +// the already-normalized filter, so `--label " "` is no label at all and +// still does not suppress the default. +func claimNextRequest(in readyInput) issueops.ClaimNextRequest { + req := in.ReadyRequest + // Limit and Offset are ErrValidation on a claim. Neither was ever live + // here: --offset with --claim is already a usage error above, and the + // claim scan zeroes the limit itself. + req.Limit, req.Offset = nil, 0 + if len(in.filter.Labels) == 0 && len(in.filter.LabelsAny) == 0 { + if dirLabels := config.GetDirectoryLabels(); len(dirLabels) > 0 { + req.LabelsAny = dirLabels + } + } + return issueops.ClaimNextRequest{Actor: actor, Filter: req} +} diff --git a/cmd/bd/ready_proxied_server.go b/cmd/bd/ready_proxied_server.go index ac3c16b50..f466a7bc9 100644 --- a/cmd/bd/ready_proxied_server.go +++ b/cmd/bd/ready_proxied_server.go @@ -2,6 +2,7 @@ package main import ( "context" + "errors" "fmt" "os" "strings" @@ -13,6 +14,7 @@ import ( "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" "github.com/steveyegge/beads/internal/workapi" + "github.com/steveyegge/beads/issueops" ) func runReadyProxiedServer(cmd *cobra.Command, ctx context.Context) error { @@ -40,7 +42,7 @@ func runReadyProxiedServer(cmd *cobra.Command, ctx context.Context) error { } if in.claim { - return runReadyProxiedClaim(ctx, nil, in) + return runReadyProxiedClaim(ctx, in) } uw, err := uowProvider.NewUOW(ctx) @@ -188,40 +190,25 @@ func runReadyProxiedList(ctx context.Context, uw uow.UnitOfWork, in readyInput) return nil } -func runReadyProxiedClaim(ctx context.Context, _ uow.UnitOfWork, in readyInput) error { +// runReadyProxiedClaim is the proxied route of `bd ready --claim`, on the same +// ReadyClaimer role the direct route reaches through the store's accessor. +// Both build their request in claimNextRequest, so the two doors ask one +// question — and neither opens a unit of work of its own: the role's request +// IS the transaction, which is what lets the selection, the compare-and-set +// and the hydration this route prints share it. +func runReadyProxiedClaim(ctx context.Context, in readyInput) error { CheckReadonly("ready --claim") - type claimResult struct { - issue *types.Issue - claimed bool - jsonPayload []*types.IssueWithCounts + claimer, err := proxiedReadyClaimer() + if err != nil { + return HandleErrorRespectJSON("%v", err) } - - res, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (claimResult, string, error) { - claimRes, err := uw.IssueUseCase().ClaimReadyIssue(ctx, in.filter, actor) - if err != nil { - return claimResult{}, "", err - } - if !claimRes.Claimed { - return claimResult{claimed: false}, "", nil - } - - var jsonPayload []*types.IssueWithCounts - if in.jsonOut { - jsonPayload = buildReadyIssueOutputProxied(ctx, uw, []*types.Issue{claimRes.Issue}) - } - - return claimResult{ - issue: claimRes.Issue, - claimed: true, - jsonPayload: jsonPayload, - }, fmt.Sprintf("bd: ready --claim %s", claimRes.Issue.ID), nil - }) + res, err := claimer.ClaimNext(ctx, claimNextRequest(in)) if err != nil { return HandleErrorRespectJSON("%v", err) } - if !res.claimed { + if res.Claimed == nil { if in.jsonOut { _ = outputJSON([]*types.IssueWithCounts{}) } else { @@ -230,16 +217,31 @@ func runReadyProxiedClaim(ctx context.Context, _ uow.UnitOfWork, in readyInput) return nil } - SetLastTouchedID(res.issue.ID) + SetLastTouchedID(res.Claimed.ID) if in.jsonOut { - _ = outputJSON(res.jsonPayload) + _ = outputJSON([]*types.IssueWithCounts{res.Claimed}) } else { - fmt.Printf("%s Claimed issue: %s\n", ui.RenderPass("✓"), formatFeedbackID(res.issue.ID, res.issue.Title)) + fmt.Printf("%s Claimed issue: %s\n", ui.RenderPass("✓"), formatFeedbackID(res.Claimed.ID, res.Claimed.Title)) } return nil } +// proxiedReadyClaimer hands back the guarded claim surface for the +// proxied-server provider, through the provider's OWN capability accessor — +// the same two-step proxiedIssueReader performs, and for the same reason: the +// accessor is where a decorator adds its layer. +func proxiedReadyClaimer() (issueops.ReadyClaimer, error) { + if uowProvider == nil { + return nil, errors.New("proxied-server UOW provider not initialized") + } + src, ok := uowProvider.(uow.ReadyClaimerSource) + if !ok { + return nil, fmt.Errorf("proxied-server provider %T does not offer the ready-claim surface", uowProvider) + } + return src.ReadyClaimer() +} + func runReadyProxiedExplain(ctx context.Context, uw uow.UnitOfWork, _ readyInput) error { filter, err := readyExplainFilter() if err != nil { @@ -454,47 +456,6 @@ func runReadyProxiedGated(ctx context.Context, uw uow.UnitOfWork, _ readyInput) return renderGatedReadyMolecules(molecules) } -func buildReadyIssueOutputProxied(ctx context.Context, uw uow.UnitOfWork, issues []*types.Issue) []*types.IssueWithCounts { - if issues == nil { - issues = []*types.Issue{} - } - ids := make([]string, len(issues)) - for i, issue := range issues { - ids[i] = issue.ID - } - - depCounts, _ := uw.DependencyUseCase().CountsByIssueIDs(ctx, ids) - allDeps, _ := uw.DependencyUseCase().GetForIssueIDs(ctx, ids) - commentCounts, _ := uw.CommentUseCase().GetCommentCounts(ctx, ids) - - for _, issue := range issues { - issue.Dependencies = allDeps[issue.ID] - } - - out := make([]*types.IssueWithCounts, len(issues)) - for i, issue := range issues { - counts := depCounts[issue.ID] - if counts == nil { - counts = &types.DependencyCounts{} - } - var parent *string - for _, dep := range allDeps[issue.ID] { - if dep.Type == types.DepParentChild { - parent = &dep.DependsOnID - break - } - } - out[i] = &types.IssueWithCounts{ - Issue: issue, - DependencyCount: counts.DependencyCount, - DependentCount: counts.DependentCount, - CommentCount: commentCounts[issue.ID], - Parent: parent, - } - } - return out -} - func buildParentEpicMapProxied(ctx context.Context, uw uow.UnitOfWork, issues []*types.Issue) map[string]string { if len(issues) == 0 { return nil diff --git a/cmd/bd/reopen.go b/cmd/bd/reopen.go index 59453e459..305d8dd13 100644 --- a/cmd/bd/reopen.go +++ b/cmd/bd/reopen.go @@ -77,6 +77,10 @@ This is more explicit than 'bd update --status open' and emits a Reopened event. Actor: actor, IssueID: fullID, Reason: reason, + // Names the issue for the reason `bd close`'s does, and keeps + // the entry identical across backends: the proxied route + // already writes "bd: reopen ". + Provenance: "bd: reopen " + fullID, }) if err != nil { fmt.Fprintf(os.Stderr, "Error reopening %s: %v\n", fullID, err) diff --git a/cmd/bd/update.go b/cmd/bd/update.go index 37fae153c..2f909f353 100644 --- a/cmd/bd/update.go +++ b/cmd/bd/update.go @@ -23,15 +23,16 @@ import ( "github.com/steveyegge/beads/issueops" ) -// directIssueUpdater is the lifecycle capability the direct update command -// needs. issueops.Lifecycle satisfies it without an adapter. -type directIssueUpdater interface { +// commandIssueUpdater is the lifecycle capability the update command needs. +// issueops.Lifecycle satisfies it without an adapter. +type commandIssueUpdater interface { Update(context.Context, issueops.UpdateRequest) (issueops.UpdateResult, error) } -// directUpdateMutation contains the command-derived values for one direct -// lifecycle update. -type directUpdateMutation struct { +// commandUpdateMutation contains the command-derived values for one lifecycle +// update. Both routes of `bd update` fill it in: the direct one below, and the +// proxied-server claim path in update_proxied_server.go. +type commandUpdateMutation struct { actor string issueID string patch issueops.IssuePatch @@ -39,11 +40,17 @@ type directUpdateMutation struct { force bool expectedAssignee *string expectedStatus *issueops.Status + // provenance names the history entry the write records. Empty takes the + // backend's default, which is what the direct route wants; the proxied + // route spells the message it has always written. + provenance string } -// runDirectUpdateMutation maps a direct command update into its lifecycle -// request and returns the lifecycle result unchanged. -func runDirectUpdateMutation(ctx context.Context, updater directIssueUpdater, mutation directUpdateMutation) (issueops.UpdateResult, error) { +// runCommandUpdateMutation maps a command update into its lifecycle request and +// returns the lifecycle result unchanged. It is the ONE place the command's +// flag semantics become a request — in particular the one --force that means +// two overrides, whose assignee half only applies to an assignee edit. +func runCommandUpdateMutation(ctx context.Context, updater commandIssueUpdater, mutation commandUpdateMutation) (issueops.UpdateResult, error) { return updater.Update(ctx, issueops.UpdateRequest{ Actor: mutation.actor, IssueID: mutation.issueID, @@ -53,6 +60,7 @@ func runDirectUpdateMutation(ctx context.Context, updater directIssueUpdater, mu ForceClosePolicy: mutation.force, ExpectedAssignee: mutation.expectedAssignee, ExpectedStatus: mutation.expectedStatus, + Provenance: mutation.provenance, }) } @@ -506,7 +514,7 @@ pointless).`, // which is why it is conditioned here rather than passed straight // through: `--force -s closed` is now a legitimate way to ask for // the close-policy half alone. - updateResult, updateErr := runDirectUpdateMutation(opsCtx, ops, directUpdateMutation{ + updateResult, updateErr := runCommandUpdateMutation(opsCtx, ops, commandUpdateMutation{ actor: actor, issueID: result.ResolvedID, patch: patch, diff --git a/cmd/bd/update_claim_proxied_test.go b/cmd/bd/update_claim_proxied_test.go new file mode 100644 index 000000000..bc05b7e9a --- /dev/null +++ b/cmd/bd/update_claim_proxied_test.go @@ -0,0 +1,205 @@ +package main + +import ( + "context" + "errors" + "fmt" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/hooks" + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/storage/uow" + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" +) + +// The proxied claim path is a day-one caller of issueops.Lifecycle, and these +// pin what "on the contract" means here: the request it makes, the roles it +// reaches them through, and the fact that it opens no unit of work of its own. +// The claim's behaviour against real Dolt is the integration suite's job. + +type claimRoleProvider struct { + lifecycle *recordingLifecycle + details *types.IssueDetails + readErr error + uows int +} + +func (p *claimRoleProvider) NewUOW(context.Context) (uow.UnitOfWork, error) { + p.uows++ + return nil, errors.New("the claim path opened a unit of work of its own") +} + +func (p *claimRoleProvider) Close(context.Context) error { return nil } + +func (p *claimRoleProvider) IssueLifecycle() (issueops.Lifecycle, error) { return p.lifecycle, nil } + +func (p *claimRoleProvider) IssueReader() (issueops.Reader, error) { + return &stubIssueReader{details: p.details, err: p.readErr}, nil +} + +type recordingLifecycle struct { + issueops.Lifecycle + request issueops.UpdateRequest + result issueops.UpdateResult + err error +} + +func (l *recordingLifecycle) Update(_ context.Context, request issueops.UpdateRequest) (issueops.UpdateResult, error) { + l.request = request + return l.result, l.err +} + +type stubIssueReader struct { + issueops.Reader + details *types.IssueDetails + err error +} + +func (r *stubIssueReader) Get(context.Context, issueops.GetRequest) (*types.IssueDetails, error) { + if r.err != nil { + return nil, r.err + } + return r.details, nil +} + +func withClaimRoleProvider(t *testing.T, p *claimRoleProvider) { + t.Helper() + oldProvider, oldHookRunner := uowProvider, hookRunner + uowProvider = p + hookRunner = hooks.NewRunner(t.TempDir()) // no hooks installed: RunSync no-ops + t.Cleanup(func() { + uowProvider = oldProvider + hookRunner = oldHookRunner + }) +} + +func claimRoleFixture(t *testing.T, before *types.Issue, result issueops.UpdateResult, err error) *claimRoleProvider { + t.Helper() + p := &claimRoleProvider{ + lifecycle: &recordingLifecycle{result: result, err: err}, + details: &types.IssueDetails{Issue: *before}, + } + withClaimRoleProvider(t, p) + return p +} + +func TestProxiedClaimRunsOnTheLifecycleContract(t *testing.T) { + before := &types.Issue{ID: "bd-1", Status: types.StatusOpen} + claimed := &types.Issue{ID: "bd-1", Status: types.StatusInProgress, Assignee: "agent"} + p := claimRoleFixture(t, before, issueops.UpdateResult{Issue: claimed, Changed: true}, nil) + + oldActor := actor + actor = "agent" + t.Cleanup(func() { actor = oldActor }) + + got, fail, err := applyUpdateProxiedOne(context.Background(), "bd-1", &updateInput{claim: true, fields: map[string]any{}}) + if err != nil || fail != nil { + t.Fatalf("applyUpdateProxiedOne: err = %v, fail = %+v", err, fail) + } + if got == nil || got.Assignee != "agent" { + t.Fatalf("updated issue = %+v, want the claimed row", got) + } + + req := p.lifecycle.request + if !req.Claim || req.Actor != "agent" || req.IssueID != "bd-1" { + t.Errorf("request = %+v, want a claim of bd-1 by agent", req) + } + // The commit message this path has always written, carried on the request + // instead of being spelled at the commit site. + if req.Provenance != "bd: update bd-1" { + t.Errorf("Provenance = %q, want the message the proxied update has always written", req.Provenance) + } + // A CLI claim resolves either plane; only the HTTP surface restricts it. + if req.IssuePlaneOnly { + t.Error("the CLI claim restricted the plane; `bd update --claim` has always resolved a wisp id") + } + if req.ExpectedAssignee != nil || req.ExpectedStatus != nil { + t.Errorf("request carries guards a claim may not combine with: %+v", req) + } + if p.uows != 0 { + t.Errorf("the claim path opened %d units of work; the contract owns the transaction", p.uows) + } +} + +// A lost CAS keeps its copy, its per-id failure and its exit code: the batch +// must not turn a refusal into a success, and a claim conflict is not a guard +// mismatch (exit 1, never 13). +func TestProxiedClaimConflictStaysAPerIDFailure(t *testing.T) { + before := &types.Issue{ID: "bd-1", Status: types.StatusInProgress, Assignee: "bob"} + conflict := &issueops.ClaimConflictError{ + IssueID: "bd-1", + Assignee: "bob", + Status: types.StatusInProgress, + // Composed the way both real producers compose it. The fixture must + // carry the prose, not a bare sentinel: ClaimConflictError.Error() is + // a passthrough, so a bare sentinel here would assert against a + // message no producer can emit. + Err: fmt.Errorf("%w%s%s", storage.ErrAlreadyClaimed, storage.ClaimedByFragment, "bob"), + } + claimRoleFixture(t, before, issueops.UpdateResult{}, conflict) + + var ( + got *types.Issue + fail *updateIDFailure + err error + ) + stderr := captureStderrDuring(t, func() { + got, fail, err = applyUpdateProxiedOne(context.Background(), "bd-1", &updateInput{claim: true, fields: map[string]any{}}) + }) + if err != nil { + t.Fatalf("applyUpdateProxiedOne returned a hard error: %v", err) + } + if got != nil || fail == nil { + t.Fatalf("issue = %+v, fail = %+v: a lost claim is a per-id failure", got, fail) + } + if fail.GuardMismatch { + t.Error("a claim conflict must not exit 13; retrying the same claim is not pointless") + } + if want := "Error claiming bd-1: issue already claimed by bob"; !strings.Contains(stderr, want) { + t.Errorf("stderr = %q, want %q", stderr, want) + } +} + +// SIGINT cancels bd's root context mid-batch. That is not a verdict on the +// issue in flight: the loop aborts, rather than recording one "context +// canceled" failure for this id and then the same failure for every id left. +func TestProxiedClaimAbortsTheBatchOnCancellation(t *testing.T) { + for _, cancellation := range []error{context.Canceled, context.DeadlineExceeded} { + t.Run(cancellation.Error(), func(t *testing.T) { + before := &types.Issue{ID: "bd-1", Status: types.StatusOpen} + claimRoleFixture(t, before, issueops.UpdateResult{}, fmt.Errorf("update bd-1: %w", cancellation)) + + got, fail, err := applyUpdateProxiedOne(context.Background(), "bd-1", &updateInput{claim: true, fields: map[string]any{}}) + if !errors.Is(err, cancellation) { + t.Fatalf("err = %v, want %v returned so the batch aborts", err, cancellation) + } + if got != nil || fail != nil { + t.Errorf("issue = %+v, fail = %+v: cancellation is not a per-id verdict", got, fail) + } + }) + } +} + +func TestProxiedClaimReportsAMissingIssue(t *testing.T) { + p := &claimRoleProvider{ + lifecycle: &recordingLifecycle{}, + readErr: issueops.ErrNotFound, + } + withClaimRoleProvider(t, p) + + var fail *updateIDFailure + stderr := captureStderrDuring(t, func() { + _, fail, _ = applyUpdateProxiedOne(context.Background(), "bd-404", &updateInput{claim: true, fields: map[string]any{}}) + }) + if fail == nil || fail.Error != "issue not found" { + t.Fatalf("fail = %+v, want the not-found verdict", fail) + } + if !strings.Contains(stderr, "Issue bd-404 not found") { + t.Errorf("stderr = %q, want the not-found line", stderr) + } + if p.lifecycle.request.IssueID != "" { + t.Error("a missing issue still reached the contract") + } +} diff --git a/cmd/bd/update_lifecycle_test.go b/cmd/bd/update_lifecycle_test.go index 615d8a54e..2811665da 100644 --- a/cmd/bd/update_lifecycle_test.go +++ b/cmd/bd/update_lifecycle_test.go @@ -28,12 +28,12 @@ func TestRunDirectUpdateMutationBuildsLifecycleRequest(t *testing.T) { expectedStatus := issueops.StatusOpen tests := []struct { name string - mutation directUpdateMutation + mutation commandUpdateMutation want issueops.UpdateRequest }{ { name: "force without assignee only overrides close policy", - mutation: directUpdateMutation{ + mutation: commandUpdateMutation{ actor: "writer", issueID: "bd-1", patch: issueops.IssuePatch{Status: issueops.Field[issueops.Status]{Set: true, Value: issueops.StatusClosed}}, @@ -54,7 +54,7 @@ func TestRunDirectUpdateMutationBuildsLifecycleRequest(t *testing.T) { }, { name: "force with assignee overrides both policies", - mutation: directUpdateMutation{ + mutation: commandUpdateMutation{ actor: "writer", issueID: "bd-2", patch: issueops.IssuePatch{ @@ -73,7 +73,7 @@ func TestRunDirectUpdateMutationBuildsLifecycleRequest(t *testing.T) { }, { name: "unforced update preserves guards without overrides", - mutation: directUpdateMutation{ + mutation: commandUpdateMutation{ actor: "writer", issueID: "bd-3", patch: issueops.IssuePatch{Assignee: issueops.Field[string]{Set: true, Value: "next-owner"}}, @@ -93,8 +93,8 @@ func TestRunDirectUpdateMutationBuildsLifecycleRequest(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { updater := &recordingDirectIssueUpdater{} - if _, err := runDirectUpdateMutation(context.Background(), updater, tt.mutation); err != nil { - t.Fatalf("runDirectUpdateMutation: %v", err) + if _, err := runCommandUpdateMutation(context.Background(), updater, tt.mutation); err != nil { + t.Fatalf("runCommandUpdateMutation: %v", err) } if len(updater.requests) != 1 { t.Fatalf("Update calls = %d, want 1", len(updater.requests)) @@ -114,7 +114,7 @@ func TestRunDirectUpdateMutationPropagatesErrorUnchanged(t *testing.T) { err: wantErr, } - result, err := runDirectUpdateMutation(context.Background(), updater, directUpdateMutation{}) + result, err := runCommandUpdateMutation(context.Background(), updater, commandUpdateMutation{}) if result.Issue != wantIssue || !result.Changed { t.Errorf("result = %#v, want issue %p and Changed true", result, wantIssue) } diff --git a/cmd/bd/update_proxied_server.go b/cmd/bd/update_proxied_server.go index e07ac3c3d..d359762c2 100644 --- a/cmd/bd/update_proxied_server.go +++ b/cmd/bd/update_proxied_server.go @@ -13,10 +13,11 @@ import ( "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/storage/domain" "github.com/steveyegge/beads/internal/storage/fs" - "github.com/steveyegge/beads/internal/storage/issueops" + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" "github.com/steveyegge/beads/internal/storage/uow" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" + "github.com/steveyegge/beads/issueops" ) // proxiedUpdateRetryMaxElapsed bounds the whole-attempt retry loop for one @@ -139,6 +140,9 @@ func applyUpdateProxiedOne(ctx context.Context, id string, in *updateInput) (*ty if uowProvider == nil { return nil, nil, HandleError("proxied-server UOW provider not initialized") } + if in.claim { + return applyClaimProxiedOne(ctx, id, in) + } provider := &uowStageProvider{UnitOfWorkProvider: uowProvider} attempt, err := uow.RunTxResultWithin(ctx, provider, proxiedUpdateRetryMaxElapsed, @@ -196,6 +200,225 @@ func applyUpdateProxiedOne(ctx context.Context, id string, in *updateInput) (*ty return attempt.issue, nil, nil } +// proxiedIssueLifecycle asks the unit-of-work provider for the write role, the +// same way proxiedIssueReader asks it for the read one. The accessor is the +// door: a provider that cannot answer says so rather than being wired around. +func proxiedIssueLifecycle() (issueops.Lifecycle, error) { + if uowProvider == nil { + return nil, errors.New("proxied-server UOW provider not initialized") + } + src, ok := uowProvider.(uow.IssueLifecycleSource) + if !ok { + return nil, fmt.Errorf("proxied-server provider %T does not offer the issue-lifecycle surface", uowProvider) + } + return src.IssueLifecycle() +} + +// applyClaimProxiedOne applies one issue's --claim update through +// issueops.Lifecycle rather than through a hand-rolled attempt. +// +// THE CLAIM IS NOT IMPLEMENTED HERE, and that is the point. The CAS, the +// eligibility rules, the claim-pool case, the issue-or-wisp resolve, the +// whole-attempt retry, the commit and the exact text of both refusals belong to +// the contract, which `bd serve`'s claim endpoint now reaches through the same +// call. What stays here is this surface's own protocol: the template guard, the +// per-id failure taxonomy the multi-id batch needs, the notes-overwrite warning +// and the completion hooks — none of which the HTTP surface has, and none of +// which is a claim. +// +// Provenance carries the commit message this path has always written, so `bd +// dolt log` reads the same after the move as before it. The plane is +// deliberately NOT restricted: `bd update --claim` has always resolved a wisp +// id, unlike the HTTP endpoint, which serves durable issues only. +// +// The pre-read is a read of its own, one transaction earlier than the claim, so +// the template guard is advisory in a way it was not when this file did the +// read itself. It guards a command-shaped policy, not an invariant — the +// mutation's own guards are all inside the contract's transaction — and paying +// for it is what lets the claim itself have exactly one implementation. +func applyClaimProxiedOne(ctx context.Context, id string, in *updateInput) (*types.Issue, *updateIDFailure, error) { + ops, err := proxiedIssueLifecycle() + if err != nil { + return nil, nil, HandleError("%v", err) + } + before, fail := proxiedClaimTarget(ctx, id) + if fail != nil { + return nil, fail, nil + } + patch, err := proxiedUpdatePatch(in, before) + if err != nil { + fmt.Fprintf(os.Stderr, "Error updating %s: %v\n", id, err) + return nil, &updateIDFailure{ID: id, Error: fmt.Sprintf("updating: %v", err)}, nil + } + notesOverwritten := replacesExistingNotes(before.Notes, in.fields) + + result, err := runCommandUpdateMutation(ctx, ops, commandUpdateMutation{ + actor: actor, + issueID: id, + patch: patch, + claim: true, + force: in.force, + // The guards are nil by construction: gatherUpdateInput refuses + // --if-assignee/--if-status alongside --claim, which is also what the + // request contract requires of a claim. + provenance: fmt.Sprintf("bd: update %s", id), + }) + if err != nil { + // Cancellation is not a verdict on this issue — SIGINT cancels bd's + // root context, and every remaining id in the batch would fail the same + // way. Abort the batch, as the non-claim path above still does. The + // contract owns the unit of work now, so a commit that itself failed + // with a context error is indistinguishable from a cancellation between + // attempts; aborting is the right call for both. + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return nil, nil, err + } + return nil, proxiedClaimFailure(id, err), nil + } + updated := result.Issue + if updated == nil { + fmt.Fprintf(os.Stderr, "Error updating %s: the claim reported no issue\n", id) + return nil, &updateIDFailure{ID: id, Error: "updating: no issue returned"}, nil + } + // `bd update` has never printed dependency records; the direct route drops + // them for the same reason. + updated.Dependencies = nil + // A CLAIM answers an already-published surface, and that surface is the + // bare row. issueops.ClaimResult says so outright — labels, dependency + // records and comments omitted, and "enriching it is a decision for the + // next revision window, not a side effect of moving the operation onto a + // role." Routing this path through Lifecycle hydrates labels, which is + // exactly that side effect, so they come back off here. + // + // This is what keeps `bd update --claim --json` byte-identical to the v0 + // claim response, which TestProxiedServerServeClaim asserts with an EMPTY + // allowlist: any difference at all between the two surfaces is a real + // divergence. The non-claim update path above is untouched and still + // carries labels. + updated.Labels = nil + updated.Comments = nil + + // Post-commit reporting: the write has landed, so these run exactly once no + // matter how many attempts the contract's conflict retry burned. + if notesOverwritten { + warnNotesReplacement(id) + } + if err := fireProxiedUpdateHooks(ctx, before, updated); err != nil { + fmt.Fprintf(os.Stderr, "warning: %s: %v\n", id, err) + } + return updated, nil, nil +} + +// proxiedClaimTarget reads the row a claim is about through the query role, for +// the three things the claim's own result cannot answer: whether the target is +// a template, whether --notes is about to replace existing notes, and whether +// the update closes an open issue (which fires a second hook). +func proxiedClaimTarget(ctx context.Context, id string) (*types.Issue, *updateIDFailure) { + rd, err := proxiedIssueReader() + if err != nil { + fmt.Fprintf(os.Stderr, "Error resolving %s: %v\n", id, err) + return nil, &updateIDFailure{ID: id, Error: fmt.Sprintf("resolving issue: %v", err)} + } + details, err := rd.Get(ctx, issueops.GetRequest{ID: id}) + if err != nil { + if errors.Is(err, issueops.ErrNotFound) { + fmt.Fprintf(os.Stderr, "Issue %s not found\n", id) + return nil, &updateIDFailure{ID: id, Error: "issue not found"} + } + fmt.Fprintf(os.Stderr, "Error resolving %s: %v\n", id, err) + return nil, &updateIDFailure{ID: id, Error: fmt.Sprintf("resolving issue: %v", err)} + } + current := &details.Issue + if err := validateIssueUpdatable(id, current); err != nil { + fmt.Fprintf(os.Stderr, "%s\n", err) + return nil, &updateIDFailure{ID: id, Error: err.Error()} + } + return current, nil +} + +// proxiedClaimFailure sorts a refused claim into the same per-id verdicts, with +// the same copy, the hand-rolled attempt below produces. A guard refusal sets +// GuardMismatch so the batch exits 13 rather than 1. +// +// The one verdict it cannot reproduce is stage attribution: "opening unit of +// work" and "committing" were told apart by watching the provider this path no +// longer owns, so both now read as the generic update failure. That is the +// price of the contract owning the transaction, and it costs a word in the +// message, not a verdict — the id still fails, loudly and non-zero. +func proxiedClaimFailure(id string, err error) *updateIDFailure { + switch { + case errors.Is(err, storage.ErrNotFound): + fmt.Fprintf(os.Stderr, "Issue %s not found\n", id) + return &updateIDFailure{ID: id, Error: "issue not found"} + case errors.Is(err, storage.ErrAlreadyClaimed), errors.Is(err, storage.ErrNotClaimable): + fmt.Fprintf(os.Stderr, "Error claiming %s: %v\n", id, err) + return &updateIDFailure{ID: id, Error: fmt.Sprintf("claiming issue: %v", err)} + case errors.Is(err, storage.ErrCloseOpenChildren): + fmt.Fprintf(os.Stderr, "%v\n", err) + return &updateIDFailure{ID: id, Error: err.Error()} + case errors.Is(err, storage.ErrCloseBlocked): + fmt.Fprintf(os.Stderr, "%v (use --force to override)\n", err) + return &updateIDFailure{ID: id, Error: fmt.Sprintf("%v (use --force to override)", err)} + case uow.IsSerializationError(err): + // The contract spent its retry budget losing Dolt's commit-time merge. + // The write did NOT land; fail loudly instead of exiting 0. + fmt.Fprintf(os.Stderr, "Error updating %s: retries exhausted on write conflicts: %v\n", id, err) + return &updateIDFailure{ID: id, Error: fmt.Sprintf("retries exhausted on write conflicts: %v", err)} + case isGuardMismatch(err): + fmt.Fprintf(os.Stderr, "Error updating %s: %v\n", id, err) + return &updateIDFailure{ID: id, Error: fmt.Sprintf("precondition failed: %v", err), GuardMismatch: true} + default: + fmt.Fprintf(os.Stderr, "Error updating %s: %v\n", id, err) + return &updateIDFailure{ID: id, Error: fmt.Sprintf("updating: %v", err)} + } +} + +// proxiedUpdatePatch reshapes gathered CLI input into the contract's typed +// patch. The field map goes through the same builder the direct route uses; the +// edits this input keeps beside that map (labels, reparent, the merge-shaped +// note and metadata edits) are folded in here, so both routes end up describing +// the same mutation. +// +// The merge-shaped edits stay merge-shaped: the contract resolves them against +// the row re-read inside the mutation transaction. Pre-merging them against +// `before` is what silently erased keys a concurrent writer had committed. +func proxiedUpdatePatch(in *updateInput, before *types.Issue) (issueops.IssuePatch, error) { + patch, err := buildUpdatePatch(in.fields) + if err != nil { + return issueops.IssuePatch{}, err + } + patch.Labels.Add = in.addLabels + patch.Labels.Remove = in.removeLabels + if in.setLabels != nil { + patch.Labels.Replace = setField(*in.setLabels) + } + if in.reparent != nil { + patch.ParentID = setField(*in.reparent) + } + if in.hasAppendNotes { + patch.AppendNotes = setField(in.appendNotes) + } + if len(in.mergeMetadataIn) > 0 { + patch.Metadata.Merge = setField(in.mergeMetadataIn) + } + if len(in.setMetadata) > 0 { + set, err := parseSetMetadataFlags(in.setMetadata) + if err != nil { + return issueops.IssuePatch{}, err + } + patch.Metadata.Set = set + } + if len(in.unsetMetadata) > 0 { + patch.Metadata.Unset = in.unsetMetadata + } + // GH#3233: --defer="" restores ready visibility only if the issue was + // actually deferred, exactly as the direct route decides it. + if in.clearDeferStatus && before.Status == types.StatusDeferred { + patch.Status = setField(types.StatusOpen) + } + return patch, nil +} + // applyUpdateProxiedAttempt runs one full read-merge-write attempt in the fresh // unit of work handed to it. It returns a serialization failure verbatim so the // shared retry loop redoes the whole attempt — the server-side rollback @@ -359,22 +582,22 @@ func buildUpdateSpecForIssue(current *types.Issue, in *updateInput) domain.Updat // snapshot — silently erased keys a concurrent writer committed after our // snapshot was taken: both processes exited 0, one write vanished. if in.hasAppendNotes { - fields[issueops.OpAppendNotes] = in.appendNotes + fields[storageissueops.OpAppendNotes] = in.appendNotes } if len(in.mergeMetadataIn) > 0 { - fields[issueops.OpMergeMetadata] = in.mergeMetadataIn + fields[storageissueops.OpMergeMetadata] = in.mergeMetadataIn } if len(in.setMetadata) > 0 { - fields[issueops.OpSetMetadata] = in.setMetadata + fields[storageissueops.OpSetMetadata] = in.setMetadata } if len(in.unsetMetadata) > 0 { - fields[issueops.OpUnsetMetadata] = in.unsetMetadata + fields[storageissueops.OpUnsetMetadata] = in.unsetMetadata } // --force means both of its halves here too. The assignee half is applied // above by validateIssueReassignable; this is the close-policy half, which // the repository pops before it validates fields. if in.force { - fields[issueops.OpForceClosePolicy] = true + fields[storageissueops.OpForceClosePolicy] = true } return domain.UpdateSpec{ diff --git a/go.sum b/go.sum index 2149fcd6f..7d34f19b3 100644 --- a/go.sum +++ b/go.sum @@ -44,46 +44,143 @@ cloud.google.com/go v0.100.1/go.mod h1:fs4QogzfH5n2pBXBP9vRiU+eCny7lD2vmFZy79Iuw cloud.google.com/go v0.100.2/go.mod h1:4Xra9TjzAeYHrl5+oeLlzbM2k3mjVhZh4UqTZ//w99A= cloud.google.com/go v0.120.0 h1:wc6bgG9DHyKqF5/vQvX1CiZrtHnxJjBlKUyF9nP6meA= cloud.google.com/go v0.120.0/go.mod h1:/beW32s8/pGRuj4IILWQNd4uuebeT4dkOhKmkfit64Q= +cloud.google.com/go/accessapproval v1.8.6/go.mod h1:FfmTs7Emex5UvfnnpMkhuNkRCP85URnBFt5ClLxhZaQ= +cloud.google.com/go/accesscontextmanager v1.9.6/go.mod h1:884XHwy1AQpCX5Cj2VqYse77gfLaq9f8emE2bYriilk= +cloud.google.com/go/aiplatform v1.85.0/go.mod h1:S4DIKz3TFLSt7ooF2aCRdAqsUR4v/YDXUoHqn5P0EFc= +cloud.google.com/go/analytics v0.28.0/go.mod h1:hNT09bdzGB3HsL7DBhZkoPi4t5yzZPZROoFv+JzGR7I= +cloud.google.com/go/apigateway v1.7.6/go.mod h1:SiBx36VPjShaOCk8Emf63M2t2c1yF+I7mYZaId7OHiA= +cloud.google.com/go/apigeeconnect v1.7.6/go.mod h1:zqDhHY99YSn2li6OeEjFpAlhXYnXKl6DFb/fGu0ye2w= +cloud.google.com/go/apigeeregistry v0.9.6/go.mod h1:AFEepJBKPtGDfgabG2HWaLH453VVWWFFs3P4W00jbPs= +cloud.google.com/go/appengine v1.9.6/go.mod h1:jPp9T7Opvzl97qytaRGPwoH7pFI3GAcLDaui1K8PNjY= +cloud.google.com/go/area120 v0.9.6/go.mod h1:qKSokqe0iTmwBDA3tbLWonMEnh0pMAH4YxiceiHUed4= +cloud.google.com/go/artifactregistry v1.17.1/go.mod h1:06gLv5QwQPWtaudI2fWO37gfwwRUHwxm3gA8Fe568Hc= +cloud.google.com/go/asset v1.21.0/go.mod h1:0lMJ0STdyImZDSCB8B3i/+lzIquLBpJ9KZ4pyRvzccM= +cloud.google.com/go/assuredworkloads v1.12.6/go.mod h1:QyZHd7nH08fmZ+G4ElihV1zoZ7H0FQCpgS0YWtwjCKo= cloud.google.com/go/auth v0.16.2 h1:QvBAGFPLrDeoiNjyfVunhQ10HKNYuOwZ5noee0M5df4= cloud.google.com/go/auth v0.16.2/go.mod h1:sRBas2Y1fB1vZTdurouM0AzuYQBMZinrUYL8EufhtEA= cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= +cloud.google.com/go/automl v1.14.7/go.mod h1:8a4XbIH5pdvrReOU72oB+H3pOw2JBxo9XTk39oljObE= +cloud.google.com/go/baremetalsolution v1.3.6/go.mod h1:7/CS0LzpLccRGO0HL3q2Rofxas2JwjREKut414sE9iM= +cloud.google.com/go/batch v1.12.2/go.mod h1:tbnuTN/Iw59/n1yjAYKV2aZUjvMM2VJqAgvUgft6UEU= +cloud.google.com/go/beyondcorp v1.1.6/go.mod h1:V1PigSWPGh5L/vRRmyutfnjAbkxLI2aWqJDdxKbwvsQ= cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg= cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc= cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ= +cloud.google.com/go/bigquery v1.67.0/go.mod h1:HQeP1AHFuAz0Y55heDSb0cjZIhnEkuwFRBGo6EEKHug= +cloud.google.com/go/bigtable v1.37.0/go.mod h1:HXqddP6hduwzrtiTCqZPpj9ij4hGZb4Zy1WF/dT+yaU= +cloud.google.com/go/billing v1.20.4/go.mod h1:hBm7iUmGKGCnBm6Wp439YgEdt+OnefEq/Ib9SlJYxIU= +cloud.google.com/go/binaryauthorization v1.9.5/go.mod h1:CV5GkS2eiY461Bzv+OH3r5/AsuB6zny+MruRju3ccB8= +cloud.google.com/go/certificatemanager v1.9.5/go.mod h1:kn7gxT/80oVGhjL8rurMUYD36AOimgtzSBPadtAeffs= +cloud.google.com/go/channel v1.19.5/go.mod h1:vevu+LK8Oy1Yuf7lcpDbkQQQm5I7oiY5fFTn3uwfQLY= +cloud.google.com/go/cloudbuild v1.22.2/go.mod h1:rPyXfINSgMqMZvuTk1DbZcbKYtvbYF/i9IXQ7eeEMIM= +cloud.google.com/go/clouddms v1.8.7/go.mod h1:DhWLd3nzHP8GoHkA6hOhso0R9Iou+IGggNqlVaq/KZ4= +cloud.google.com/go/cloudtasks v1.13.6/go.mod h1:/IDaQqGKMixD+ayM43CfsvWF2k36GeomEuy9gL4gLmU= cloud.google.com/go/compute v0.1.0/go.mod h1:GAesmwr110a34z04OlxYkATPBEfVhkymfTBXtfbBFow= cloud.google.com/go/compute v1.2.0/go.mod h1:xlogom/6gr8RJGBe7nT2eGsQYAFUbbv8dbC29qE3Xmw= cloud.google.com/go/compute v1.3.0/go.mod h1:cCZiE1NHEtai4wiufUhW8I8S1JKkAnhnQJWM7YD99wM= cloud.google.com/go/compute v1.5.0/go.mod h1:9SMHyhJlzhlkJqrPAc839t2BZFTSk6Jdj6mkzQJeu0M= +cloud.google.com/go/compute v1.37.0/go.mod h1:AsK4VqrSyXBo4SMbRtfAO1VfaMjUEjEwv1UB/AwVp5Q= cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs= cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10= +cloud.google.com/go/contactcenterinsights v1.17.3/go.mod h1:7Uu2CpxS3f6XxhRdlEzYAkrChpR5P5QfcdGAFEdHOG8= +cloud.google.com/go/container v1.42.4/go.mod h1:wf9lKc3ayWVbbV/IxKIDzT7E+1KQgzkzdxEJpj1pebE= +cloud.google.com/go/containeranalysis v0.14.1/go.mod h1:28e+tlZgauWGHmEbnI5UfIsjMmrkoR1tFN0K2i71jBI= +cloud.google.com/go/datacatalog v1.26.0/go.mod h1:bLN2HLBAwB3kLTFT5ZKLHVPj/weNz6bR0c7nYp0LE14= +cloud.google.com/go/dataflow v0.10.6/go.mod h1:Vi0pTYCVGPnM2hWOQRyErovqTu2xt2sr8Rp4ECACwUI= +cloud.google.com/go/dataform v0.11.2/go.mod h1:IMmueJPEKpptT2ZLWlvIYjw6P/mYHHxA7/SUBiXqZUY= +cloud.google.com/go/datafusion v1.8.6/go.mod h1:fCyKJF2zUKC+O3hc2F9ja5EUCAbT4zcH692z8HiFZFw= +cloud.google.com/go/datalabeling v0.9.6/go.mod h1:n7o4x0vtPensZOoFwFa4UfZgkSZm8Qs0Pg/T3kQjXSM= +cloud.google.com/go/dataplex v1.25.2/go.mod h1:AH2/a7eCYvFP58scJGR7YlSY9qEhM8jq5IeOA/32IZ0= +cloud.google.com/go/dataproc/v2 v2.11.2/go.mod h1:xwukBjtfiO4vMEa1VdqyFLqJmcv7t3lo+PbLDcTEw+g= +cloud.google.com/go/dataqna v0.9.6/go.mod h1:rjnNwjh8l3ZsvrANy6pWseBJL2/tJpCcBwJV8XCx4kU= cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= +cloud.google.com/go/datastore v1.20.0/go.mod h1:uFo3e+aEpRfHgtp5pp0+6M0o147KoPaYNaPAKpfh8Ew= +cloud.google.com/go/datastream v1.14.1/go.mod h1:JqMKXq/e0OMkEgfYe0nP+lDye5G2IhIlmencWxmesMo= +cloud.google.com/go/deploy v1.27.1/go.mod h1:il2gxiMgV3AMlySoQYe54/xpgVDoEh185nj4XjJ+GRk= +cloud.google.com/go/dialogflow v1.68.2/go.mod h1:E0Ocrhf5/nANZzBju8RX8rONf0PuIvz2fVj3XkbAhiY= +cloud.google.com/go/dlp v1.22.1/go.mod h1:Gc7tGo1UJJTBRt4OvNQhm8XEQ0i9VidAiGXBVtsftjM= +cloud.google.com/go/documentai v1.37.0/go.mod h1:qAf3ewuIUJgvSHQmmUWvM3Ogsr5A16U2WPHmiJldvLA= +cloud.google.com/go/domains v0.10.6/go.mod h1:3xzG+hASKsVBA8dOPc4cIaoV3OdBHl1qgUpAvXK7pGY= +cloud.google.com/go/edgecontainer v1.4.3/go.mod h1:q9Ojw2ox0uhAvFisnfPRAXFTB1nfRIOIXVWzdXMZLcE= +cloud.google.com/go/errorreporting v0.3.2/go.mod h1:s5kjs5r3l6A8UUyIsgvAhGq6tkqyBCUss0FRpsoVTww= +cloud.google.com/go/essentialcontacts v1.7.6/go.mod h1:/Ycn2egr4+XfmAfxpLYsJeJlVf9MVnq9V7OMQr9R4lA= +cloud.google.com/go/eventarc v1.15.5/go.mod h1:vDCqGqyY7SRiickhEGt1Zhuj81Ya4F/NtwwL3OZNskg= +cloud.google.com/go/filestore v1.10.2/go.mod h1:w0Pr8uQeSRQfCPRsL0sYKW6NKyooRgixCkV9yyLykR4= cloud.google.com/go/firestore v1.6.1/go.mod h1:asNXNOzBdyVQmEU+ggO8UPodTkEVFW5Qx+rwHnAz+EY= +cloud.google.com/go/firestore v1.18.0/go.mod h1:5ye0v48PhseZBdcl0qbl3uttu7FIEwEYVaWm0UIEOEU= +cloud.google.com/go/functions v1.19.6/go.mod h1:0G0RnIlbM4MJEycfbPZlCzSf2lPOjL7toLDwl+r0ZBw= +cloud.google.com/go/gkebackup v1.7.0/go.mod h1:oPHXUc6X6tg6Zf/7QmKOfXOFaVzBEgMWpLDb4LqngWA= +cloud.google.com/go/gkeconnect v0.12.4/go.mod h1:bvpU9EbBpZnXGo3nqJ1pzbHWIfA9fYqgBMJ1VjxaZdk= +cloud.google.com/go/gkehub v0.15.6/go.mod h1:sRT0cOPAgI1jUJrS3gzwdYCJ1NEzVVwmnMKEwrS2QaM= +cloud.google.com/go/gkemulticloud v1.5.3/go.mod h1:KPFf+/RcfvmuScqwS9/2MF5exZAmXSuoSLPuaQ98Xlk= +cloud.google.com/go/gsuiteaddons v1.7.7/go.mod h1:zTGmmKG/GEBCONsvMOY2ckDiEsq3FN+lzWGUiXccF9o= cloud.google.com/go/iam v0.1.0/go.mod h1:vcUNEa0pEm0qRVpmWepWaFMIAI8/hjB9mO8rNCJtF6c= cloud.google.com/go/iam v0.1.1/go.mod h1:CKqrcnI/suGpybEHxZ7BMehL0oA4LpdyJdUlTl9jVMw= cloud.google.com/go/iam v0.3.0/go.mod h1:XzJPvDayI+9zsASAFO68Hk07u3z+f+JrT2xXNdp4bnY= cloud.google.com/go/iam v1.5.2 h1:qgFRAGEmd8z6dJ/qyEchAuL9jpswyODjA2lS+w234g8= cloud.google.com/go/iam v1.5.2/go.mod h1:SE1vg0N81zQqLzQEwxL2WI6yhetBdbNQuTvIKCSkUHE= +cloud.google.com/go/iap v1.11.1/go.mod h1:qFipMJ4nOIv4yDHZxn31PiS8QxJJH2FlxgH9aFauejw= +cloud.google.com/go/ids v1.5.6/go.mod h1:y3SGLmEf9KiwKsH7OHvYYVNIJAtXybqsD2z8gppsziQ= +cloud.google.com/go/iot v1.8.6/go.mod h1:MThnkiihNkMysWNeNje2Hp0GSOpEq2Wkb/DkBCVYa0U= cloud.google.com/go/kms v1.1.0/go.mod h1:WdbppnCDMDpOvoYBMn1+gNmOeEoZYqAv+HeuKARGCXI= cloud.google.com/go/kms v1.4.0/go.mod h1:fajBHndQ+6ubNw6Ss2sSd+SWvjL26RNo/dr7uxsnnOA= +cloud.google.com/go/kms v1.21.2/go.mod h1:8wkMtHV/9Z8mLXEXr1GK7xPSBdi6knuLXIhqjuWcI6w= +cloud.google.com/go/language v1.14.5/go.mod h1:nl2cyAVjcBct1Hk73tzxuKebk0t2eULFCaruhetdZIA= +cloud.google.com/go/lifesciences v0.10.6/go.mod h1:1nnZwaZcBThDujs9wXzECnd1S5d+UiDkPuJWAmhRi7Q= cloud.google.com/go/logging v1.13.0 h1:7j0HgAp0B94o1YRDqiqm26w4q1rDMH7XNRU34lJXHYc= cloud.google.com/go/logging v1.13.0/go.mod h1:36CoKh6KA/M0PbhPKMq6/qety2DCAErbhXT62TuXALA= cloud.google.com/go/longrunning v0.6.7 h1:IGtfDWHhQCgCjwQjV9iiLnUta9LBCo8R9QmAFsS/PrE= cloud.google.com/go/longrunning v0.6.7/go.mod h1:EAFV3IZAKmM56TyiE6VAP3VoTzhZzySwI/YI1s/nRsY= +cloud.google.com/go/managedidentities v1.7.6/go.mod h1:pYCWPaI1AvR8Q027Vtp+SFSM/VOVgbjBF4rxp1/z5p4= +cloud.google.com/go/maps v1.20.4/go.mod h1:Act0Ws4HffrECH+pL8YYy1scdSLegov7+0c6gvKqRzI= +cloud.google.com/go/mediatranslation v0.9.6/go.mod h1:WS3QmObhRtr2Xu5laJBQSsjnWFPPthsyetlOyT9fJvE= +cloud.google.com/go/memcache v1.11.6/go.mod h1:ZM6xr1mw3F8TWO+In7eq9rKlJc3jlX2MDt4+4H+/+cc= +cloud.google.com/go/metastore v1.14.6/go.mod h1:iDbuGwlDr552EkWA5E1Y/4hHme3cLv3ZxArKHXjS2OU= cloud.google.com/go/monitoring v1.1.0/go.mod h1:L81pzz7HKn14QCMaCs6NTQkdBnE87TElyanS95vIcl4= cloud.google.com/go/monitoring v1.4.0/go.mod h1:y6xnxfwI3hTFWOdkOaD7nfJVlwuC3/mS/5kvtT131p4= cloud.google.com/go/monitoring v1.24.2 h1:5OTsoJ1dXYIiMiuL+sYscLc9BumrL3CarVLL7dd7lHM= cloud.google.com/go/monitoring v1.24.2/go.mod h1:x7yzPWcgDRnPEv3sI+jJGBkwl5qINf+6qY4eq0I9B4U= +cloud.google.com/go/networkconnectivity v1.17.1/go.mod h1:DTZCq8POTkHgAlOAAEDQF3cMEr/B9k1ZbpklqvHEBtg= +cloud.google.com/go/networkmanagement v1.19.1/go.mod h1:icgk265dNnilxQzpr6rO9WuAuuCmUOqq9H6WBeM2Af4= +cloud.google.com/go/networksecurity v0.10.6/go.mod h1:FTZvabFPvK2kR/MRIH3l/OoQ/i53eSix2KA1vhBMJec= +cloud.google.com/go/notebooks v1.12.6/go.mod h1:3Z4TMEqAKP3pu6DI/U+aEXrNJw9hGZIVbp+l3zw8EuA= +cloud.google.com/go/optimization v1.7.6/go.mod h1:4MeQslrSJGv+FY4rg0hnZBR/tBX2awJ1gXYp6jZpsYY= +cloud.google.com/go/orchestration v1.11.9/go.mod h1:KKXK67ROQaPt7AxUS1V/iK0Gs8yabn3bzJ1cLHw4XBg= +cloud.google.com/go/orgpolicy v1.15.0/go.mod h1:NTQLwgS8N5cJtdfK55tAnMGtvPSsy95JJhESwYHaJVs= +cloud.google.com/go/osconfig v1.14.5/go.mod h1:XH+NjBVat41I/+xgQzKOJEhuC4xI7lX2INE5SWnVr9U= +cloud.google.com/go/oslogin v1.14.6/go.mod h1:xEvcRZTkMXHfNSKdZ8adxD6wvRzeyAq3cQX3F3kbMRw= +cloud.google.com/go/phishingprotection v0.9.6/go.mod h1:VmuGg03DCI0wRp/FLSvNyjFj+J8V7+uITgHjCD/x4RQ= +cloud.google.com/go/policytroubleshooter v1.11.6/go.mod h1:jdjYGIveoYolk38Dm2JjS5mPkn8IjVqPsDHccTMu3mY= +cloud.google.com/go/privatecatalog v0.10.7/go.mod h1:Fo/PF/B6m4A9vUYt0nEF1xd0U6Kk19/Je3eZGrQ6l60= cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjpRVR+TSU= cloud.google.com/go/pubsub v1.19.0/go.mod h1:/O9kmSe9bb9KRnIAWkzmqhPjHo6LtzGOBYd/kr06XSs= +cloud.google.com/go/pubsub v1.49.0/go.mod h1:K1FswTWP+C1tI/nfi3HQecoVeFvL4HUOB1tdaNXKhUY= +cloud.google.com/go/pubsublite v1.8.2/go.mod h1:4r8GSa9NznExjuLPEJlF1VjOPOpgf3IT6k8x/YgaOPI= +cloud.google.com/go/recaptchaenterprise/v2 v2.20.4/go.mod h1:3H8nb8j8N7Ss2eJ+zr+/H7gyorfzcxiDEtVBDvDjwDQ= +cloud.google.com/go/recommendationengine v0.9.6/go.mod h1:nZnjKJu1vvoxbmuRvLB5NwGuh6cDMMQdOLXTnkukUOE= +cloud.google.com/go/recommender v1.13.5/go.mod h1:v7x/fzk38oC62TsN5Qkdpn0eoMBh610UgArJtDIgH/E= +cloud.google.com/go/redis v1.18.2/go.mod h1:q6mPRhLiR2uLf584Lcl4tsiRn0xiFlu6fnJLwCORMtY= +cloud.google.com/go/resourcemanager v1.10.6/go.mod h1:VqMoDQ03W4yZmxzLPrB+RuAoVkHDS5tFUUQUhOtnRTg= +cloud.google.com/go/resourcesettings v1.8.3/go.mod h1:BzgfXFHIWOOmHe6ZV9+r3OWfpHJgnqXy8jqwx4zTMLw= +cloud.google.com/go/retail v1.20.0/go.mod h1:1CXWDZDJTOsK6lPjkv67gValP9+h1TMadTC9NpFFr9s= +cloud.google.com/go/run v1.9.3/go.mod h1:Si9yDIkUGr5vsXE2QVSWFmAjJkv/O8s3tJ1eTxw3p1o= +cloud.google.com/go/scheduler v1.11.7/go.mod h1:gqYs8ndLx2M5D0oMJh48aGS630YYvC432tHCnVWN13s= cloud.google.com/go/secretmanager v1.3.0/go.mod h1:+oLTkouyiYiabAQNugCeTS3PAArGiMJuBqvJnJsyH+U= +cloud.google.com/go/secretmanager v1.14.7/go.mod h1:uRuB4F6NTFbg0vLQ6HsT7PSsfbY7FqHbtJP1J94qxGc= +cloud.google.com/go/security v1.18.5/go.mod h1:D1wuUkDwGqTKD0Nv7d4Fn2Dc53POJSmO4tlg1K1iS7s= +cloud.google.com/go/securitycenter v1.36.2/go.mod h1:80ocoXS4SNWxmpqeEPhttYrmlQzCPVGaPzL3wVcoJvE= +cloud.google.com/go/servicedirectory v1.12.6/go.mod h1:OojC1KhOMDYC45oyTn3Mup08FY/S0Kj7I58dxUMMTpg= +cloud.google.com/go/shell v1.8.6/go.mod h1:GNbTWf1QA/eEtYa+kWSr+ef/XTCDkUzRpV3JPw0LqSk= +cloud.google.com/go/spanner v1.80.0/go.mod h1:XQWUqx9r8Giw6gNh0Gu8xYfz7O+dAKouAkFCxG/mZC8= +cloud.google.com/go/speech v1.27.1/go.mod h1:efCfklHFL4Flxcdt9gpEMEJh9MupaBzw3QiSOVeJ6ck= cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= @@ -93,10 +190,24 @@ cloud.google.com/go/storage v1.12.0/go.mod h1:fFLk2dp2oAhDz8QFKwqrjdJvxSp/W2g7ni cloud.google.com/go/storage v1.21.0/go.mod h1:XmRlxkgPjlBONznT2dDUU/5XlpU2OjMnKuqnZI01LAA= cloud.google.com/go/storage v1.50.0 h1:3TbVkzTooBvnZsk7WaAQfOsNrdoM8QHusXA1cpk6QJs= cloud.google.com/go/storage v1.50.0/go.mod h1:l7XeiD//vx5lfqE3RavfmU9yvk5Pp0Zhcv482poyafY= +cloud.google.com/go/storagetransfer v1.12.4/go.mod h1:p1xLKvpt78aQFRJ8lZGYArgFuL4wljFzitPZoYjl/8A= +cloud.google.com/go/talent v1.8.3/go.mod h1:oD3/BilJpJX8/ad8ZUAxlXHCslTg2YBbafFH3ciZSLQ= +cloud.google.com/go/texttospeech v1.12.1/go.mod h1:f8vrD3OXAKTRr4eL0TPjZgYQhiN6ti/tKM3i1Uub5X0= +cloud.google.com/go/tpu v1.8.3/go.mod h1:Do6Gq+/Jx6Xs3LcY2WhHyGwKDKVw++9jIJp+X+0rxRE= cloud.google.com/go/trace v1.0.0/go.mod h1:4iErSByzxkyHWzzlAj63/Gmjz0NH1ASqhJguHpGcr6A= cloud.google.com/go/trace v1.2.0/go.mod h1:Wc8y/uYyOhPy12KEnXG9XGrvfMz5F5SrYecQlbW1rwM= cloud.google.com/go/trace v1.11.6 h1:2O2zjPzqPYAHrn3OKl029qlqG6W8ZdYaOWRyr8NgMT4= cloud.google.com/go/trace v1.11.6/go.mod h1:GA855OeDEBiBMzcckLPE2kDunIpC72N+Pq8WFieFjnI= +cloud.google.com/go/translate v1.12.5/go.mod h1:o/v+QG/bdtBV1d1edmtau0PwTfActvxPk/gtqdSDBi4= +cloud.google.com/go/video v1.23.5/go.mod h1:ZSpGFCpfTOTmb1IkmHNGC/9yI3TjIa/vkkOKBDo0Vpo= +cloud.google.com/go/videointelligence v1.12.6/go.mod h1:/l34WMndN5/bt04lHodxiYchLVuWPQjCU6SaiTswrIw= +cloud.google.com/go/vision/v2 v2.9.5/go.mod h1:1SiNZPpypqZDbOzU052ZYRiyKjwOcyqgGgqQCI/nlx8= +cloud.google.com/go/vmmigration v1.8.6/go.mod h1:uZ6/KXmekwK3JmC8PzBM/cKQmq404TTfWtThF6bbf0U= +cloud.google.com/go/vmwareengine v1.3.5/go.mod h1:QuVu2/b/eo8zcIkxBYY5QSwiyEcAy6dInI7N+keI+Jg= +cloud.google.com/go/vpcaccess v1.8.6/go.mod h1:61yymNplV1hAbo8+kBOFO7Vs+4ZHYI244rSFgmsHC6E= +cloud.google.com/go/webrisk v1.11.1/go.mod h1:+9SaepGg2lcp1p0pXuHyz3R2Yi2fHKKb4c1Q9y0qbtA= +cloud.google.com/go/websecurityscanner v1.7.6/go.mod h1:ucaaTO5JESFn5f2pjdX01wGbQ8D6h79KHrmO2uGZeiY= +cloud.google.com/go/workflows v1.14.2/go.mod h1:5nqKjMD+MsJs41sJhdVrETgvD5cOK3hUcAs8ygqYvXQ= contrib.go.opencensus.io/exporter/aws v0.0.0-20200617204711-c478e41e60e9/go.mod h1:uu1P0UCM/6RbsMrgPa98ll8ZcHM858i/AD06a9aLRCA= contrib.go.opencensus.io/exporter/stackdriver v0.13.10/go.mod h1:I5htMbyta491eUxufwwZPQdcKvvgzMB4O9ni41YnIM8= contrib.go.opencensus.io/integrations/ocsql v0.1.7/go.mod h1:8DsSdjz3F+APR+0z0WkU1aRorQCFfRxvqjUUPMbF3fE= @@ -200,8 +311,11 @@ github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= github.com/Shopify/toxiproxy/v2 v2.5.0 h1:i4LPT+qrSlKNtQf5QliVjdP08GyAH8+BUIc9gT0eahc= github.com/Shopify/toxiproxy/v2 v2.5.0/go.mod h1:yhM2epWtAmel9CB8r2+L+PCmhH6yH2pITaPAo7jxJl0= +github.com/VividCortex/ewma v1.2.0/go.mod h1:nz4BbCtbLyFDeC9SUHbtcT5644juEuWfUAUnGx7j5l4= github.com/abiosoft/readline v0.0.0-20180607040430-155bce2042db h1:CjPUSXOiYptLbTdr1RceuZgSFDQ7U15ITERUGrUORx8= github.com/abiosoft/readline v0.0.0-20180607040430-155bce2042db/go.mod h1:rB3B4rKii8V21ydCbIzH5hZiCQE7f5E9SzUb/ZZx530= +github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d/go.mod h1:asat636LX7Bqt5lYEZ27JNDcqxfjdBQuJ/MM4CN/Lzo= +github.com/agnivade/levenshtein v1.2.1/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU= github.com/ajstarks/svgo v0.0.0-20180226025133-644b8db467af/go.mod h1:K08gAheRH3/J6wwsYMMT4xOr94bZjxIelGM0+d/wbFw= github.com/ajstarks/svgo v0.0.0-20211024235047-1546f124cd8b h1:slYM766cy2nI3BwyRiyQj/Ud48djTMtMebDqepE95rw= github.com/ajstarks/svgo v0.0.0-20211024235047-1546f124cd8b/go.mod h1:1KcenG0jGWcpt8ov532z81sp/kMMUG485J2InIOyADM= @@ -211,10 +325,13 @@ github.com/alecthomas/chroma/v2 v2.20.0 h1:sfIHpxPyR07/Oylvmcai3X/exDlE8+FA820NT github.com/alecthomas/chroma/v2 v2.20.0/go.mod h1:e7tViK0xh/Nf4BYHl00ycY6rV7b8iXBksI9E359yNmA= github.com/alecthomas/repr v0.5.1 h1:E3G4t2QbHTSNpPKBgMTln5KLkZHLOcU7r37J4pXBuIg= github.com/alecthomas/repr v0.5.1/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= +github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE= github.com/aliyun/aliyun-oss-go-sdk v3.0.2+incompatible h1:8psS8a+wKfiLt1iVDX79F7Y6wUM49Lcha2FMXt4UM8g= github.com/aliyun/aliyun-oss-go-sdk v3.0.2+incompatible/go.mod h1:T/Aws4fEfogEE9v+HPhhw+CntffsBHJ8nXQCwKr0/g8= github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 h1:bvNMNQO63//z+xNgfBlViaCIJKLlCJ6/fmUseuG0wVQ= github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8= +github.com/andybalholm/cascadia v1.3.4/go.mod h1:BLRmbRjpEtNKieZOCCvYj4RqN+KRA41GBe/5O+G93kM= github.com/anthropics/anthropic-sdk-go v1.61.0 h1:JRTnm1tPqn5xo1xd1zfrcFDlcoWXVMvV1K68YmhpZKw= github.com/anthropics/anthropic-sdk-go v1.61.0/go.mod h1:3EfIfmFqxH6rbiLcIP4tPFyXL/IHakx2wDG4OU+TIEI= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= @@ -227,6 +344,7 @@ github.com/apache/thrift v0.23.0 h1:wKR6YnefQSEnxpEfmgTPuJibNG4bF0p2TK34tHLWi3s= github.com/apache/thrift v0.23.0/go.mod h1:zPt6WxgvTOM6hF92y8C+MkEM5LMxZuk4JcQOiU4Esvs= github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= +github.com/attic-labs/kingpin v2.2.7-0.20180312050558-442efcfac769+incompatible/go.mod h1:Cp18FeDCvsK+cD2QAGkqerGjrgSXLiJWnjHeY2mneBc= github.com/aws/aws-sdk-go v1.15.27/go.mod h1:mFuSZ37Z9YOHbQEwBWztmVzqXrEkub65tZoCYDt7FT0= github.com/aws/aws-sdk-go v1.30.19/go.mod h1:5zCpMtNQVjRREroY7sYe8lOMRSxkhG6MZveU8YkpAk0= github.com/aws/aws-sdk-go v1.37.0/go.mod h1:hcU610XS61/+aQV88ixoOzUoG7v3b31pl2zKMmprdro= @@ -314,6 +432,7 @@ github.com/aws/smithy-go v1.11.2/go.mod h1:3xHYmszWVx2c0kIwQeEVf9uSm4fYZt67FBJnw github.com/aws/smithy-go v1.17.0/go.mod h1:NukqUGpCZIILqqiV0NIjeFh24kd/FAa4beRb6nbIUPE= github.com/aws/smithy-go v1.24.2 h1:FzA3bu/nt/vDvmnkg+R8Xl46gmzEDam6mZ1hzmwXFng= github.com/aws/smithy-go v1.24.2/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= +github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= github.com/aymanbagabas/go-udiff v0.4.1 h1:OEIrQ8maEeDBXQDoGCbbTTXYJMYRCRO1fnodZ12Gv5o= github.com/aymanbagabas/go-udiff v0.4.1/go.mod h1:0L9PGwj20lrtmEMeyw4WKJ/TMyDtvAoK9bf2u/mNo3w= github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk= @@ -325,7 +444,10 @@ github.com/bcicen/jstream v1.0.1/go.mod h1:9ielPxqFry7Y4Tg3j4BfjPocfJ3TbsRtXOAYX github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/bits-and-blooms/bitset v1.24.4/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8= +github.com/bmatcuk/doublestar/v4 v4.10.0/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc= github.com/bobg/gcsobj v0.1.2/go.mod h1:vS49EQ1A1Ib8FgrL58C8xXYZyOCR2TgzAdopy6/ipa8= +github.com/boltdb/bolt v1.3.1/go.mod h1:clJnj/oiGkjum5o1McbSZDSLxVThjynRyGBgiAx27Ps= github.com/boombuler/barcode v1.0.0/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8= github.com/buger/jsonparser v1.1.2 h1:frqHqw7otoVbk5M8LlE/L7HTnIq2v9RX6EJ48i9AxJk= github.com/buger/jsonparser v1.1.2/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0= @@ -343,6 +465,7 @@ github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UF github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q= github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q= +github.com/charmbracelet/harmonica v0.2.0/go.mod h1:KSri/1RMQOZLbw7AHqgcBycp8pgJnQMYYT8QZRqZ1Ao= github.com/charmbracelet/ultraviolet v0.0.0-20260205113103-524a6607adb8 h1:eyFRbAmexyt43hVfeyBofiGSEmJ7krjLOYt/9CF5NKA= github.com/charmbracelet/ultraviolet v0.0.0-20260205113103-524a6607adb8/go.mod h1:SQpCTRNBtzJkwku5ye4S3HEuthAlGy2n9VXZnWkEW98= github.com/charmbracelet/x/ansi v0.11.7 h1:kzv1kJvjg2S3r9KHo8hDdHFQLEqn4RBCb39dAYC84jI= @@ -375,6 +498,7 @@ github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMn github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSEFgwIwO+UVM8= github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0= +github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEXNWYXQgCt4hdOzA= github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk= github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= @@ -399,6 +523,7 @@ github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I= github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo= github.com/containerd/platforms v0.2.1 h1:zvwtM3rz2YHPQsF2CHYM8+KtB5dvhISiXh5ZpSBQv6A= github.com/containerd/platforms v0.2.1/go.mod h1:XHCb+2/hzowdiut9rkudds9bE5yJ7npe7dG/wG+uFPw= +github.com/containerd/typeurl/v2 v2.2.0/go.mod h1:8XOOxnyatxSWuG8OfsZXVnAF4iZfedjS/8UHSPJnX4g= github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= @@ -409,6 +534,7 @@ github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7Do github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= +github.com/creasty/defaults v1.6.0/go.mod h1:iGzKe6pbEHnpMPtfDXZEr0NVxWnPTjb1bbDy08fPzYM= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= @@ -457,6 +583,7 @@ github.com/dolthub/ishell v0.0.0-20260414231531-5f031e3e9037 h1:oIW9HwuWrhxv+4HZ github.com/dolthub/ishell v0.0.0-20260414231531-5f031e3e9037/go.mod h1:ehexgi1mPxRTk0Mok/pADALuHbvATulTh6gzr7NzZto= github.com/dolthub/jsonpath v0.0.2-0.20240227200619-19675ab05c71 h1:bMGS25NWAGTEtT5tOBsCuCrlYnLRKpbJVJkDbrTRhwQ= github.com/dolthub/jsonpath v0.0.2-0.20240227200619-19675ab05c71/go.mod h1:2/2zjLQ/JOOSbbSboojeg+cAwcRV0fDLzIiWch/lhqI= +github.com/dolthub/sqllogictest/go v0.0.0-20240618184124-ca47f9354216/go.mod h1:e/FIZVvT2IR53HBCAo41NjqgtEnjMJGKca3Y/dAmZaA= github.com/dolthub/vitess v0.0.0-20260624214226-81d034e0fde8 h1:zmKLyRCTiNZnizO++sNXP1QW2bxLE2Y+WJAdu/hcu6s= github.com/dolthub/vitess v0.0.0-20260624214226-81d034e0fde8/go.mod h1:5SVEJgAhw5nnQUFnGgKI1Svqes1Mw+zKUsalyxmOuG0= github.com/dprotaso/go-yit v0.0.0-20191028211022-135eb7262960/go.mod h1:9HQzr9D/0PGwMEbC3d5AB7oi67+h4TsQqItC1GVYG58= @@ -553,6 +680,7 @@ github.com/go-sql-driver/mysql v1.10.0 h1:Q+1LV8DkHJvSYAdR83XzuhDaTykuDx0l6fkXxo github.com/go-sql-driver/mysql v1.10.0/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= +github.com/go-test/deep v1.0.8/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE= github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs= github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee/go.mod h1:L0fX3K22YWvt/FAX9NnzrNzcI4wNYi9Yku4O0LKYflo= @@ -566,6 +694,7 @@ github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5x github.com/gofrs/flock v0.8.1 h1:+gYjHKf32LDeiEEFhQaotPbLuUXjY5ZqxKgXy7n59aw= github.com/gofrs/flock v0.8.1/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU= github.com/gofrs/uuid v4.0.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang-jwt/jwt v3.2.1+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= github.com/golang-jwt/jwt/v4 v4.0.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg= github.com/golang-jwt/jwt/v4 v4.2.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg= @@ -581,6 +710,7 @@ github.com/golang-sql/sqlexp v0.0.0-20170517235910-f1bb20e5a188/go.mod h1:vXjM/+ github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g= github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/glog v1.2.5/go.mod h1:6AhwSGph0fcJtXVM/PEHPqZlFeoLxhs7/t5UDAwmO+w= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= @@ -643,11 +773,13 @@ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/go-github/v57 v57.0.0 h1:L+Y3UPTY8ALM8x+TV0lg+IEBI+upibemtBD8Q9u7zHs= github.com/google/go-github/v57 v57.0.0/go.mod h1:s0omdnye0hvK/ecLvpsGfJMiRt85PimQh4oygmLIxHw= +github.com/google/go-pkcs11 v0.3.0/go.mod h1:6eQoGcuNJpa7jnd5pMGdkSaQpNDYvPlXWMcjXXThLlY= github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8= github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU= github.com/google/go-replayers/grpcreplay v1.1.0/go.mod h1:qzAvJ8/wi57zq7gWqaE6AwLM6miiXUQwP1S+I9icmhk= github.com/google/go-replayers/httpreplay v1.1.1/go.mod h1:gN9GeLIs7l6NUoVaSSnv2RiqK1NiwAmD0MrKeC9IIks= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/jsonschema-go v0.4.2/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= github.com/google/martian v2.1.1-0.20190517191504-25dcb96d9e51+incompatible h1:xmapqc1AyLoB+ddYT6r04bD9lIjlOqGaREovi0SzFaE= github.com/google/martian v2.1.1-0.20190517191504-25dcb96d9e51+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= @@ -716,6 +848,7 @@ github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyf github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= @@ -830,6 +963,7 @@ github.com/lucasb-eyer/go-colorful v1.4.0 h1:UtrWVfLdarDgc44HcS7pYloGHJUjHV/4FwW github.com/lucasb-eyer/go-colorful v1.4.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 h1:6E+4a0GO5zZEnZ81pIr0yLvtUWk2if982qA3F3QD6H4= github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I= +github.com/lyft/protoc-gen-star/v2 v2.0.4/go.mod h1:amey7yeodaJhXSbf/TlLvWiqQfLOSpEk//mLlc+axEk= github.com/magiconair/properties v1.8.10 h1:s31yESBquKXCV9a/ScB3ESkOjUYYv+X0rg8SYxI99mE= github.com/magiconair/properties v1.8.10/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= @@ -871,6 +1005,9 @@ github.com/moby/moby/client v0.4.0 h1:S+2XegzHQrrvTCvF6s5HFzcrywWQmuVnhOXe2kiWjI github.com/moby/moby/client v0.4.0/go.mod h1:QWPbvWchQbxBNdaLSpoKpCdf5E+WxFAgNHogCWDoa7g= github.com/moby/patternmatcher v0.6.1 h1:qlhtafmr6kgMIJjKJMDmMWq7WLkKIo23hsrpR3x084U= github.com/moby/patternmatcher v0.6.1/go.mod h1:hDPoyOpDY7OrrMDLaYoY3hf52gNCR/YOUYxkhApJIxc= +github.com/moby/sys/mount v0.3.4/go.mod h1:KcQJMbQdJHPlq5lcYT+/CjatWM4PuxKe+XLSVS4J6Os= +github.com/moby/sys/mountinfo v0.7.2/go.mod h1:1YOa8w8Ih7uW0wALDUgT1dTTSBrZ+HiBLGws92L2RU4= +github.com/moby/sys/reexec v0.1.0/go.mod h1:EqjBg8F3X7iZe5pU6nRZnYCMUTXoxsjiIfHup5wYIN8= github.com/moby/sys/sequential v0.6.0 h1:qrx7XFUd/5DxtqcoH1h438hF5TmOvzC/lspjy7zgvCU= github.com/moby/sys/sequential v0.6.0/go.mod h1:uyv8EUTrca5PnDsdMGXhZe6CCe8U/UiTWd+lL+7b/Ko= github.com/moby/sys/user v0.4.0 h1:jhcMKit7SA80hivmFJcbB1vqmw//wU61Zdui2eQXuMs= @@ -879,6 +1016,7 @@ github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/g github.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28= github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ= github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc= +github.com/modelcontextprotocol/go-sdk v1.3.1/go.mod h1:DgVX498dMD8UJlseK1S5i1T4tFz2fkBk4xogC3D15nw= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= @@ -892,6 +1030,7 @@ github.com/montanaflynn/stats v0.6.6/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt github.com/montanaflynn/stats v0.7.0/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow= github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= +github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/ncw/swift v1.0.52/go.mod h1:23YIA4yWVnGwv2dQlN4bB7egfYX6YLn0Yo/S6zZO/ZM= @@ -920,6 +1059,7 @@ github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8 github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040= github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M= +github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= github.com/oracle/oci-go-sdk/v65 v65.55.0 h1:enKyHVLdJYDJrc9232w33u5F6t2p8Din4593kn3nh/w= github.com/oracle/oci-go-sdk/v65 v65.55.0/go.mod h1:IBEV9l1qBzUpo7zgGaRUhbB05BVfcDGYRFBCPlTcPp0= github.com/pb33f/ordered-map/v2 v2.3.1 h1:5319HDO0aw4DA4gzi+zv4FXU9UlSs3xGZ40wcP1nBjY= @@ -973,13 +1113,18 @@ github.com/rs/zerolog v1.13.0/go.mod h1:YbFCdg8HfsridGWAh22vktObvhZbQsZXe4/zB0OK github.com/rs/zerolog v1.15.0/go.mod h1:xYTKnLHcpfU2225ny5qZjxnj9NvkumZYjJHlAThCjNc= github.com/rs/zerolog v1.28.0 h1:MirSo27VyNi7RJYP3078AA1+Cyzd2GB66qy3aUHvsWY= github.com/rs/zerolog v1.28.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0= +github.com/russross/blackfriday v1.6.0/go.mod h1:ti0ldHuxg49ri4ksnFxlkCfN+hvslNlmVHqNRXXJNAY= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ruudk/golang-pdf417 v0.0.0-20181029194003-1af4ab5afa58/go.mod h1:6lfFZQK844Gfx8o5WFuvpxWRwnSoipWe/p622j1v06w= github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc= github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik= +github.com/sahilm/fuzzy v0.1.1/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y= +github.com/santhosh-tekuri/jsonschema/v5 v5.3.1/go.mod h1:uToXkOrWAZ6/Oc07xWQrPOhJotwFIyu2bBVN41fcDUY= github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= github.com/sebdah/goldie/v2 v2.8.0 h1:dZb9wR8q5++oplmEiJT+U/5KyotVD+HNGCAc5gNr8rc= github.com/sebdah/goldie/v2 v2.8.0/go.mod h1:oZ9fp0+se1eapSRjfYbsV/0Hqhbuu3bJVvKI/NNtssI= +github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg= +github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0= github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw= github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4= @@ -987,6 +1132,7 @@ github.com/shirou/gopsutil/v4 v4.26.5 h1:RPcBXkpz7kOj9PqGFQOlBPZHsyaPvPVQc098y9R github.com/shirou/gopsutil/v4 v4.26.5/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ= github.com/shopspring/decimal v0.0.0-20180709203117-cd690d0c9e24/go.mod h1:M+9NzErvs504Cn4c5DxATwIqPbtswREoFCre64PpcG4= github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= +github.com/silvasur/buzhash v0.0.0-20160816060738-9bdec3dec7c6/go.mod h1:jk5gVE20+MCoyJ2TFiiMrbWPyaH4t9T5F3HwVdthB2w= github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= @@ -1062,6 +1208,7 @@ github.com/tklauser/numcpus v0.11.0 h1:nSTwhKH5e1dMNsCdVBukSZrURJRoHbSEQjdEbY+9R github.com/tklauser/numcpus v0.11.0/go.mod h1:z+LwcLq54uWZTX0u/bGobaV34u6V7KNlTZejzM6/3MQ= github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= +github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= github.com/vbauerster/mpb/v8 v8.7.2 h1:SMJtxhNho1MV3OuFgS1DAzhANN1Ejc5Ct+0iSaIkB14= github.com/vbauerster/mpb/v8 v8.7.2/go.mod h1:ZFnrjzspgDHoxYLGvxIruiNk73GNTPG4YHgVNpR10VY= github.com/vmware-labs/yaml-jsonpath v0.3.2 h1:/5QKeCBGdsInyDCyVNLbXyilb61MXGi9NP674f9Hobk= @@ -1100,6 +1247,7 @@ github.com/zeebo/blake3 v0.2.3/go.mod h1:mjJjZpnsyIVtVgTOSpJ9vmRE4wgDeyt2HU3qXvv github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0= github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA= github.com/zenazn/goji v0.9.0/go.mod h1:7S9M489iMyHBNxwZnk9/EHS098H4/F6TATF2mIxtB1Q= +go.etcd.io/bbolt v1.3.6/go.mod h1:qXsaaIqmgQH0T+OPdb99Bf+PKfBBQVAdyD6TY9G8XM4= go.opencensus.io v0.15.0/go.mod h1:UffZAU+4sDEINUGP/B7UfBBkq4fqLu9zXAX7ke6CHW0= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= @@ -1108,6 +1256,7 @@ go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= +go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= go.opentelemetry.io/contrib/detectors/gcp v1.42.0 h1:kpt2PEJuOuqYkPcktfJqWWDjTEd/FNgrxcniL7kQrXQ= @@ -1118,6 +1267,7 @@ go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 h1:F7Jx+6h go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q= go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU= go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc= +go.opentelemetry.io/otel/exporters/jaeger v1.17.0/go.mod h1:nPCqOnEH9rNLKqH/+rrUjiMzHJdV1BlpKcTwRTyKkKI= go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.44.0 h1:RuynHbfU8JUEw7DyONgkVYg2SVtsoF28y0LGIr69jgA= go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.44.0/go.mod h1:qZF+/lBs71APw8mlnEZcqZHMzqrYrsFiJOv83lX1OGo= go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.44.0 h1:hqxVTu/GtBF+vJ8d1fzW7fRxZFvgoDjWcxwwCaFDYpU= @@ -1599,6 +1749,7 @@ google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/appengine v1.6.8/go.mod h1:1jJ3jBArFh5pcgW8gCtRJnepW8FzD1V44FJffLiz/Ds= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= @@ -1689,6 +1840,7 @@ google.golang.org/genproto v0.0.0-20250505200425-f936aa4a68b2 h1:1tXaIXCracvtsRx google.golang.org/genproto v0.0.0-20250505200425-f936aa4a68b2/go.mod h1:49MsLSx0oWMOZqcpB3uL8ZOkAh1+TndpJ8ONoCBWiZk= google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa h1:Kjn0N0tCrDgiAFW+lGO4JZ3ck44CehvJQMAwj9QF0G8= google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:q4lMZS6kskjT5HvCPrnnypcDPVJqT/f4nfxmkE7gryY= +google.golang.org/genproto/googleapis/bytestream v0.0.0-20250603155806-513f23925822/go.mod h1:h6yxum/C2qRb4txaZRLDHK8RyS0H/o2oEDeKY4onY/Y= google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa h1:mZHHdPZl0dbGHCflZgAq/Q468DWVFcU2whhB2KAo8fk= google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= @@ -1723,6 +1875,7 @@ google.golang.org/grpc v1.45.0/go.mod h1:lN7owxKUQEqMfSyQikvvk5tf/6zMPsrK+ONuO11 google.golang.org/grpc v1.81.1 h1:VnnIIZ88UzOOKLukQi+ImGz8O1Wdp8nAGGnvOfEIWQQ= google.golang.org/grpc v1.81.1/go.mod h1:xGH9GfzOyMTGIOXBJmXt+BX/V0kcdQbdcuwQ/zNw42I= google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.1.0/go.mod h1:6Kw0yEErY5E/yWrBtf03jp27GLLJujG4z/JK95pnjjw= +google.golang.org/grpc/examples v0.0.0-20250407062114-b368379ef8f6/go.mod h1:6ytKWczdvnpnO+m+JiG9NjEDzR1FJfsnmJdG7B8QVZ8= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= diff --git a/internal/httpapi/doc.go b/internal/httpapi/doc.go index 162447c3f..9e01c5866 100644 --- a/internal/httpapi/doc.go +++ b/internal/httpapi/doc.go @@ -73,6 +73,19 @@ // deletion and non-fast-forward, so no check is GitHub-required and a red gate // binds by convention. // +// A THIRD rule closes the other way past the roles. Denying internal/workapi +// stops a handler building a filter; it says nothing about a handler taking +// uw.IssueUseCase() and calling the domain straight, which needs no filter and +// no builder — and which is what the proxied CLI did for years. depguard +// (httpapi-domain-boundary) therefore denies internal/storage/domain from this +// package's non-test files, deny-by-default so a file added tomorrow is covered +// the moment it exists. It has exactly two named holes, both for a VALUE the +// embedder assembled rather than a use case: server.go, whose Config.Workspace +// is the domain.ContextInfo startup snapshot it is handed, and handlers.go, +// whose contextResponse projects that snapshot through domain.PublishedContext +// — the same projection `bd context` publishes, and where the credential and +// host-path exclusions live. reads.go and claim.go carry no exception. +// // The claim OPERATION is the only mutation this surface has, and claim.go // states the two things a client must know before adopting it: the actor is // caller-asserted provenance rather than authenticated identity, and hooks do diff --git a/internal/httpapi/server_test.go b/internal/httpapi/server_test.go index 688f7f67f..487802951 100644 --- a/internal/httpapi/server_test.go +++ b/internal/httpapi/server_test.go @@ -60,6 +60,24 @@ func (u *fakeUOW) IssueUseCase() domain.IssueUseCase { // path, which never asks for one. func (u *fakeUOW) ConfigUseCase() domain.ConfigUseCase { return u.readConfig } +// LabelUseCase and DependencyUseCase answer the hydration issueops.Lifecycle +// runs over the row a claim wrote. Neither carries state: the claimed row's +// identity is what these tests assert on, and a fake that invented labels or +// edges would be a second source of truth for it. The full-item shape is pinned +// against the CLI by the parity oracle in cmd/bd, over real Dolt. +func (u *fakeUOW) LabelUseCase() domain.LabelUseCase { return emptyLabels{} } +func (u *fakeUOW) DependencyUseCase() domain.DependencyUseCase { return emptyDeps{} } + +type emptyLabels struct{ domain.LabelUseCase } + +func (emptyLabels) GetLabels(context.Context, string) ([]string, error) { return nil, nil } + +type emptyDeps struct{ domain.DependencyUseCase } + +func (emptyDeps) GetIssueDependencyRecords(context.Context, []string) (map[string][]*types.Dependency, error) { + return nil, nil +} + func (u *fakeUOW) Commit(_ context.Context, message string) error { u.mu.Lock() defer u.mu.Unlock() diff --git a/internal/jira/tracker_test.go b/internal/jira/tracker_test.go index 77d7e1ae6..65c930572 100644 --- a/internal/jira/tracker_test.go +++ b/internal/jira/tracker_test.go @@ -639,6 +639,21 @@ func (s *configStore) IssueReader() (issueops.Reader, error) { func (s *configStore) IssueClaimer() (issueops.Claimer, error) { return nil, &storage.ErrUnsupported{Op: "IssueClaimer", Backend: "jira-config-stub"} } +func (s *configStore) ReadyClaimer() (issueops.ReadyClaimer, error) { + return nil, &storage.ErrUnsupported{Op: "ReadyClaimer", Backend: "jira-config-stub"} +} +func (s *configStore) BatchCloser() (issueops.BatchCloser, error) { + return nil, &storage.ErrUnsupported{Op: "BatchCloser", Backend: "jira-config-stub"} +} +func (s *configStore) DependencyEditor() (issueops.DependencyEditor, error) { + return nil, &storage.ErrUnsupported{Op: "DependencyEditor", Backend: "jira-config-stub"} +} +func (s *configStore) Commenter() (issueops.Commenter, error) { + return nil, &storage.ErrUnsupported{Op: "Commenter", Backend: "jira-config-stub"} +} +func (s *configStore) IssueRelations() (issueops.Relations, error) { + return nil, &storage.ErrUnsupported{Op: "IssueRelations", Backend: "jira-config-stub"} +} func (s *configStore) SetConfig(_ context.Context, _, _ string) error { return nil } func (s *configStore) SetLocalMetadata(_ context.Context, _, _ string) error { return nil } func (s *configStore) GetLocalMetadata(_ context.Context, _ string) (string, error) { diff --git a/internal/storage/dolt/batch_closer.go b/internal/storage/dolt/batch_closer.go new file mode 100644 index 000000000..e27dd9c2f --- /dev/null +++ b/internal/storage/dolt/batch_closer.go @@ -0,0 +1,70 @@ +package dolt + +import ( + "context" + "database/sql" + + "github.com/steveyegge/beads/internal/storage" + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/internal/workapi" + "github.com/steveyegge/beads/issueops" +) + +// BatchCloser returns the guarded close-many surface for this store. +func (s *DoltStore) BatchCloser() (issueops.BatchCloser, error) { + return NewBatchCloser(s) +} + +// NewBatchCloser returns a guarded batch closer backed by store. +func NewBatchCloser(store *DoltStore) (issueops.BatchCloser, error) { + if store == nil { + return nil, &storage.ErrUnsupported{Op: "NewBatchCloser", Backend: "nil"} + } + return &batchCloser{store: store}, nil +} + +type batchCloser struct{ store *DoltStore } + +// CloseBatch runs every close, and the optional claim, in ONE transaction with +// one commit. The message is composed inside the body because it names what +// LANDED, which is not knowable until the last item has been tried. +func (o *batchCloser) CloseBatch(ctx context.Context, request issueops.CloseBatchRequest) (issueops.CloseBatchResult, error) { + if err := storageissueops.ValidateCloseBatchRequest(request); err != nil { + return issueops.CloseBatchResult{}, err + } + claimFilter, err := batchClaimFilter(request.ClaimNext) + if err != nil { + return issueops.CloseBatchResult{}, err + } + + var result issueops.CloseBatchResult + err = o.store.runIssueOperationTxWithMessage(ctx, func(tx *sql.Tx) (storageissueops.ChangedTables, string, error) { + attempt, tables, err := storageissueops.ExecuteCloseBatch(ctx, tx, request, claimFilter) + if err != nil { + return nil, "", err + } + result = attempt + return tables, storageissueops.CloseBatchCommitMessage(attempt), nil + }) + if err != nil { + return issueops.CloseBatchResult{}, err + } + return result, nil +} + +// batchClaimFilter translates the request's optional claim into the filter the +// storage layer speaks, through the same builder Reader.Ready and +// ReadyClaimer.ClaimNext run. Nil in, nil out: no claim was asked for. +func batchClaimFilter(request *issueops.ReadyRequest) (*types.WorkFilter, error) { + if request == nil { + return nil, nil + } + filter, err := workapi.BuildReadyFilter(*request) + if err != nil { + return nil, err + } + return &filter, nil +} + +var _ issueops.BatchCloser = (*batchCloser)(nil) diff --git a/internal/storage/dolt/batch_closer_contract_test.go b/internal/storage/dolt/batch_closer_contract_test.go new file mode 100644 index 000000000..08b04f6cd --- /dev/null +++ b/internal/storage/dolt/batch_closer_contract_test.go @@ -0,0 +1,156 @@ +package dolt + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/backend/conformance" +) + +// The server-backed store's wiring of the BatchCloser contract. Each case gets +// its own store, which on this backend is its own copy-on-write branch, so the +// history deltas the atomicity cases take cannot be moved by a sibling. + +func TestBatchCloserOutcomesMirrorItemsIndexForIndex(t *testing.T) { + fixture, ctx, cleanup := newDoltBatchCloserFixture(t, "bcmirror") + defer cleanup() + conformance.RunBatchCloserOutcomesMirrorItemsIndexForIndex(t, ctx, fixture) +} + +func TestBatchCloserPerItemRefusalIsAResultAndSurvivorsCommit(t *testing.T) { + fixture, ctx, cleanup := newDoltBatchCloserFixture(t, "bcrefusal") + defer cleanup() + conformance.RunBatchCloserPerItemRefusalIsAResultAndSurvivorsCommit(t, ctx, fixture) +} + +func TestBatchCloserOutcomeSnapshotIsTheDocumentedShape(t *testing.T) { + fixture, ctx, cleanup := newDoltBatchCloserFixture(t, "bcshape") + defer cleanup() + conformance.RunBatchCloserOutcomeSnapshotIsTheDocumentedShape(t, ctx, fixture) +} + +func TestBatchCloserRequestValidationReturnsZeroResultAndChangesNothing(t *testing.T) { + fixture, ctx, cleanup := newDoltBatchCloserFixture(t, "bcvalid") + defer cleanup() + conformance.RunBatchCloserRequestValidationReturnsZeroResultAndChangesNothing(t, ctx, fixture) +} + +func TestBatchCloserClaimFilterValueFailureIsARequestValidationFailure(t *testing.T) { + fixture, ctx, cleanup := newDoltBatchCloserFixture(t, "bcbadsort") + defer cleanup() + conformance.RunBatchCloserClaimFilterValueFailureIsARequestValidationFailure(t, ctx, fixture) +} + +func TestBatchCloserBackendFailureReturnsNoOutcomes(t *testing.T) { + fixture, ctx, cleanup := newDoltBatchCloserFixture(t, "bcdeadctx") + defer cleanup() + conformance.RunBatchCloserBackendFailureReturnsNoOutcomes(t, ctx, fixture) +} + +func TestBatchCloserIdempotentRecloseIsAPerItemSuccess(t *testing.T) { + fixture, ctx, cleanup := newDoltBatchCloserFixture(t, "bcreclose") + defer cleanup() + conformance.RunBatchCloserIdempotentRecloseIsAPerItemSuccess(t, ctx, fixture) +} + +func TestBatchCloserAllIdempotentBatchLandsNothing(t *testing.T) { + fixture, ctx, cleanup := newDoltBatchCloserFixture(t, "bcallidem") + defer cleanup() + conformance.RunBatchCloserAllIdempotentBatchLandsNothing(t, ctx, fixture) +} + +func TestBatchCloserDuplicateItemRecloseAtItsOwnIndex(t *testing.T) { + fixture, ctx, cleanup := newDoltBatchCloserFixture(t, "bcdup") + defer cleanup() + conformance.RunBatchCloserDuplicateItemRecloseAtItsOwnIndex(t, ctx, fixture) +} + +func TestBatchCloserWispItemClosesAndEarnsTheClaim(t *testing.T) { + fixture, ctx, cleanup := newDoltBatchCloserFixture(t, "bcwispclaim") + defer cleanup() + conformance.RunBatchCloserWispItemClosesAndEarnsTheClaim(t, ctx, fixture) +} + +func TestBatchCloserDurableHistoryNeverNamesAWisp(t *testing.T) { + fixture, ctx, cleanup := newDoltBatchCloserFixture(t, "bcwisphistory") + defer cleanup() + conformance.RunBatchCloserDurableHistoryNeverNamesAWisp(t, ctx, fixture) +} + +func TestBatchCloserForceBypassesOnlyClosePolicy(t *testing.T) { + fixture, ctx, cleanup := newDoltBatchCloserFixture(t, "bcforce") + defer cleanup() + conformance.RunBatchCloserForceBypassesOnlyClosePolicy(t, ctx, fixture) +} + +func TestBatchCloserClaimNextHydratesWhenSomethingClosed(t *testing.T) { + fixture, ctx, cleanup := newDoltBatchCloserFixture(t, "bcclaimhit") + defer cleanup() + conformance.RunBatchCloserClaimNextHydratesWhenSomethingClosed(t, ctx, fixture) +} + +func TestBatchCloserClaimNextIsNilWhenNothingClosed(t *testing.T) { + fixture, ctx, cleanup := newDoltBatchCloserFixture(t, "bcclaimnone") + defer cleanup() + conformance.RunBatchCloserClaimNextIsNilWhenNothingClosed(t, ctx, fixture) +} + +func TestBatchCloserClaimNextIsNilWhenTheFrontIsEmpty(t *testing.T) { + fixture, ctx, cleanup := newDoltBatchCloserFixture(t, "bcclaimempty") + defer cleanup() + conformance.RunBatchCloserClaimNextIsNilWhenTheFrontIsEmpty(t, ctx, fixture) +} + +func TestBatchCloserClaimNextSeesAnUnblockingFromItsOwnBatch(t *testing.T) { + fixture, ctx, cleanup := newDoltBatchCloserFixture(t, "bcclaimunblock") + defer cleanup() + conformance.RunBatchCloserClaimNextSeesAnUnblockingFromItsOwnBatch(t, ctx, fixture) +} + +func TestBatchCloserRecordsOneHistoryEntryForWhatLanded(t *testing.T) { + fixture, ctx, cleanup := newDoltBatchCloserFixture(t, "bchistory") + defer cleanup() + conformance.RunBatchCloserRecordsOneHistoryEntryForWhatLanded(t, ctx, fixture) +} + +func TestBatchCloserAllRefusedBatchRecordsNoHistory(t *testing.T) { + fixture, ctx, cleanup := newDoltBatchCloserFixture(t, "bcnohistory") + defer cleanup() + conformance.RunBatchCloserAllRefusedBatchRecordsNoHistory(t, ctx, fixture) +} + +func TestBatchCloserDoesNotMutateTheCallerRequest(t *testing.T) { + fixture, ctx, cleanup := newDoltBatchCloserFixture(t, "bcsnapshot") + defer cleanup() + conformance.RunBatchCloserDoesNotMutateTheCallerRequest(t, ctx, fixture) +} + +func newDoltBatchCloserFixture(t *testing.T, prefix string) (conformance.BatchCloserFixture, context.Context, func()) { + t.Helper() + store, storeCleanup := setupTestStore(t) + ctx, cancel := testContext(t) + closer, err := store.BatchCloser() + if err != nil { + cancel() + storeCleanup() + t.Fatalf("BatchCloser(): %v", err) + } + kit := newDoltRoleFixtureKit(store, prefix) + fixture := conformance.BatchCloserFixture{ + IssuePrefix: kit.IssuePrefix, + Closer: closer, + CreateIssue: kit.CreateIssue, + CreateWisp: kit.CreateWisp, + AddDependency: kit.AddDependency, + // Local, because the shared kit exposes no comment hook. Folding it in + // is an S0 follow-up (bd-kue5t); editing the frozen kit from this slice + // would collide with the five running beside it. + AddComment: store.AddComment, + QueryScalar: kit.QueryScalar, + CountHistory: kit.CountHistory, + } + return fixture, ctx, func() { + cancel() + storeCleanup() + } +} diff --git a/internal/storage/dolt/claim_verify.go b/internal/storage/dolt/claim_verify.go index c8015c533..1b456bc85 100644 --- a/internal/storage/dolt/claim_verify.go +++ b/internal/storage/dolt/claim_verify.go @@ -36,8 +36,13 @@ import ( // - any other error -> honest failure (CAS lost, not-claimable, or // pre-commit errors withRetryTx already retried); no verify needed // -// Wisps are exempt: they are ephemeral, never leased, and not reclaimable -// coordination state. +// A claim the caller NAMES by id is exempt when the id is a wisp: wisps are +// ephemeral, never leased, and not reclaimable coordination state, so the +// verify round trip buys nothing. A READY claim is different — it does not know +// what it won until the write has run, and what it won may be a wisp, because +// the ready set follows the request's filter and IncludeEphemeral admits the +// wisp plane. That one verifies whatever it claimed, in the plane it wrote +// (see readReadyClaimState). // claimPostcondition describes the row state a claim-family write must leave // behind to count as applied, plus the words to use when it didn't. @@ -128,11 +133,37 @@ func guardedUpdatePostcondition(opts storage.UpdateIssueOptions, updates map[str // transaction. withReadTx retries transient connection errors itself, so a // failure here means the server is genuinely unreachable, not a blip. func (s *DoltStore) readClaimState(ctx context.Context, id string) (string, types.Status, error) { + return s.readClaimStateIn(ctx, "issues", id) +} + +// readReadyClaimState re-reads a ready claim's winner in the plane the claim +// actually wrote. A ready claim can win an ephemeral row — the ready set is +// whatever the request's filter admits, and IncludeEphemeral admits the wisp +// plane — and issueops.ClaimIssueInTx routes the compare-and-set by plane +// (IsActiveWispInTx then WispTableRouting), so the compare-and-set lands on +// wisps. Verifying that against `issues` finds no row and reports a write that +// demonstrably succeeded as unverifiable (bd-yby99.4). +// +// A failed plane probe degrades to the issues plane, which is where a durable +// claim — the overwhelmingly common case — belongs anyway. +func (s *DoltStore) readReadyClaimState(ctx context.Context, id string) (string, types.Status, error) { + if s.isActiveWisp(ctx, id) { + return s.readClaimStateIn(ctx, "wisps", id) + } + return s.readClaimStateIn(ctx, "issues", id) +} + +// readClaimStateIn is readClaimState against a named plane. Both planes carry +// the same two coordination columns, so the postcondition is the same either +// way; only the table differs. +// +//nolint:gosec // G201: table is one of the two plane names this file passes. +func (s *DoltStore) readClaimStateIn(ctx context.Context, table, id string) (string, types.Status, error) { var assignee sql.NullString var status types.Status err := s.withReadTx(ctx, func(tx *sql.Tx) error { return tx.QueryRowContext(ctx, - `SELECT assignee, status FROM issues WHERE id = ?`, id, + `SELECT assignee, status FROM `+table+` WHERE id = ?`, id, ).Scan(&assignee, &status) }) if err != nil { diff --git a/internal/storage/dolt/commenter.go b/internal/storage/dolt/commenter.go new file mode 100644 index 000000000..fef5845d1 --- /dev/null +++ b/internal/storage/dolt/commenter.go @@ -0,0 +1,49 @@ +package dolt + +import ( + "context" + "database/sql" + + "github.com/steveyegge/beads/internal/storage" + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/issueops" +) + +// Commenter returns the guarded add-comment surface for this store. +func (s *DoltStore) Commenter() (issueops.Commenter, error) { + return NewCommenter(s) +} + +// NewCommenter returns a guarded commenter backed by store. +func NewCommenter(store *DoltStore) (issueops.Commenter, error) { + if store == nil { + return nil, &storage.ErrUnsupported{Op: "NewCommenter", Backend: "nil"} + } + return &commenter{store: store}, nil +} + +type commenter struct{ store *DoltStore } + +// AddComment resolves the plane and appends the row in ONE transaction, so a +// comment cannot land on an issue that was promoted or demoted between the +// resolve and the insert. +func (c *commenter) AddComment(ctx context.Context, request issueops.AddCommentRequest) (issueops.AddCommentResult, error) { + if err := storageissueops.ValidateAddCommentRequest(request); err != nil { + return issueops.AddCommentResult{}, err + } + message := storageissueops.AddCommentCommitMessage(request.IssueID) + + var result issueops.AddCommentResult + err := c.store.runIssueOperationTx(ctx, message, func(tx *sql.Tx) (storageissueops.ChangedTables, error) { + var err error + var tables storageissueops.ChangedTables + result, tables, err = storageissueops.ExecuteAddComment(ctx, tx, request) + return tables, err + }) + if err != nil { + return issueops.AddCommentResult{}, err + } + return result, nil +} + +var _ issueops.Commenter = (*commenter)(nil) diff --git a/internal/storage/dolt/commenter_contract_test.go b/internal/storage/dolt/commenter_contract_test.go new file mode 100644 index 000000000..36fb8d643 --- /dev/null +++ b/internal/storage/dolt/commenter_contract_test.go @@ -0,0 +1,80 @@ +package dolt + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/backend/conformance" +) + +// TestCommenterContract runs the Commenter contract against the server-backed +// store. +// +// The cases are subtests of one parent so the whole role suite shares one +// store and one copy-on-write branch: each Run namespaces its ids under the +// fixture prefix, and the history cases take before/after deltas, which is +// only meaningful while the subtests run sequentially. setupTestStore already +// marks the PARENT parallel; no subtest here calls t.Parallel. +func TestCommenterContract(t *testing.T) { + fixture, ctx, cleanup := newDoltCommenterFixture(t, "cmt") + defer cleanup() + + t.Run("StoresTextVerbatim", func(t *testing.T) { + conformance.RunCommenterStoresTextVerbatim(t, ctx, fixture) + }) + t.Run("ResultMirrorsTheStoredRow", func(t *testing.T) { + conformance.RunCommenterResultMirrorsTheStoredRow(t, ctx, fixture) + }) + t.Run("CommentOnAWispLandsOnTheWispThread", func(t *testing.T) { + conformance.RunCommenterCommentOnAWispLandsOnTheWispThread(t, ctx, fixture) + }) + t.Run("RefusesAnIDOnNeitherPlane", func(t *testing.T) { + conformance.RunCommenterRefusesAnIDOnNeitherPlane(t, ctx, fixture) + }) + t.Run("RefusesAnEmptyIssueID", func(t *testing.T) { + conformance.RunCommenterRefusesAnEmptyIssueID(t, ctx, fixture) + }) + t.Run("DoesNotResolvePrefixes", func(t *testing.T) { + conformance.RunCommenterDoesNotResolvePrefixes(t, ctx, fixture) + }) + t.Run("RecordsAtMostOneHistoryEntry", func(t *testing.T) { + conformance.RunCommenterRecordsAtMostOneHistoryEntry(t, ctx, fixture) + }) + t.Run("LeavesTheAnchorIssueUntouched", func(t *testing.T) { + conformance.RunCommenterLeavesTheAnchorIssueUntouched(t, ctx, fixture) + }) + t.Run("RefusesBlankText", func(t *testing.T) { + conformance.RunCommenterRefusesBlankText(t, ctx, fixture) + }) + t.Run("RefusesAnEmptyAuthor", func(t *testing.T) { + conformance.RunCommenterRefusesAnEmptyAuthor(t, ctx, fixture) + }) + t.Run("LeavesTheCallersRequestAlone", func(t *testing.T) { + conformance.RunCommenterLeavesTheCallersRequestAlone(t, ctx, fixture) + }) +} + +func newDoltCommenterFixture(t *testing.T, prefix string) (conformance.CommenterFixture, context.Context, func()) { + t.Helper() + store, storeCleanup := setupTestStore(t) + ctx, cancel := testContext(t) + commenter, err := store.Commenter() + if err != nil { + cancel() + storeCleanup() + t.Fatalf("Commenter(): %v", err) + } + kit := newDoltRoleFixtureKit(store, prefix) + fixture := conformance.CommenterFixture{ + IssuePrefix: kit.IssuePrefix, + Commenter: commenter, + CreateIssue: kit.CreateIssue, + CreateWisp: kit.CreateWisp, + QueryScalar: kit.QueryScalar, + CountHistory: kit.CountHistory, + } + return fixture, ctx, func() { + cancel() + storeCleanup() + } +} diff --git a/internal/storage/dolt/commenter_persistence_test.go b/internal/storage/dolt/commenter_persistence_test.go new file mode 100644 index 000000000..155dd1602 --- /dev/null +++ b/internal/storage/dolt/commenter_persistence_test.go @@ -0,0 +1,104 @@ +package dolt + +import ( + "testing" + + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// This file is the persistence tier of the Commenter role: what the shared +// contract in package conformance deliberately leaves out because it is a +// property of the Dolt working set rather than a promised result of the +// operation. It is pinned at this backend only. +// +// - The commit-message spelling is single-sourced in +// storageissueops.AddCommentCommitMessage, so one backend pinning it is +// enough and re-pinning it three times would be duplication. +// - The staging assertions need a planted dirty working set and a dolt_status +// read. The working set is not a caller-visible thing on the unit-of-work +// route, which is where the same line was already drawn for Lifecycle in +// conformance/issue_operations_staging.go. +// +// Everything else the old commenter_test.go asserted — verbatim text, the +// result mirroring the row, wisp-thread routing, ErrNotFound — is now +// conformance.RunCommenter*, wired at all three backends. + +// TestDoltStoreCommenterNamesTheIssueInHistoryAndCommitsTheTable pins the two +// persistence halves of a durable comment: the history entry is named +// "bd: comment ", and the comments table is committed rather than left +// dirty in the working set. +func TestDoltStoreCommenterNamesTheIssueInHistoryAndCommitsTheTable(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + seedIssues(ctx, t, store, "test-comment-role") + + commenter, err := store.Commenter() + if err != nil { + t.Fatalf("Commenter(): %v", err) + } + if _, err := commenter.AddComment(ctx, publicops.AddCommentRequest{ + Author: "author", + IssueID: "test-comment-role", + Text: "a durable comment", + }); err != nil { + t.Fatalf("AddComment: %v", err) + } + + if !doltHasCommitMessage(ctx, t, store, "bd: comment test-comment-role") { + t.Error("the comment did not name its issue in history") + } + requireCleanTables(ctx, t, store, "comments") +} + +// TestDoltStoreCommenterOnAWispSweepsNoPendingRow pins the staging half of the +// ephemeral case, which no data read can see. +// +// It needs a pending row in the durable comments table to be visible at all. +// The wisp tables are dolt-ignored, so a commit that named one is swallowed +// and a commit count alone cannot tell a correctly-staged wisp write from one +// that reached for `comments` — which is exactly what a wrongly resolved plane +// would do while the thread read still passed. A comment on a wisp must +// therefore leave `comments` dirty: it neither wrote to it nor swept someone +// else's pending row into a commit. +func TestDoltStoreCommenterOnAWispSweepsNoPendingRow(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + seedIssues(ctx, t, store, "test-comment-neighbor") + wisp := &types.Issue{ID: "test-comment-wisp", Title: "wisp", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: true} + if err := store.CreateIssue(ctx, wisp, "seed"); err != nil { + t.Fatalf("create wisp: %v", err) + } + if _, err := store.db.ExecContext(ctx, ` + INSERT INTO comments (id, issue_id, author, text, created_at) + VALUES (?, ?, ?, ?, NOW())`, + "00000000-0000-4000-8000-00000000c0de", "test-comment-neighbor", "someone-else", "pending", + ); err != nil { + t.Fatalf("stage a pending comment row: %v", err) + } + + commenter, err := store.Commenter() + if err != nil { + t.Fatalf("Commenter(): %v", err) + } + if _, err := commenter.AddComment(ctx, publicops.AddCommentRequest{ + Author: "author", + IssueID: wisp.ID, + Text: "on the ephemeral plane", + }); err != nil { + t.Fatalf("AddComment on a wisp: %v", err) + } + + var dirty int + if err := store.db.QueryRowContext(ctx, + "SELECT COUNT(*) FROM dolt_status WHERE table_name = 'comments'").Scan(&dirty); err != nil { + t.Fatalf("query dolt_status: %v", err) + } + if dirty == 0 { + t.Fatal("comments is clean: the wisp comment staged the durable table and carried a pending row with it") + } +} diff --git a/internal/storage/dolt/dependency_editor.go b/internal/storage/dolt/dependency_editor.go new file mode 100644 index 000000000..653d7c1c0 --- /dev/null +++ b/internal/storage/dolt/dependency_editor.go @@ -0,0 +1,71 @@ +package dolt + +import ( + "context" + "database/sql" + + "github.com/steveyegge/beads/internal/storage" + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/issueops" +) + +// DependencyEditor returns the guarded dependency-edge surface for this store. +func (s *DoltStore) DependencyEditor() (issueops.DependencyEditor, error) { + return NewDependencyEditor(s) +} + +// NewDependencyEditor returns a guarded dependency editor backed by store. +func NewDependencyEditor(store *DoltStore) (issueops.DependencyEditor, error) { + if store == nil { + return nil, &storage.ErrUnsupported{Op: "NewDependencyEditor", Backend: "nil"} + } + return &dependencyEditor{store: store}, nil +} + +type dependencyEditor struct{ store *DoltStore } + +// AddDependencies asserts every edge in ONE transaction with one commit. The +// first refusal rolls the whole thing back, which is what makes the request +// all-or-nothing without any bookkeeping of its own. +func (e *dependencyEditor) AddDependencies(ctx context.Context, request issueops.AddDependenciesRequest) (issueops.AddDependenciesResult, error) { + if err := storageissueops.ValidateAddDependenciesRequest(request); err != nil { + return issueops.AddDependenciesResult{}, err + } + message := storageissueops.AddDependenciesCommitMessage(request) + + var result issueops.AddDependenciesResult + err := e.store.runIssueOperationTx(ctx, message, func(tx *sql.Tx) (storageissueops.ChangedTables, error) { + var err error + var tables storageissueops.ChangedTables + result, tables, err = storageissueops.ExecuteAddDependencies(ctx, tx, request) + return tables, err + }) + if err != nil { + return issueops.AddDependenciesResult{}, err + } + return result, nil +} + +// RemoveDependency removes one edge. The message is composed up front because +// a removal names the edge it was asked for; whether an entry is recorded at +// all is decided by the changed-table set, which is empty when no edge existed. +func (e *dependencyEditor) RemoveDependency(ctx context.Context, request issueops.RemoveDependencyRequest) (issueops.RemoveDependencyResult, error) { + if err := storageissueops.ValidateRemoveDependencyRequest(request); err != nil { + return issueops.RemoveDependencyResult{}, err + } + message := storageissueops.RemoveDependencyCommitMessage(request.IssueID, request.DependsOnID) + + var result issueops.RemoveDependencyResult + err := e.store.runIssueOperationTx(ctx, message, func(tx *sql.Tx) (storageissueops.ChangedTables, error) { + var err error + var tables storageissueops.ChangedTables + result, tables, err = storageissueops.ExecuteRemoveDependency(ctx, tx, request) + return tables, err + }) + if err != nil { + return issueops.RemoveDependencyResult{}, err + } + return result, nil +} + +var _ issueops.DependencyEditor = (*dependencyEditor)(nil) diff --git a/internal/storage/dolt/dependency_editor_contract_test.go b/internal/storage/dolt/dependency_editor_contract_test.go new file mode 100644 index 000000000..2df594f2a --- /dev/null +++ b/internal/storage/dolt/dependency_editor_contract_test.go @@ -0,0 +1,198 @@ +package dolt + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/backend/conformance" +) + +func TestDependencyEditorRoutesWispSourcedEdgeToTheWispPlane(t *testing.T) { + fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "wroute") + defer cleanup() + conformance.RunDependencyEditorRoutesWispSourcedEdgeToTheWispPlane(t, ctx, fixture) +} + +func TestDependencyEditorMixedBatchWritesBothPlanes(t *testing.T) { + fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "wmixed") + defer cleanup() + conformance.RunDependencyEditorMixedBatchWritesBothPlanes(t, ctx, fixture) +} + +func TestDependencyEditorMixedBatchRefusalRollsBackBothPlanes(t *testing.T) { + fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "wrollback") + defer cleanup() + conformance.RunDependencyEditorMixedBatchRefusalRollsBackBothPlanes(t, ctx, fixture) +} + +func TestDependencyEditorRefusesCrossPlaneCycle(t *testing.T) { + fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "wcycle") + defer cleanup() + conformance.RunDependencyEditorRefusesCrossPlaneCycle(t, ctx, fixture) +} + +func TestDependencyEditorAddedEchoesTheRequestOrder(t *testing.T) { + fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "echo") + defer cleanup() + conformance.RunDependencyEditorAddedEchoesTheRequestOrder(t, ctx, fixture) +} + +func TestDependencyEditorSameTypeReAddIsIdempotent(t *testing.T) { + fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "idem") + defer cleanup() + conformance.RunDependencyEditorSameTypeReAddIsIdempotent(t, ctx, fixture) +} + +func TestDependencyEditorRepeatsWithinOneRequestCollapse(t *testing.T) { + fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "repeat") + defer cleanup() + conformance.RunDependencyEditorRepeatsWithinOneRequestCollapse(t, ctx, fixture) +} + +func TestDependencyEditorAttributesItsEventsToTheActor(t *testing.T) { + fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "depactor") + defer cleanup() + conformance.RunDependencyEditorAttributesItsEventsToTheActor(t, ctx, fixture) +} + +func TestDependencyEditorRetypeRefusalLeavesTheOriginalEdge(t *testing.T) { + fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "retype") + defer cleanup() + conformance.RunDependencyEditorRetypeRefusalLeavesTheOriginalEdge(t, ctx, fixture) +} + +func TestDependencyEditorRefusalWritesNothing(t *testing.T) { + fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "refuse") + defer cleanup() + conformance.RunDependencyEditorRefusalWritesNothing(t, ctx, fixture) +} + +func TestDependencyEditorRemoveIsIdempotent(t *testing.T) { + fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "rm") + defer cleanup() + conformance.RunDependencyEditorRemoveIsIdempotent(t, ctx, fixture) +} + +func TestDependencyEditorAppliesParentChildBeforeBlockingEdges(t *testing.T) { + fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "pcfirst") + defer cleanup() + conformance.RunDependencyEditorAppliesParentChildBeforeBlockingEdges(t, ctx, fixture) +} + +func TestDependencyEditorAcceptsAnExternalTarget(t *testing.T) { + fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "ext") + defer cleanup() + conformance.RunDependencyEditorAcceptsAnExternalTarget(t, ctx, fixture) +} + +func TestDependencyEditorAcceptsAForeignRepoTarget(t *testing.T) { + fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "foreign") + defer cleanup() + conformance.RunDependencyEditorAcceptsAForeignRepoTarget(t, ctx, fixture) +} + +func TestDependencyEditorRefusesBlockingEdgeAcrossItsOwnHierarchy(t *testing.T) { + fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "hier") + defer cleanup() + conformance.RunDependencyEditorRefusesBlockingEdgeAcrossItsOwnHierarchy(t, ctx, fixture) +} + +func TestDependencyEditorRefusesSelfDependencyWithTheProbeSkipped(t *testing.T) { + fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "self") + defer cleanup() + conformance.RunDependencyEditorRefusesSelfDependencyWithTheProbeSkipped(t, ctx, fixture) +} + +func TestDependencyEditorRecordsOneHistoryEntryPerLandedRequest(t *testing.T) { + fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "hist") + defer cleanup() + conformance.RunDependencyEditorRecordsOneHistoryEntryPerLandedRequest(t, ctx, fixture) +} + +func TestDependencyEditorRecordsNoHistoryForAnAllEphemeralRequest(t *testing.T) { + fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "ephhist") + defer cleanup() + conformance.RunDependencyEditorRecordsNoHistoryForAnAllEphemeralRequest(t, ctx, fixture) +} + +func TestDependencyEditorSnapshotsTheRequest(t *testing.T) { + fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "snap") + defer cleanup() + conformance.RunDependencyEditorSnapshotsTheRequest(t, ctx, fixture) +} + +func TestDependencyEditorValidationRefusalsWriteNothing(t *testing.T) { + fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "valid") + defer cleanup() + conformance.RunDependencyEditorValidationRefusalsWriteNothing(t, ctx, fixture) +} + +func TestDependencyEditorRoutesWispSourcedRemovalToTheWispPlane(t *testing.T) { + fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "wrm") + defer cleanup() + conformance.RunDependencyEditorRoutesWispSourcedRemovalToTheWispPlane(t, ctx, fixture) +} + +func TestDependencyEditorRefusesAGhostSource(t *testing.T) { + fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "ghostsrc") + defer cleanup() + conformance.RunDependencyEditorRefusesAGhostSource(t, ctx, fixture) +} + +func TestDependencyEditorRefusesAMissingLocalTarget(t *testing.T) { + fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "notgt") + defer cleanup() + conformance.RunDependencyEditorRefusesAMissingLocalTarget(t, ctx, fixture) +} + +func TestDependencyEditorAcceptsATypeOutsideTheConstants(t *testing.T) { + fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "opentype") + defer cleanup() + conformance.RunDependencyEditorAcceptsATypeOutsideTheConstants(t, ctx, fixture) +} + +func TestDependencyEditorRemovesOnlyTheNamedEdge(t *testing.T) { + fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "rmnamed") + defer cleanup() + conformance.RunDependencyEditorRemovesOnlyTheNamedEdge(t, ctx, fixture) +} + +func TestDependencyEditorSkipPerEdgeCycleCheckDropsOnlyTheProbe(t *testing.T) { + fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "skipok") + defer cleanup() + conformance.RunDependencyEditorSkipPerEdgeCycleCheckDropsOnlyTheProbe(t, ctx, fixture) +} + +func TestDependencyEditorRecordsOneHistoryEntryForAMixedPlaneRequest(t *testing.T) { + fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "mixhist") + defer cleanup() + conformance.RunDependencyEditorRecordsOneHistoryEntryForAMixedPlaneRequest(t, ctx, fixture) +} + +// newDoltDependencyEditorFixture composes the backend's role fixture kit with +// the accessor under test. Every hook but the accessor comes from the kit, so +// the seeding and scalar-query plumbing stays identical to the other roles'. +func newDoltDependencyEditorFixture(t *testing.T, prefix string) (conformance.DependencyEditorFixture, context.Context, func()) { + t.Helper() + store, storeCleanup := setupTestStore(t) + ctx, cancel := testContext(t) + editor, err := store.DependencyEditor() + if err != nil { + cancel() + storeCleanup() + t.Fatalf("DependencyEditor(): %v", err) + } + kit := newDoltRoleFixtureKit(store, prefix) + fixture := conformance.DependencyEditorFixture{ + IssuePrefix: kit.IssuePrefix, + Editor: editor, + CreateIssue: kit.CreateIssue, + CreateWisp: kit.CreateWisp, + QueryScalar: kit.QueryScalar, + CountHistory: kit.CountHistory, + } + return fixture, ctx, func() { + cancel() + storeCleanup() + } +} diff --git a/internal/storage/dolt/dependency_editor_test.go b/internal/storage/dolt/dependency_editor_test.go new file mode 100644 index 000000000..d17c93e9b --- /dev/null +++ b/internal/storage/dolt/dependency_editor_test.go @@ -0,0 +1,159 @@ +package dolt + +import ( + "testing" + + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// What is left here is the DependencyEditor's PERSISTENCE tier: how a history +// entry lands and what it says. The role's semantics — result shape, +// idempotency verdicts, the typed refusals, all-or-nothing, and the number of +// history entries a call records — moved to +// conformance.RunDependencyEditor*, which runs on all three backends. +// +// These stay dolt-only on purpose. The commit-message spellings are +// single-sourced in internal/storage/issueops, so one backend pinning a +// spelling is enough and re-pinning it three times is duplication; the staging +// assertions read dolt_status and plant a dirty working set, and the working +// set is not a caller-visible concept on the unit-of-work route. + +// TestDoltStoreDependencyEditorBatchNamesItsHistoryEntry pins the count +// spelling and the staging half: N edges commit as one entry that names the +// count, and the table it staged is clean afterwards. +func TestDoltStoreDependencyEditorBatchNamesItsHistoryEntry(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + seedIssues(ctx, t, store, "test-dep-add-a", "test-dep-add-b", "test-dep-add-c") + + editor, err := store.DependencyEditor() + if err != nil { + t.Fatalf("DependencyEditor(): %v", err) + } + if _, err := editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{ + {IssueID: "test-dep-add-a", DependsOnID: "test-dep-add-b", Type: publicops.DepBlocks}, + {IssueID: "test-dep-add-a", DependsOnID: "test-dep-add-c", Type: publicops.DepRelated}, + }, + }); err != nil { + t.Fatalf("AddDependencies: %v", err) + } + + if !doltHasCommitMessage(ctx, t, store, "dependency: add 2 edges") { + t.Fatal("no commit named the edge count") + } + requireCleanTables(ctx, t, store, "dependencies") +} + +// TestDoltStoreDependencyEditorSingleEdgeNamesTheHistoryEntry pins the other +// spelling: one edge names both endpoints, however the caller spelled the +// request. +func TestDoltStoreDependencyEditorSingleEdgeNamesTheHistoryEntry(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + seedIssues(ctx, t, store, "test-dep-msg-a", "test-dep-msg-b") + + editor, err := store.DependencyEditor() + if err != nil { + t.Fatalf("DependencyEditor(): %v", err) + } + if _, err := editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{{IssueID: "test-dep-msg-a", DependsOnID: "test-dep-msg-b", Type: publicops.DepBlocks}}, + }); err != nil { + t.Fatalf("AddDependencies single: %v", err) + } + if !doltHasCommitMessage(ctx, t, store, "bd: dep add test-dep-msg-a test-dep-msg-b") { + t.Fatal("a single edge did not name both endpoints in history") + } +} + +// TestDoltStoreDependencyEditorRemoveNamesTheHistoryEntry pins the removal's +// spelling and its staging. +func TestDoltStoreDependencyEditorRemoveNamesTheHistoryEntry(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + seedIssues(ctx, t, store, "test-dep-rm-a", "test-dep-rm-b") + + editor, err := store.DependencyEditor() + if err != nil { + t.Fatalf("DependencyEditor(): %v", err) + } + if _, err := editor.AddDependencies(ctx, publicops.AddDependenciesRequest{ + Actor: "writer", + Edges: []publicops.DependencyEdge{{IssueID: "test-dep-rm-a", DependsOnID: "test-dep-rm-b", Type: publicops.DepBlocks}}, + }); err != nil { + t.Fatalf("AddDependencies: %v", err) + } + if _, err := editor.RemoveDependency(ctx, publicops.RemoveDependencyRequest{ + Actor: "writer", IssueID: "test-dep-rm-a", DependsOnID: "test-dep-rm-b", + }); err != nil { + t.Fatalf("RemoveDependency: %v", err) + } + + if !doltHasCommitMessage(ctx, t, store, "bd: dep remove test-dep-rm-a test-dep-rm-b") { + t.Fatal("the removal did not name the edge in history") + } + requireCleanTables(ctx, t, store, "dependencies") +} + +// TestDoltStoreDependencyEditorNoOpRemoveLeavesPendingRowsUncommitted is the +// GH#2455 pin for this role: an operation that wrote nothing must stage +// nothing, because DOLT_ADD stages a whole TABLE and a commit made for a no-op +// carries away whatever else was pending in it. +// +// The commit COUNT cannot see this on its own — Dolt swallows a commit with an +// empty diff, so a leaky no-op only shows up when there is something in the +// table for it to sweep. That is why this case survives the conformance +// contract's own "a removal that found nothing records no history" assertion: +// they fail on different bugs. +func TestDoltStoreDependencyEditorNoOpRemoveLeavesPendingRowsUncommitted(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + seedIssues(ctx, t, store, "test-dep-sweep-a", "test-dep-sweep-b", "test-dep-sweep-c") + + editor, err := store.DependencyEditor() + if err != nil { + t.Fatalf("DependencyEditor(): %v", err) + } + // A pending edge in the working set that belongs to nobody's transaction. + if _, err := store.db.ExecContext(ctx, ` + INSERT INTO dependencies (id, issue_id, depends_on_issue_id, type, created_at, created_by) + VALUES (?, ?, ?, ?, NOW(), ?)`, + "00000000-0000-4000-8000-00000000d09e", "test-dep-sweep-b", "test-dep-sweep-c", types.DepBlocks, "someone-else", + ); err != nil { + t.Fatalf("stage a pending dependency row: %v", err) + } + + before := doltCommitCount(ctx, t, store) + removed, err := editor.RemoveDependency(ctx, publicops.RemoveDependencyRequest{ + Actor: "writer", IssueID: "test-dep-sweep-a", DependsOnID: "test-dep-sweep-b", + }) + if err != nil { + t.Fatalf("RemoveDependency on a missing edge: %v", err) + } + if removed.Removed { + t.Fatal("Removed = true, want false") + } + if after := doltCommitCount(ctx, t, store); after != before { + t.Fatalf("commit count = %d, want %d: the no-op swept the pending row into a commit", after, before) + } + var dirty int + if err := store.db.QueryRowContext(ctx, + "SELECT COUNT(*) FROM dolt_status WHERE table_name = 'dependencies'").Scan(&dirty); err != nil { + t.Fatalf("query dolt_status: %v", err) + } + if dirty == 0 { + t.Fatal("dependencies is clean: the no-op removal committed a row it never wrote") + } +} diff --git a/internal/storage/dolt/dolt_test.go b/internal/storage/dolt/dolt_test.go index 910e5822e..4b663f62b 100644 --- a/internal/storage/dolt/dolt_test.go +++ b/internal/storage/dolt/dolt_test.go @@ -86,6 +86,48 @@ func uniqueTestDBName(t *testing.T) string { return "testdb_" + hex.EncodeToString(buf) } +// doltCommitCount reports how many commits the test branch has. Tests that +// care whether an operation recorded history take it before and after rather +// than reading the top of dolt_log, because two commits made inside one second +// tie on date and the ordering between them is not something to rely on. +func doltCommitCount(ctx context.Context, t *testing.T, store *DoltStore) int { + t.Helper() + var n int + if err := store.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM dolt_log").Scan(&n); err != nil { + t.Fatalf("count dolt_log: %v", err) + } + return n +} + +// doltHasCommitMessage reports whether the test branch has a commit with +// exactly this message. +func doltHasCommitMessage(ctx context.Context, t *testing.T, store *DoltStore, message string) bool { + t.Helper() + var n int + if err := store.db.QueryRowContext(ctx, + "SELECT COUNT(*) FROM dolt_log WHERE message = ?", message).Scan(&n); err != nil { + t.Fatalf("query dolt_log for %q: %v", message, err) + } + return n > 0 +} + +// requireCleanTables fails when any named table is still dirty in the working +// set. It is how a test says "the operation staged and committed what it +// wrote", which is the half of the staging contract a data read cannot see. +func requireCleanTables(ctx context.Context, t *testing.T, store *DoltStore, tables ...string) { + t.Helper() + for _, table := range tables { + var dirty int + if err := store.db.QueryRowContext(ctx, + "SELECT COUNT(*) FROM dolt_status WHERE table_name = ?", table).Scan(&dirty); err != nil { + t.Fatalf("query dolt_status for %s: %v", table, err) + } + if dirty != 0 { + t.Fatalf("%s is still dirty in the working set after the operation committed", table) + } + } +} + // setupTestStore creates a test store on the shared database with branch isolation. // Each test gets its own branch (COW snapshot), preventing cross-test data leakage // without the overhead of CREATE/DROP DATABASE per test. diff --git a/internal/storage/dolt/issue_operations.go b/internal/storage/dolt/issue_operations.go index 7a1be4c3d..73dad2cee 100644 --- a/internal/storage/dolt/issue_operations.go +++ b/internal/storage/dolt/issue_operations.go @@ -52,7 +52,7 @@ func (o *issueOperations) Update(ctx context.Context, request issueops.UpdateReq // The message names the issue because that is the one `bd dolt log` // affordance callers actually grep, and it is what the CLI's own // per-command commit wrote before updates moved onto this path. - return o.store.runIssueOperationTx(ctx, updateCommitMessage(snapshot.IssueID), func(tx *sql.Tx) (storageissueops.ChangedTables, error) { + return o.store.runIssueOperationTx(ctx, storageissueops.HistoryEntry(snapshot.Provenance, updateCommitMessage(snapshot.IssueID)), func(tx *sql.Tx) (storageissueops.ChangedTables, error) { var err error var tables storageissueops.ChangedTables result, tables, err = storageissueops.ExecuteUpdate(ctx, tx, snapshot) @@ -131,7 +131,7 @@ func (o *issueOperations) Close(ctx context.Context, request issueops.CloseReque func (o *issueOperations) Reopen(ctx context.Context, request issueops.ReopenRequest) (issueops.ReopenResult, error) { snapshot := storageissueops.CloneReopenRequest(request) var result issueops.ReopenResult - err := o.store.runIssueOperationTx(ctx, "bd: reopen issue", func(tx *sql.Tx) (storageissueops.ChangedTables, error) { + err := o.store.runIssueOperationTx(ctx, storageissueops.HistoryEntry(snapshot.Provenance, "bd: reopen issue"), func(tx *sql.Tx) (storageissueops.ChangedTables, error) { var err error var tables storageissueops.ChangedTables result, tables, err = storageissueops.ExecuteReopen(ctx, tx, snapshot) diff --git a/internal/storage/dolt/issue_operations_contract_test.go b/internal/storage/dolt/issue_operations_contract_test.go index 66bfa2184..cdf37b137 100644 --- a/internal/storage/dolt/issue_operations_contract_test.go +++ b/internal/storage/dolt/issue_operations_contract_test.go @@ -43,6 +43,72 @@ func TestIssueOperationsUpdateClosedFieldsMatchClose(t *testing.T) { conformance.RunIssueOperationsUpdateClosedFieldsMatchClose(t, ctx, fixture) } +func TestIssueOperationsUpdateClaimConflictCarriesTheLosingState(t *testing.T) { + fixture, ctx, cleanup := newDoltIssueOperationsFixture(t) + defer cleanup() + conformance.RunIssueOperationsUpdateClaimConflictCarriesTheLosingState(t, ctx, fixture) +} + +func TestIssueOperationsUpdateClaimHonorsConfiguredActiveStatuses(t *testing.T) { + fixture, ctx, cleanup := newDoltIssueOperationsFixture(t) + defer cleanup() + conformance.RunIssueOperationsUpdateClaimHonorsConfiguredActiveStatuses(t, ctx, fixture) +} + +func TestIssueOperationsUpdateIssuePlaneOnlyRefusesWisps(t *testing.T) { + fixture, ctx, cleanup := newDoltIssueOperationsFixture(t) + defer cleanup() + conformance.RunIssueOperationsUpdateIssuePlaneOnlyRefusesWisps(t, ctx, fixture) +} + +func TestIssueOperationsUpdateLabelPatchOrdering(t *testing.T) { + fixture, ctx, cleanup := newDoltIssueOperationsFixture(t) + defer cleanup() + conformance.RunIssueOperationsUpdateLabelPatchOrdering(t, ctx, fixture) +} + +func TestIssueOperationsUpdateLabelPatchValueRules(t *testing.T) { + fixture, ctx, cleanup := newDoltIssueOperationsFixture(t) + defer cleanup() + conformance.RunIssueOperationsUpdateLabelPatchValueRules(t, ctx, fixture) +} + +func TestIssueOperationsUpdateParentIDReplacesTheParentEdge(t *testing.T) { + fixture, ctx, cleanup := newDoltIssueOperationsFixture(t) + defer cleanup() + conformance.RunIssueOperationsUpdateParentIDReplacesTheParentEdge(t, ctx, fixture) +} + +func TestIssueOperationsUpdateParentIDReplacesEveryParent(t *testing.T) { + fixture, ctx, cleanup := newDoltIssueOperationsFixture(t) + defer cleanup() + conformance.RunIssueOperationsUpdateParentIDReplacesEveryParent(t, ctx, fixture) +} + +func TestIssueOperationsUpdateMetadataReplaceClearsAndValidates(t *testing.T) { + fixture, ctx, cleanup := newDoltIssueOperationsFixture(t) + defer cleanup() + conformance.RunIssueOperationsUpdateMetadataReplaceClearsAndValidates(t, ctx, fixture) +} + +func TestIssueOperationsRequestValuesAreNotMutated(t *testing.T) { + fixture, ctx, cleanup := newDoltIssueOperationsFixture(t) + defer cleanup() + conformance.RunIssueOperationsRequestValuesAreNotMutated(t, ctx, fixture) +} + +func TestIssueOperationsUpdateProvenanceLabelsHistory(t *testing.T) { + fixture, ctx, cleanup := newDoltIssueOperationsFixture(t) + defer cleanup() + conformance.RunIssueOperationsUpdateProvenanceLabelsHistory(t, ctx, fixture) +} + +func TestIssueOperationsUpdatePersistentPreservesUnversionedClass(t *testing.T) { + fixture, ctx, cleanup := newDoltIssueOperationsFixture(t) + defer cleanup() + conformance.RunIssueOperationsUpdatePersistentPreservesUnversionedClass(t, ctx, fixture) +} + func newDoltIssueOperationsFixture(t *testing.T) (conformance.IssueOperationsStagingFixture, context.Context, func()) { t.Helper() store, storeCleanup := setupTestStore(t) diff --git a/internal/storage/dolt/issue_operations_tx.go b/internal/storage/dolt/issue_operations_tx.go index 60f9f3a15..74d3bc507 100644 --- a/internal/storage/dolt/issue_operations_tx.go +++ b/internal/storage/dolt/issue_operations_tx.go @@ -9,8 +9,19 @@ import ( ) func (s *DoltStore) runIssueOperationTx(ctx context.Context, commitMsg string, fn func(*sql.Tx) (storageissueops.ChangedTables, error)) error { - return s.withRetryTx(ctx, func(tx *sql.Tx) error { + return s.runIssueOperationTxWithMessage(ctx, func(tx *sql.Tx) (storageissueops.ChangedTables, string, error) { tables, err := fn(tx) + return tables, commitMsg, err + }) +} + +// runIssueOperationTxWithMessage is runIssueOperationTx for an operation whose +// commit message is only known once the body has run. A ready claim names the +// id it won, and nothing outside the transaction can predict which one that +// is, so the message is composed where the selection happens. +func (s *DoltStore) runIssueOperationTxWithMessage(ctx context.Context, fn func(*sql.Tx) (storageissueops.ChangedTables, string, error)) error { + return s.withRetryTx(ctx, func(tx *sql.Tx) error { + tables, commitMsg, err := fn(tx) if err != nil { return err } diff --git a/internal/storage/dolt/issues.go b/internal/storage/dolt/issues.go index 2361d4843..1298e48e6 100644 --- a/internal/storage/dolt/issues.go +++ b/internal/storage/dolt/issues.go @@ -404,6 +404,10 @@ func (s *DoltStore) ClaimReadyIssue(ctx context.Context, filter types.WorkFilter // front and may legitimately claim a different issue. Split from // ClaimReadyIssue so injection tests can drive the write seam directly, the // same way the verifiedClaimWrite tests do. +// +// The re-read is per-attempt and plane-aware (readReadyClaimState): the winner +// may be an ephemeral row, and a replay may win a row in the other plane than +// the first attempt selected. func (s *DoltStore) verifiedReadyClaim(ctx context.Context, actor string, write func() (*types.Issue, error)) (*types.Issue, error) { claimed, err := write() if err != nil && !(errors.Is(err, errCommitPhase) && claimed != nil && s.serverMode) { @@ -413,7 +417,7 @@ func (s *DoltStore) verifiedReadyClaim(ctx context.Context, actor string, write return claimed, err } for attempt := 0; ; attempt++ { - assignee, status, verr := s.readClaimState(ctx, claimed.ID) + assignee, status, verr := s.readReadyClaimState(ctx, claimed.ID) if verr != nil { if err != nil { return nil, err // the honest indeterminate error from withRetryTx diff --git a/internal/storage/dolt/lifecycle_close_reopen_contract_test.go b/internal/storage/dolt/lifecycle_close_reopen_contract_test.go new file mode 100644 index 000000000..c80d9a7c9 --- /dev/null +++ b/internal/storage/dolt/lifecycle_close_reopen_contract_test.go @@ -0,0 +1,80 @@ +package dolt + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/backend/conformance" +) + +// TestLifecycleCloseReopenContract runs the Close/Reopen half of the Lifecycle +// contract against the server-backed store. It shares its validate/execute body +// with the embedded store (internal/storage/issueops ExecuteClose and +// ExecuteReopen), so this wiring and the embedded one are ONE vote on the +// semantics; the unit-of-work wiring is the second. +// +// The cases are subtests of one parent so the whole role suite shares one store +// and one copy-on-write branch: each Run namespaces its ids under the fixture +// prefix, and the event assertions take before/after deltas, which is only +// meaningful while the subtests run sequentially. setupTestStore already marks +// the PARENT parallel; no subtest here calls t.Parallel. +func TestLifecycleCloseReopenContract(t *testing.T) { + fixture, ctx, cleanup := newDoltLifecycleCloseReopenFixture(t, "lcr") + defer cleanup() + + t.Run("CloseRefusalsCarryTheirTypesAndWriteNothing", func(t *testing.T) { + conformance.RunLifecycleCloseRefusalsCarryTheirTypesAndWriteNothing(t, ctx, fixture) + }) + t.Run("CloseIsIdempotentAndKeepsTheFirstClose", func(t *testing.T) { + conformance.RunLifecycleCloseIsIdempotentAndKeepsTheFirstClose(t, ctx, fixture) + }) + t.Run("ReopenLeavesNonDoneStatusesUnchanged", func(t *testing.T) { + conformance.RunLifecycleReopenLeavesNonDoneStatusesUnchanged(t, ctx, fixture) + }) + t.Run("CloseAndReopenSpanTheConfiguredDoneCategory", func(t *testing.T) { + conformance.RunLifecycleCloseAndReopenSpanTheConfiguredDoneCategory(t, ctx, fixture) + }) + t.Run("ExpectedVersionIsCheckedBeforeTheNoOps", func(t *testing.T) { + conformance.RunLifecycleExpectedVersionIsCheckedBeforeTheNoOps(t, ctx, fixture) + }) + t.Run("ReopenRecordsItsReason", func(t *testing.T) { + conformance.RunLifecycleReopenRecordsItsReason(t, ctx, fixture) + }) + t.Run("ReopenProvenanceLabelsHistory", func(t *testing.T) { + conformance.RunLifecycleReopenProvenanceLabelsHistory(t, ctx, fixture) + }) + t.Run("ResultsAreHydratedPostStateSnapshots", func(t *testing.T) { + conformance.RunLifecycleResultsAreHydratedPostStateSnapshots(t, ctx, fixture) + }) + t.Run("CloseAndReopenRequireActorAndIssueID", func(t *testing.T) { + conformance.RunLifecycleCloseAndReopenRequireActorAndIssueID(t, ctx, fixture) + }) +} + +func newDoltLifecycleCloseReopenFixture(t *testing.T, prefix string) (conformance.LifecycleCloseReopenFixture, context.Context, func()) { + t.Helper() + store, storeCleanup := setupTestStore(t) + ctx, cancel := testContext(t) + // Through the capability accessor, not NewIssueOperations: a store that + // stopped offering the role is the regression, and a constructor call would + // hide it. + lifecycle, err := store.IssueLifecycle() + if err != nil { + cancel() + storeCleanup() + t.Fatalf("IssueLifecycle(): %v", err) + } + kit := newDoltRoleFixtureKit(store, prefix) + fixture := conformance.LifecycleCloseReopenFixture{ + IssuePrefix: kit.IssuePrefix, + Lifecycle: lifecycle, + CreateIssue: kit.CreateIssue, + AddDependency: kit.AddDependency, + SetConfig: kit.SetConfig, + QueryScalar: kit.QueryScalar, + } + return fixture, ctx, func() { + cancel() + storeCleanup() + } +} diff --git a/internal/storage/dolt/reader_contract_test.go b/internal/storage/dolt/reader_contract_test.go new file mode 100644 index 000000000..910bedb88 --- /dev/null +++ b/internal/storage/dolt/reader_contract_test.go @@ -0,0 +1,178 @@ +package dolt + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/backend/conformance" +) + +// The Reader contract, wired at the server-backed store. This accessor and the +// embedded one both return workapi/storereader.New(store), so these two wirings +// run ONE body against two engines; the third wiring +// (internal/storage/uow/reader_contract_test.go) is the genuinely separate +// implementation. A case passing here and on the embedded store is one vote, +// not two. + +func TestReaderReadyDefaultTypeExclusionsYieldToAnExplicitType(t *testing.T) { + fixture, ctx, cleanup := newDoltReaderFixture(t, "rdr") + defer cleanup() + conformance.RunReaderReadyDefaultTypeExclusionsYieldToAnExplicitType(t, ctx, fixture) +} + +func TestReaderReadyDeferredAndEphemeralGates(t *testing.T) { + fixture, ctx, cleanup := newDoltReaderFixture(t, "rdr") + defer cleanup() + conformance.RunReaderReadyDeferredAndEphemeralGates(t, ctx, fixture) +} + +func TestReaderReadyLimitBoundary(t *testing.T) { + fixture, ctx, cleanup := newDoltReaderFixture(t, "rdr") + defer cleanup() + conformance.RunReaderReadyLimitBoundary(t, ctx, fixture) +} + +func TestReaderOffsetIsHonoredOrRefused(t *testing.T) { + fixture, ctx, cleanup := newDoltReaderFixture(t, "rdr") + defer cleanup() + conformance.RunReaderOffsetIsHonoredOrRefused(t, ctx, fixture) +} + +func TestReaderReadySortPoliciesOrderTheSameRows(t *testing.T) { + fixture, ctx, cleanup := newDoltReaderFixture(t, "rdr") + defer cleanup() + conformance.RunReaderReadySortPoliciesOrderTheSameRows(t, ctx, fixture) +} + +func TestReaderListDefaultExclusionsAndTheirOverrides(t *testing.T) { + fixture, ctx, cleanup := newDoltReaderFixture(t, "rdr") + defer cleanup() + conformance.RunReaderListDefaultExclusionsAndTheirOverrides(t, ctx, fixture) +} + +func TestReaderListRejectsATypeOutsideTheWorkspaceVocabulary(t *testing.T) { + fixture, ctx, cleanup := newDoltReaderFixture(t, "rdr") + defer cleanup() + conformance.RunReaderListRejectsATypeOutsideTheWorkspaceVocabulary(t, ctx, fixture) +} + +func TestReaderListNaturalNumericIDSortTrimsAfterTheFetch(t *testing.T) { + fixture, ctx, cleanup := newDoltReaderFixture(t, "rdr") + defer cleanup() + conformance.RunReaderListNaturalNumericIDSortTrimsAfterTheFetch(t, ctx, fixture) +} + +func TestReaderListLimitBoundaryUnderASortTheDatabaseCanExpress(t *testing.T) { + fixture, ctx, cleanup := newDoltReaderFixture(t, "rdr") + defer cleanup() + conformance.RunReaderListLimitBoundaryUnderASortTheDatabaseCanExpress(t, ctx, fixture) +} + +func TestReaderReadySetOwnsItsStatusPinnedAndTemplateDecisions(t *testing.T) { + fixture, ctx, cleanup := newDoltReaderFixture(t, "rdr") + defer cleanup() + conformance.RunReaderReadySetOwnsItsStatusPinnedAndTemplateDecisions(t, ctx, fixture) +} + +func TestReaderListReadyFlagCarriesTheAssigneeAndPriorityFilters(t *testing.T) { + fixture, ctx, cleanup := newDoltReaderFixture(t, "rdr") + defer cleanup() + conformance.RunReaderListReadyFlagCarriesTheAssigneeAndPriorityFilters(t, ctx, fixture) +} + +func TestReaderListStatusAcceptsACommaSeparatedORSet(t *testing.T) { + fixture, ctx, cleanup := newDoltReaderFixture(t, "rdr") + defer cleanup() + conformance.RunReaderListStatusAcceptsACommaSeparatedORSet(t, ctx, fixture) +} + +func TestReaderListKeysetPositionResumesTheCreatedDescIDAscOrder(t *testing.T) { + fixture, ctx, cleanup := newDoltReaderFixture(t, "rdr") + defer cleanup() + conformance.RunReaderListKeysetPositionResumesTheCreatedDescIDAscOrder(t, ctx, fixture) +} + +func TestReaderListReadyFlagAnswersTheBlockerAwareSet(t *testing.T) { + fixture, ctx, cleanup := newDoltReaderFixture(t, "rdr") + defer cleanup() + conformance.RunReaderListReadyFlagAnswersTheBlockerAwareSet(t, ctx, fixture) +} + +func TestReaderListReadyFlagRefusesAFilterItCannotCarry(t *testing.T) { + fixture, ctx, cleanup := newDoltReaderFixture(t, "rdr") + defer cleanup() + conformance.RunReaderListReadyFlagRefusesAFilterItCannotCarry(t, ctx, fixture) +} + +func TestReaderListEmptyPageIsWellFormed(t *testing.T) { + fixture, ctx, cleanup := newDoltReaderFixture(t, "rdr") + defer cleanup() + conformance.RunReaderListEmptyPageIsWellFormed(t, ctx, fixture) +} + +func TestReaderGetResolvesTheExactIDAcrossBothPlanes(t *testing.T) { + fixture, ctx, cleanup := newDoltReaderFixture(t, "rdr") + defer cleanup() + conformance.RunReaderGetResolvesTheExactIDAcrossBothPlanes(t, ctx, fixture) +} + +func TestReaderGetMissIsNotFoundAndBackendFailureDoesNotDecay(t *testing.T) { + fixture, ctx, cleanup := newDoltReaderFixture(t, "rdr") + defer cleanup() + conformance.RunReaderGetMissIsNotFoundAndBackendFailureDoesNotDecay(t, ctx, fixture) +} + +func TestReaderGetOptionalRowListsAreOffByDefault(t *testing.T) { + fixture, ctx, cleanup := newDoltReaderFixture(t, "rdr") + defer cleanup() + conformance.RunReaderGetOptionalRowListsAreOffByDefault(t, ctx, fixture) +} + +func TestReaderGetDetailShapeMatchesTheSeededIssue(t *testing.T) { + fixture, ctx, cleanup := newDoltReaderFixture(t, "rdr") + defer cleanup() + conformance.RunReaderGetDetailShapeMatchesTheSeededIssue(t, ctx, fixture) +} + +func TestReaderDoesNotMutateTheCallerRequest(t *testing.T) { + fixture, ctx, cleanup := newDoltReaderFixture(t, "rdr") + defer cleanup() + conformance.RunReaderDoesNotMutateTheCallerRequest(t, ctx, fixture) +} + +// newDoltReaderFixture composes the shared role kit with the reader accessor. +// One store per case here rather than one per suite: setupTestStore gives each +// test its own copy-on-write branch and costs a fraction of a second, so the +// isolation is nearly free — unlike the unit-of-work wiring, where a provider +// boot is seconds and the suite has to share one. +func newDoltReaderFixture(t *testing.T, prefix string) (conformance.ReaderFixture, context.Context, func()) { + t.Helper() + store, storeCleanup := setupTestStore(t) + ctx, cancel := testContext(t) + reader, err := store.IssueReader() + if err != nil { + cancel() + storeCleanup() + t.Fatalf("IssueReader(): %v", err) + } + kit := newDoltRoleFixtureKit(store, prefix) + fixture := conformance.ReaderFixture{ + IssuePrefix: kit.IssuePrefix, + Reader: reader, + CreateIssue: kit.CreateIssue, + CreateWisp: kit.CreateWisp, + AddDependency: kit.AddDependency, + // Not on the kit: the role fixtures the scaffolding slice froze have no + // comment hook, and the Get detail view's comment count and opt-in + // comment rows cannot be asserted without one. Supplied locally rather + // than by editing the frozen kit. + AddComment: func(ctx context.Context, issueID, author, text string) error { + _, err := store.AddIssueComment(ctx, issueID, author, text) + return err + }, + } + return fixture, ctx, func() { + cancel() + storeCleanup() + } +} diff --git a/internal/storage/dolt/ready_claimer.go b/internal/storage/dolt/ready_claimer.go new file mode 100644 index 000000000..8d9ee2197 --- /dev/null +++ b/internal/storage/dolt/ready_claimer.go @@ -0,0 +1,74 @@ +package dolt + +import ( + "context" + "database/sql" + + "github.com/steveyegge/beads/internal/storage" + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/internal/workapi" + "github.com/steveyegge/beads/issueops" +) + +// ReadyClaimer returns the guarded take-ready-work surface for this store. +func (s *DoltStore) ReadyClaimer() (issueops.ReadyClaimer, error) { + return NewReadyClaimer(s) +} + +// NewReadyClaimer returns a guarded ready claimer backed by store. +func NewReadyClaimer(store *DoltStore) (issueops.ReadyClaimer, error) { + if store == nil { + return nil, &storage.ErrUnsupported{Op: "NewReadyClaimer", Backend: "nil"} + } + return &readyClaimer{store: store}, nil +} + +type readyClaimer struct{ store *DoltStore } + +// ClaimNext runs selection, the compare-and-set and hydration in one +// transaction, under the claim-family verify-after-write (bd-zccb9) that +// ClaimReadyIssue runs: this reaches the same writes, so under a degraded +// server its exit status is no more trustworthy than that one's. A replay is +// safe and may legitimately win a DIFFERENT issue, because the replay re-scans +// the ready front rather than re-asserting a decision the first attempt made. +func (c *readyClaimer) ClaimNext(ctx context.Context, request issueops.ClaimNextRequest) (issueops.ClaimNextResult, error) { + if err := storageissueops.ValidateClaimNextRequest(request); err != nil { + return issueops.ClaimNextResult{}, err + } + // The same builder Reader.Ready runs, over the same request type: the + // claim's predicate IS the listing's predicate, because there is only one + // place that turns the request into a filter. + filter, err := workapi.BuildReadyFilter(request.Filter) + if err != nil { + return issueops.ClaimNextResult{}, err + } + + var result issueops.ClaimNextResult + write := func() (*types.Issue, error) { + var claimed *types.Issue + err := c.store.runIssueOperationTxWithMessage(ctx, func(tx *sql.Tx) (storageissueops.ChangedTables, string, error) { + attempt, tables, err := storageissueops.ExecuteClaimNext(ctx, tx, request.Actor, filter) + if err != nil { + return nil, "", err + } + result = attempt + if attempt.Claimed == nil { + return tables, "", nil + } + claimed = attempt.Claimed.Issue + // The message names the claimed issue because that is the one `bd + // dolt log` affordance callers actually grep, and it is what the + // store's own ClaimReadyIssue wrote before the claim moved here. + return tables, storageissueops.ClaimNextCommitMessage(attempt.Claimed.ID), nil + }) + return claimed, err + } + + if _, err := c.store.verifiedReadyClaim(ctx, request.Actor, write); err != nil { + return issueops.ClaimNextResult{}, err + } + return result, nil +} + +var _ issueops.ReadyClaimer = (*readyClaimer)(nil) diff --git a/internal/storage/dolt/ready_claimer_contract_test.go b/internal/storage/dolt/ready_claimer_contract_test.go new file mode 100644 index 000000000..b55a4d72a --- /dev/null +++ b/internal/storage/dolt/ready_claimer_contract_test.go @@ -0,0 +1,103 @@ +package dolt + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/backend/conformance" +) + +func TestReadyClaimerRejectsLimitOffsetAndEmptyActor(t *testing.T) { + fixture, ctx, cleanup := newDoltReadyClaimerFixture(t, "rcrej") + defer cleanup() + conformance.RunReadyClaimerRejectsLimitOffsetAndEmptyActor(t, ctx, fixture) +} + +func TestReadyClaimerEmptyFrontIsNormal(t *testing.T) { + fixture, ctx, cleanup := newDoltReadyClaimerFixture(t, "rcempty") + defer cleanup() + conformance.RunReadyClaimerEmptyFrontIsNormal(t, ctx, fixture) +} + +func TestReadyClaimerClaimsTheFrontRowAndReturnsThePostClaimState(t *testing.T) { + fixture, ctx, cleanup := newDoltReadyClaimerFixture(t, "rcwin") + defer cleanup() + conformance.RunReadyClaimerClaimsTheFrontRowAndReturnsThePostClaimState(t, ctx, fixture) +} + +func TestReadyClaimerClaimsAnEphemeralRowTheFilterAdmits(t *testing.T) { + fixture, ctx, cleanup := newDoltReadyClaimerFixture(t, "rcwisp") + defer cleanup() + conformance.RunReadyClaimerClaimsAnEphemeralRowTheFilterAdmits(t, ctx, fixture) +} + +func TestReadyClaimerLeavesEphemeralRowsOutOfTheDefaultReadySet(t *testing.T) { + fixture, ctx, cleanup := newDoltReadyClaimerFixture(t, "rcdefault") + defer cleanup() + conformance.RunReadyClaimerLeavesEphemeralRowsOutOfTheDefaultReadySet(t, ctx, fixture) +} + +func TestReadyClaimerLeasesADurableWinButNotAnEphemeralOne(t *testing.T) { + fixture, ctx, cleanup := newDoltReadyClaimerFixture(t, "rclease") + defer cleanup() + conformance.RunReadyClaimerLeasesADurableWinButNotAnEphemeralOne(t, ctx, fixture) +} + +func TestReadyClaimerAnswersTheQuestionReaderReadyLists(t *testing.T) { + fixture, ctx, cleanup := newDoltReadyClaimerFixture(t, "rcagree") + defer cleanup() + conformance.RunReadyClaimerAnswersTheQuestionReaderReadyLists(t, ctx, fixture) +} + +func TestReadyClaimerSkipsIneligibleFrontRows(t *testing.T) { + fixture, ctx, cleanup := newDoltReadyClaimerFixture(t, "rcskip") + defer cleanup() + conformance.RunReadyClaimerSkipsIneligibleFrontRows(t, ctx, fixture) +} + +func TestReadyClaimerRecordsOneHistoryEntryForAWin(t *testing.T) { + fixture, ctx, cleanup := newDoltReadyClaimerFixture(t, "rchist") + defer cleanup() + conformance.RunReadyClaimerRecordsOneHistoryEntryForAWin(t, ctx, fixture) +} + +func TestReadyClaimerDoesNotMutateTheCallerRequest(t *testing.T) { + fixture, ctx, cleanup := newDoltReadyClaimerFixture(t, "rcsnap") + defer cleanup() + conformance.RunReadyClaimerDoesNotMutateTheCallerRequest(t, ctx, fixture) +} + +// newDoltReadyClaimerFixture composes the frozen role kit with this backend's +// two accessors. A store per case is affordable here — setupTestStore hands out +// a copy-on-write branch of the shared package server — which is why this +// wiring keeps one test function per case while the unit-of-work one cannot. +func newDoltReadyClaimerFixture(t *testing.T, prefix string) (conformance.ReadyClaimerFixture, context.Context, func()) { + t.Helper() + store, storeCleanup := setupTestStore(t) + ctx, cancel := testContext(t) + stop := func() { + cancel() + storeCleanup() + } + claimer, err := store.ReadyClaimer() + if err != nil { + stop() + t.Fatalf("ReadyClaimer(): %v", err) + } + reader, err := store.IssueReader() + if err != nil { + stop() + t.Fatalf("IssueReader(): %v", err) + } + kit := newDoltRoleFixtureKit(store, prefix) + return conformance.ReadyClaimerFixture{ + IssuePrefix: kit.IssuePrefix, + Claimer: claimer, + Reader: reader, + CreateIssue: kit.CreateIssue, + CreateWisp: kit.CreateWisp, + AddDependency: kit.AddDependency, + QueryScalar: kit.QueryScalar, + CountHistory: kit.CountHistory, + }, ctx, stop +} diff --git a/internal/storage/dolt/relations.go b/internal/storage/dolt/relations.go new file mode 100644 index 000000000..f426e9eb2 --- /dev/null +++ b/internal/storage/dolt/relations.go @@ -0,0 +1,47 @@ +package dolt + +import ( + "context" + "database/sql" + + "github.com/steveyegge/beads/internal/storage" + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" +) + +// IssueRelations returns the guarded neighbor-query surface for this store. +func (s *DoltStore) IssueRelations() (issueops.Relations, error) { + return NewIssueRelations(s) +} + +// NewIssueRelations returns guarded neighbor queries backed by store. +func NewIssueRelations(store *DoltStore) (issueops.Relations, error) { + if store == nil { + return nil, &storage.ErrUnsupported{Op: "NewIssueRelations", Backend: "nil"} + } + return &issueRelations{store: store}, nil +} + +type issueRelations struct{ store *DoltStore } + +// Related runs the anchor probe and the neighbor read in ONE read +// transaction, so an anchor cannot be reported missing by a probe that raced a +// create the neighbor read then saw. +func (r *issueRelations) Related(ctx context.Context, request issueops.RelatedRequest) ([]*issueops.RelatedIssue, error) { + if err := storageissueops.ValidateRelatedRequest(request); err != nil { + return nil, err + } + var items []*types.IssueWithDependencyMetadata + err := r.store.withReadTx(ctx, func(tx *sql.Tx) error { + var err error + items, err = storageissueops.ExecuteRelated(ctx, tx, request) + return err + }) + if err != nil { + return nil, err + } + return items, nil +} + +var _ issueops.Relations = (*issueRelations)(nil) diff --git a/internal/storage/dolt/relations_contract_test.go b/internal/storage/dolt/relations_contract_test.go new file mode 100644 index 000000000..3d2582411 --- /dev/null +++ b/internal/storage/dolt/relations_contract_test.go @@ -0,0 +1,111 @@ +package dolt + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/backend/conformance" +) + +func TestRelationsAnswersInThePinnedOrder(t *testing.T) { + fixture, ctx, cleanup := newDoltRelationsFixture(t, "relord") + defer cleanup() + conformance.RunRelationsAnswersInThePinnedOrder(t, ctx, fixture) +} + +func TestRelationsOrdersNeighborsFromBothPlanesTogether(t *testing.T) { + fixture, ctx, cleanup := newDoltRelationsFixture(t, "relplane") + defer cleanup() + conformance.RunRelationsOrdersNeighborsFromBothPlanesTogether(t, ctx, fixture) +} + +func TestRelationsAnswersAWispTargetInTheOutDirection(t *testing.T) { + fixture, ctx, cleanup := newDoltRelationsFixture(t, "relwout") + defer cleanup() + conformance.RunRelationsAnswersAWispTargetInTheOutDirection(t, ctx, fixture) +} + +func TestRelationsRefusesTheZeroDirection(t *testing.T) { + fixture, ctx, cleanup := newDoltRelationsFixture(t, "reldirnone") + defer cleanup() + conformance.RunRelationsRefusesTheZeroDirection(t, ctx, fixture) +} + +func TestRelationsSeparatesNoNeighborsFromNoSuchIssue(t *testing.T) { + fixture, ctx, cleanup := newDoltRelationsFixture(t, "relmiss") + defer cleanup() + conformance.RunRelationsSeparatesNoNeighborsFromNoSuchIssue(t, ctx, fixture) +} + +func TestRelationsResolvesAWispAnchor(t *testing.T) { + fixture, ctx, cleanup := newDoltRelationsFixture(t, "relwisp") + defer cleanup() + conformance.RunRelationsResolvesAWispAnchor(t, ctx, fixture) +} + +func TestRelationsFiltersByAnOpenTypeVocabulary(t *testing.T) { + fixture, ctx, cleanup := newDoltRelationsFixture(t, "relfilter") + defer cleanup() + conformance.RunRelationsFiltersByAnOpenTypeVocabulary(t, ctx, fixture) +} + +func TestRelationsRefusesAnUnusableTypeFilter(t *testing.T) { + fixture, ctx, cleanup := newDoltRelationsFixture(t, "relbadfilter") + defer cleanup() + conformance.RunRelationsRefusesAnUnusableTypeFilter(t, ctx, fixture) +} + +func TestRelationsRefusesATypeFilterOverTheColumnLength(t *testing.T) { + fixture, ctx, cleanup := newDoltRelationsFixture(t, "rellongfilter") + defer cleanup() + conformance.RunRelationsRefusesATypeFilterOverTheColumnLength(t, ctx, fixture) +} + +func TestRelationsDirectionSelectsTheInverseGraph(t *testing.T) { + fixture, ctx, cleanup := newDoltRelationsFixture(t, "reldir") + defer cleanup() + conformance.RunRelationsDirectionSelectsTheInverseGraph(t, ctx, fixture) +} + +func TestRelationsLeavesTheCallersRequestAlone(t *testing.T) { + fixture, ctx, cleanup := newDoltRelationsFixture(t, "relsnap") + defer cleanup() + conformance.RunRelationsLeavesTheCallersRequestAlone(t, ctx, fixture) +} + +func TestRelationsLeavesAnExternalTargetOutOfTheAnswer(t *testing.T) { + fixture, ctx, cleanup := newDoltRelationsFixture(t, "relext") + defer cleanup() + conformance.RunRelationsLeavesAnExternalTargetOutOfTheAnswer(t, ctx, fixture) +} + +func TestRelationsResolvesTheAnchorIDExactly(t *testing.T) { + fixture, ctx, cleanup := newDoltRelationsFixture(t, "relexact") + defer cleanup() + conformance.RunRelationsResolvesTheAnchorIDExactly(t, ctx, fixture) +} + +func newDoltRelationsFixture(t *testing.T, prefix string) (conformance.RelationsFixture, context.Context, func()) { + t.Helper() + store, storeCleanup := setupTestStore(t) + ctx, cancel := testContext(t) + relations, err := store.IssueRelations() + if err != nil { + cancel() + storeCleanup() + t.Fatalf("IssueRelations(): %v", err) + } + kit := newDoltRoleFixtureKit(store, prefix) + fixture := conformance.RelationsFixture{ + IssuePrefix: kit.IssuePrefix, + Relations: relations, + CreateIssue: kit.CreateIssue, + CreateWisp: kit.CreateWisp, + AddDependency: kit.AddDependency, + QueryScalar: kit.QueryScalar, + } + return fixture, ctx, func() { + cancel() + storeCleanup() + } +} diff --git a/internal/storage/dolt/role_fixture_kit_test.go b/internal/storage/dolt/role_fixture_kit_test.go new file mode 100644 index 000000000..80353bf01 --- /dev/null +++ b/internal/storage/dolt/role_fixture_kit_test.go @@ -0,0 +1,243 @@ +package dolt + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/backend/conformance" + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/types" +) + +// roleFixtureKit is the server-backed store's answer to the hooks every +// issueops role fixture in package conformance needs. A role's wiring file +// composes one of these with the accessor under test and the IssuePrefix, so +// the seeding and scalar-query plumbing is written once per backend instead of +// once per role. +// +// The field names and signatures are IDENTICAL across the three backends' +// kits, and identical to the fields the conformance fixtures declare, so a kit +// closure is assignable to any role fixture with no adapter in between. That +// sameness is the point of the type; changing a signature here is a change to +// all three backends and to every role wiring at once. +// +// FROZEN SURFACE. This file is owned by the scaffolding slice (bd-kue5t) and +// no role slice edits it. A role that needs a hook this kit does not expose +// routes the addition through a follow-up commit against that bead, so the +// three kits never drift apart in a worktree. +// +// NAMING CONVENTION FOR EVERYTHING BUILT ON THIS KIT: every unexported helper a +// role slice adds — in package conformance and in the per-backend wiring files — +// is ROLE-PREFIXED (seedRelationsAnchor, assertCommenterEventCount), the way the +// existing contract already names seedDependencyEditorIssue and +// assertDependencyEdgeCount. Five slices add files to one package from separate +// worktrees; two of them each defining a bare seedIssue would compile alone and +// break combined. The scaffolding's own helpers are prefixed roleFixtureKit for +// the same reason. +type roleFixtureKit struct { + // IssuePrefix namespaces the ids each assertion seeds, so several + // assertions can share one database. + IssuePrefix string + // CreateIssue seeds a durable issue in the issues plane. + CreateIssue func(context.Context, *types.Issue, string) error + // CreateWisp seeds an ephemeral issue in the wisps plane. It is a separate + // field rather than a flag because the three backends reach the two planes + // through different verbs. + CreateWisp func(context.Context, *types.Issue, string) error + // AddDependency seeds ONE edge, routed to the plane the edge's SOURCE lives + // in, and RECORDS a dependency_added event. + // + // The event is not incidental. The unit-of-work backend has no event-free + // route to the dependency tables — both domain.DependencyUseCase.add and + // AddDependencies hard-code EmitEvent: true — while the two store backends + // default the other way (dolt/dependencies.go:20-26 "adds a dependency + // between two issues WITHOUT recording a dependency_added event"). Rather + // than let the same seed leave different rows behind on different backends, + // all three kits emit. A contract case that counts events must therefore + // take a DELTA around the operation under test; an absolute count taken + // after seeding edges counts the seeds too. + // + // SPEC-GAP bd-yby99.1: no issueops leaf doc says whether a structural + // dependency insert records an event, so the kits normalise rather than + // pick a winner. The owner adjudicates it with the rest of the batch. + AddDependency func(context.Context, *types.Dependency, string) error + // SetConfig writes one workspace config key, which is how a case installs + // the vocabulary (excluded types, default limits) a request is read against. + SetConfig func(context.Context, string, string) error + // QueryScalar runs a single-row query and scans it, and RETURNS the error + // rather than failing the test, so a case can assert on a query that is + // expected to fail. + QueryScalar func(context.Context, string, []any, ...any) error + // CountHistory reports how many history entries the fixture's branch has, + // for the "at most one entry per call, none when nothing landed" clause the + // role contracts state. Cases take it before and after rather than reading + // the top of the log, because two commits made inside one second tie on + // date and their relative order is not something to rely on. + // + // A nil CountHistory means "this backend cannot observe history here". A + // case that needs it must then skip LOUDLY with that reason rather than + // pass quietly. It is non-nil on all three backends today; see + // uow/role_fixture_kit_test.go for the evidence on the awkward one. + CountHistory func(context.Context) (int, error) +} + +// roleFixtureKitComposesConformanceFixtures is the compile-time half of the +// kit's promise: every hook is assignable to the fixture field of the same +// name with NO adapter in between. A signature drifting apart from the +// conformance fixtures breaks here, in the frozen file that owns the +// signatures, instead of in five role wirings at once. +var roleFixtureKitComposesConformanceFixtures = func(kit roleFixtureKit) (conformance.DependencyEditorFixture, conformance.IssueOperationsStagingFixture) { + return conformance.DependencyEditorFixture{ + IssuePrefix: kit.IssuePrefix, + CreateIssue: kit.CreateIssue, + CreateWisp: kit.CreateWisp, + QueryScalar: kit.QueryScalar, + }, conformance.IssueOperationsStagingFixture{ + IssuePrefix: kit.IssuePrefix, + CreateIssue: kit.CreateIssue, + AddDependency: kit.AddDependency, + SetConfig: kit.SetConfig, + QueryScalar: kit.QueryScalar, + } +} + +// newDoltRoleFixtureKit builds the kit for a store from setupTestStore. The +// store's own create routes an ephemeral issue to the wisps plane, so the two +// seed verbs differ only by the flag already on the issue. +func newDoltRoleFixtureKit(store *DoltStore, prefix string) roleFixtureKit { + return roleFixtureKit{ + IssuePrefix: prefix, + CreateIssue: store.CreateIssue, + CreateWisp: store.CreateIssue, + AddDependency: func(ctx context.Context, dep *types.Dependency, actor string) error { + return store.AddDependencyWithOptions(ctx, dep, actor, storage.DependencyAddOptions{EmitEvent: true}) + }, + SetConfig: store.SetConfig, + QueryScalar: func(ctx context.Context, query string, args []any, dest ...any) error { + return store.db.QueryRowContext(ctx, query, args...).Scan(dest...) + }, + CountHistory: func(ctx context.Context) (int, error) { + var entries int + err := store.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM dolt_log").Scan(&entries) + return entries, err + }, + } +} + +// TestDoltRoleFixtureKitHooksAreUsable is the scaffolding's own tripwire: every +// hook the role fixtures compose is exercised once here, so a kit broken by a +// signature change fails in one obvious place instead of five role suites. +func TestDoltRoleFixtureKitHooksAreUsable(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + kit := newDoltRoleFixtureKit(store, "test") + + assertRoleFixtureKitHooksAreUsable(t, ctx, kit) +} + +// assertRoleFixtureKitHooksAreUsable drives every hook once and checks the rows +// landed where the field docs say they land. It is shared by the kit tripwire +// and is deliberately not a conformance case: it pins the FIXTURE, not a role. +func assertRoleFixtureKitHooksAreUsable(t *testing.T, ctx context.Context, kit roleFixtureKit) { + t.Helper() + issue := kit.IssuePrefix + "-kit-issue" + target := kit.IssuePrefix + "-kit-target" + wisp := kit.IssuePrefix + "-kit-wisp" + + for _, id := range []string{issue, target} { + if err := kit.CreateIssue(ctx, &types.Issue{ + ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, + }, "seed"); err != nil { + t.Fatalf("kit.CreateIssue(%s): %v", id, err) + } + } + if err := kit.CreateWisp(ctx, &types.Issue{ + ID: wisp, Title: wisp, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: true, + }, "seed"); err != nil { + t.Fatalf("kit.CreateWisp(%s): %v", wisp, err) + } + if err := kit.AddDependency(ctx, &types.Dependency{ + IssueID: issue, DependsOnID: target, Type: types.DepBlocks, + }, "seed"); err != nil { + t.Fatalf("kit.AddDependency: %v", err) + } + if err := kit.SetConfig(ctx, "role_fixture_kit_probe", "on"); err != nil { + t.Fatalf("kit.SetConfig: %v", err) + } + + var issues, wisps, edges int + if err := kit.QueryScalar(ctx, "SELECT COUNT(*) FROM issues WHERE id IN (?, ?)", []any{issue, target}, &issues); err != nil { + t.Fatalf("kit.QueryScalar issues: %v", err) + } + if issues != 2 { + t.Fatalf("seeded durable issues = %d, want 2", issues) + } + if err := kit.QueryScalar(ctx, "SELECT COUNT(*) FROM wisps WHERE id = ?", []any{wisp}, &wisps); err != nil { + t.Fatalf("kit.QueryScalar wisps: %v", err) + } + if wisps != 1 { + t.Fatalf("seeded wisps = %d, want 1 — CreateWisp did not reach the ephemeral plane", wisps) + } + if err := kit.QueryScalar(ctx, + // The target's own class decides which typed column holds it, so the + // contracts resolve it through this COALESCE rather than one column. + "SELECT COUNT(*) FROM dependencies WHERE issue_id = ? AND "+ + "COALESCE(depends_on_issue_id, depends_on_wisp_id, depends_on_external) = ?", + []any{issue, target}, &edges); err != nil { + t.Fatalf("kit.QueryScalar dependencies: %v", err) + } + if edges != 1 { + t.Fatalf("seeded edges = %d, want 1", edges) + } + var configured string + if err := kit.QueryScalar(ctx, "SELECT value FROM config WHERE `key` = ?", []any{"role_fixture_kit_probe"}, &configured); err != nil { + t.Fatalf("kit.QueryScalar config: %v", err) + } + if configured != "on" { + t.Fatalf("configured value = %q, want %q", configured, "on") + } + + if kit.CountHistory == nil { + t.Fatal("kit.CountHistory is nil — this backend cannot observe history, which the role contracts' entry-per-call clause needs") + } + entries, err := kit.CountHistory(ctx) + if err != nil { + t.Fatalf("kit.CountHistory: %v", err) + } + if entries < 1 { + t.Fatalf("history entries = %d, want at least the initializing commit", entries) + } +} + +// TestDoltRoleFixtureKitCountHistoryMovesWithACommit is the other half of the +// history capability: CountHistory has to MOVE, not merely answer. The seed +// hooks are the wrong probe for it — only some of them version what they write +// (the embedded store's withConn takes a SQL commit, not a Dolt one) — so each +// backend proves the delta with its own committing verb. +func TestDoltRoleFixtureKitCountHistoryMovesWithACommit(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + ctx, cancel := testContext(t) + defer cancel() + kit := newDoltRoleFixtureKit(store, "test") + + seedIssues(ctx, t, store, "test-kit-hist-a", "test-kit-hist-b") + before, err := kit.CountHistory(ctx) + if err != nil { + t.Fatalf("CountHistory before: %v", err) + } + if err := kit.AddDependency(ctx, &types.Dependency{ + IssueID: "test-kit-hist-a", DependsOnID: "test-kit-hist-b", Type: types.DepBlocks, + }, "writer"); err != nil { + t.Fatalf("AddDependency: %v", err) + } + after, err := kit.CountHistory(ctx) + if err != nil { + t.Fatalf("CountHistory after: %v", err) + } + if after != before+1 { + t.Fatalf("history entries went %d -> %d across one versioned write, want exactly one more", before, after) + } +} diff --git a/internal/storage/dolt/role_test_helpers_test.go b/internal/storage/dolt/role_test_helpers_test.go new file mode 100644 index 000000000..2c8eda4aa --- /dev/null +++ b/internal/storage/dolt/role_test_helpers_test.go @@ -0,0 +1,42 @@ +package dolt + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/internal/types" +) + +// This file holds the test helpers the issueops role tests share. They live +// here, in a file that owns no test of its own, because the per-role duplicate +// files that used to define them are being folded into the shared conformance +// contracts one role at a time: a helper defined inside a file that is about to +// be deleted takes its siblings' compilation with it. + +// seedIssues creates durable issues with the given ids, in one batch. +func seedIssues(ctx context.Context, t *testing.T, store *DoltStore, ids ...string) { + t.Helper() + issues := make([]*types.Issue, 0, len(ids)) + for _, id := range ids { + issues = append(issues, &types.Issue{ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask}) + } + if err := store.CreateIssues(ctx, issues, "seed"); err != nil { + t.Fatalf("seed issues %v: %v", ids, err) + } +} + +// skipKnownDivergence parks one conformance case on the backend that disagrees +// with the leaf contract's doc comment. +// +// The contract case asserts what the doc promises, so a genuine disagreement is +// a behaviour-unification decision for the owner rather than something a test +// slice may settle by weakening the assertion. Parking at the WIRING site (never +// inside the shared Run function) keeps the case running and passing on the +// backends that agree, so their behaviour is pinned the day the divergence is +// found. The "KNOWN DIVERGENCE" prefix is literal so `grep -r "KNOWN DIVERGENCE"` +// finds every parked case, and beadID names the child of bd-yby99 that records +// the three-way observed behaviour. +func skipKnownDivergence(t *testing.T, beadID, reason string) { + t.Helper() + t.Skipf("KNOWN DIVERGENCE %s: %s", beadID, reason) +} diff --git a/internal/storage/domain/db/dependency.go b/internal/storage/domain/db/dependency.go index 13eb03cac..915ec9e63 100644 --- a/internal/storage/domain/db/dependency.go +++ b/internal/storage/domain/db/dependency.go @@ -42,8 +42,15 @@ func pickDepTable(useWisps bool) string { return "dependencies" } -func (r *dependencySQLRepositoryImpl) pickDepTargetColumn(ctx context.Context, dependsOnID string) (string, error) { - if strings.HasPrefix(dependsOnID, "external:") { +// pickDepTargetColumn classifies an edge's target the same way the in-tx store +// bodies do, through issueops.IsExternalDepTarget: a target this database +// cannot hold — an "external:" reference or an issue belonging to another +// repository — goes to depends_on_external, which carries no foreign key. +// Only a target that could plausibly be local is probed against wisps and +// otherwise treated as a local issue, where fk_dep_issue_target still refuses +// an id that is genuinely missing. +func (r *dependencySQLRepositoryImpl) pickDepTargetColumn(ctx context.Context, issueID, dependsOnID string) (string, error) { + if issueops.IsExternalDepTarget(issueID, dependsOnID) { return "depends_on_external", nil } var probe int @@ -127,7 +134,7 @@ func (r *dependencySQLRepositoryImpl) Insert(ctx context.Context, dep *types.Dep return fmt.Errorf("db: DependencySQLRepository.Insert: check existing: %w", err) } - targetCol, err := r.pickDepTargetColumn(ctx, dep.DependsOnID) + targetCol, err := r.pickDepTargetColumn(ctx, dep.IssueID, dep.DependsOnID) if err != nil { return fmt.Errorf("db: DependencySQLRepository.Insert: %w", err) } @@ -214,8 +221,7 @@ func (r *dependencySQLRepositoryImpl) ValidateBlockingHierarchy(ctx context.Cont if dep == nil { return errors.New("db: DependencySQLRepository.ValidateBlockingHierarchy: dep must not be nil") } - if strings.HasPrefix(dep.DependsOnID, "external:") || - types.ExtractPrefix(dep.IssueID) != types.ExtractPrefix(dep.DependsOnID) { + if issueops.IsExternalDepTarget(dep.IssueID, dep.DependsOnID) { return nil } return issueops.CheckBlockingHierarchyInTx(ctx, r.runner, dep, nil) @@ -841,6 +847,18 @@ func (r *dependencySQLRepositoryImpl) CycleThroughEdges(ctx context.Context, edg return issueops.CycleThroughEdgesInGraph(graph, edges), nil } +// WispSourceIDs classifies a batch of ids by plane in one scoped query. It is +// the proxied twin of the in-tx probe the store-backed dependency editor runs, +// and shares its implementation so the two answer the same question — down to +// treating a missing wisps table as "no wisps" rather than an error. +func (r *dependencySQLRepositoryImpl) WispSourceIDs(ctx context.Context, ids []string) (map[string]struct{}, error) { + set, err := issueops.WispIDSetInTx(ctx, r.runner, ids) + if err != nil { + return nil, fmt.Errorf("db: DependencySQLRepository.WispSourceIDs: %w", err) + } + return set, nil +} + func (r *dependencySQLRepositoryImpl) GetDependencyRecordsForIssues(ctx context.Context, issueIDs []string) (map[string][]*types.Dependency, error) { if len(issueIDs) == 0 { return map[string][]*types.Dependency{}, nil diff --git a/internal/storage/domain/db/dependency_test.go b/internal/storage/domain/db/dependency_test.go index c659602ea..ad9cabd7d 100644 --- a/internal/storage/domain/db/dependency_test.go +++ b/internal/storage/domain/db/dependency_test.go @@ -1,6 +1,8 @@ package db import ( + "database/sql" + "github.com/steveyegge/beads/internal/storage/depid" "github.com/steveyegge/beads/internal/storage/domain" "github.com/steveyegge/beads/internal/types" @@ -16,6 +18,7 @@ func (s *testSuite) TestDependencySQLRepository() { s.Run("ParentChildTouchesCoordinationOnlyForNewEdge", s.depInsertParentChildTouchesCoordinationOnlyForNewEdge) s.Run("DifferentTypeIsRejected", s.depInsertConflictingType) s.Run("MissingTargetIssueFailsFK", s.depInsertFKViolation) + s.Run("ForeignRepoTargetGoesToExternalColumn", s.depInsertForeignRepoTarget) s.Run("ThreadIDPersists", s.depInsertThreadID) s.Run("EmitsDependencyAddedEventWhenEmitEventSet", s.depInsertEmitsAddedEvent) s.Run("RecordsNoEventWithoutEmitEvent", s.depInsertWithoutEmitEventRecordsNoEvent) @@ -201,6 +204,26 @@ func (s *testSuite) depInsertFKViolation() { s.Require().Error(err, "missing target should fail fk_dep_issue_target") } +// depInsertForeignRepoTarget is the other half of depInsertFKViolation: a target +// this database is not expected to hold is not a missing local issue. An id whose +// prefix names another repository is classified external, like an "external:" +// reference, and lands in depends_on_external — the one target column with no +// foreign key — so fk_dep_issue_target never sees it (bd-ocrn7). +func (s *testSuite) depInsertForeignRepoTarget() { + s.seedIssueRow("bd-dep-foreign-src") + const target = "otherrig-9001" + s.Require().NoError(s.depRepo().Insert(s.Ctx(), + newDep("bd-dep-foreign-src", target, types.DepBlocks), "tester", domain.DepInsertOpts{})) + + var external, issueTarget, wispTarget sql.NullString + s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(), + "SELECT depends_on_external, depends_on_issue_id, depends_on_wisp_id FROM dependencies WHERE issue_id = ?", + "bd-dep-foreign-src").Scan(&external, &issueTarget, &wispTarget)) + s.Equal(target, external.String, "foreign-repo target belongs in depends_on_external") + s.Empty(issueTarget.String, "foreign-repo target must not be written to depends_on_issue_id") + s.Empty(wispTarget.String) +} + func (s *testSuite) depInsertThreadID() { s.seedIssueRow("bd-dep-th-1") s.seedIssueRow("bd-dep-th-2") diff --git a/internal/storage/domain/db/dependency_usecase_extras_test.go b/internal/storage/domain/db/dependency_usecase_extras_test.go index 3ab5341ee..90ffe7f52 100644 --- a/internal/storage/domain/db/dependency_usecase_extras_test.go +++ b/internal/storage/domain/db/dependency_usecase_extras_test.go @@ -29,9 +29,9 @@ func (s *testSuite) TestDependencyUseCase_Extras() { s.Run("SkipPerEdgeStillRunsFinalCheck", s.ducAddBulkFinalCycleCheck) s.Run("SkipPerEdgeAcceptsAcyclicBulk", s.ducAddBulkSkipPerEdgeAcyclic) s.Run("NonBlockingEdgesSkipCycleChecks", s.ducAddBulkNonBlockingNoCheck) - }) - s.Run("AddWispDependencies", func() { - s.Run("RoutesToWispDepsTable", s.ducAddBulkWispRoutes) + s.Run("WispSourceRoutesToWispDepsTable", s.ducAddBulkWispRoutes) + s.Run("MixedBatchLandsEachEdgeInItsSourcePlane", s.ducAddBulkSourceRoutesMixedBatch) + s.Run("RefusesCrossPlaneCycle", s.ducAddBulkSourceRoutesRefusesCrossPlaneCycle) }) } @@ -329,8 +329,11 @@ func (s *testSuite) ducAddBulkSelfEdge() { s.Equal(0, count, "self-edge must not have been inserted") } -// ---- AddWispDependencies ---- +// ---- AddDependencies: source routing ---- +// ducAddBulkWispRoutes pins the all-wisp batch: a source that lives in the wisp +// plane gets its edge written to wisp_dependencies and nothing written to the +// issues plane. func (s *testSuite) ducAddBulkWispRoutes() { s.seedWispRow("bd-duc-bw-src") s.seedIssueRow("bd-duc-bw-tgt") @@ -338,7 +341,7 @@ func (s *testSuite) ducAddBulkWispRoutes() { deps := []*types.Dependency{ newDep("bd-duc-bw-src", "bd-duc-bw-tgt", types.DepBlocks), } - res, err := s.depUseCase().AddWispDependencies(s.Ctx(), deps, "tester", domain.BulkAddDepsOpts{}) + res, err := s.depUseCase().AddDependencies(s.Ctx(), deps, "tester", domain.BulkAddDepsOpts{}) s.Require().NoError(err) s.Require().Len(res.Added, 1) @@ -350,3 +353,55 @@ func (s *testSuite) ducAddBulkWispRoutes() { "SELECT COUNT(*) FROM dependencies WHERE issue_id = ?", "bd-duc-bw-src").Scan(&permCount)) s.Equal(0, permCount, "wisp-routed bulk add must not touch the issues dep table") } + +// ducAddBulkSourceRoutesMixedBatch pins the mixed-plane batch at the layer +// that decides the plane: one call, two write paths, each edge in the table +// its own source lives in. +func (s *testSuite) ducAddBulkSourceRoutesMixedBatch() { + s.seedWispRow("bd-duc-sr-wisp") + s.seedIssueRow("bd-duc-sr-issue") + s.seedIssueRow("bd-duc-sr-tgt") + + res, err := s.depUseCase().AddDependencies(s.Ctx(), []*types.Dependency{ + newDep("bd-duc-sr-wisp", "bd-duc-sr-tgt", types.DepBlocks), + newDep("bd-duc-sr-issue", "bd-duc-sr-tgt", types.DepBlocks), + }, "tester", domain.BulkAddDepsOpts{}) + s.Require().NoError(err) + s.Require().Len(res.Added, 2) + + s.Equal(1, s.countDepRows("wisp_dependencies", "bd-duc-sr-wisp")) + s.Equal(0, s.countDepRows("dependencies", "bd-duc-sr-wisp")) + s.Equal(1, s.countDepRows("dependencies", "bd-duc-sr-issue")) + s.Equal(0, s.countDepRows("wisp_dependencies", "bd-duc-sr-issue")) +} + +// ducAddBulkSourceRoutesRefusesCrossPlaneCycle pins bd-xe27 at this layer: the +// final gate walks both tables, so a loop that leaves the issues plane and +// returns through the wisp plane is still a loop. +// +// It asserts the REFUSAL only. Undoing the edge the gate refused is the +// caller's transaction's job, and this suite runs the use case on a bare +// runner; the rolled-back-across-both-planes half is pinned against the real +// unit of work (conformance.RunDependencyEditorMixedBatchRefusalRollsBackBothPlanes). +func (s *testSuite) ducAddBulkSourceRoutesRefusesCrossPlaneCycle() { + s.seedIssueRow("bd-duc-sx-issue") + s.seedWispRow("bd-duc-sx-wisp") + + _, err := s.depUseCase().AddDependencies(s.Ctx(), []*types.Dependency{ + newDep("bd-duc-sx-issue", "bd-duc-sx-wisp", types.DepBlocks), + }, "tester", domain.BulkAddDepsOpts{}) + s.Require().NoError(err) + + _, err = s.depUseCase().AddDependencies(s.Ctx(), []*types.Dependency{ + newDep("bd-duc-sx-wisp", "bd-duc-sx-issue", types.DepBlocks), + }, "tester", domain.BulkAddDepsOpts{SkipPerEdgeCycleCheck: true}) + s.Require().ErrorIs(err, domain.ErrDependencyCycle) +} + +//nolint:gosec // G201: table is one of two hardcoded test constants. +func (s *testSuite) countDepRows(table, sourceID string) int { + var count int + s.Require().NoError(s.Runner().QueryRowContext(s.Ctx(), + "SELECT COUNT(*) FROM "+table+" WHERE issue_id = ?", sourceID).Scan(&count)) + return count +} diff --git a/internal/storage/domain/dependency.go b/internal/storage/domain/dependency.go index 2f79b4368..ca50e9bda 100644 --- a/internal/storage/domain/dependency.go +++ b/internal/storage/domain/dependency.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "sort" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/storage/dberrors" @@ -72,10 +73,11 @@ type DepInsertOpts struct { CycleValidated bool // Set only after HasCycle or a whole-graph check on the same repository/UOW. // EmitEvent records a dependency_added / dependency_removed event on the // source's event table for a genuine edge add/remove. Only the explicit dep - // verbs (AddDependency/AddDependencies/RemoveDependency and their wisp twins) - // set it; create-with-deps and reparent call Insert/Delete directly with it - // unset so an implicit parent-child / --deps / waits-for edge produces no - // event. The embedded plumbing matches edge-for-edge: its structural paths + // verbs (AddDependency/RemoveDependency plus their wisp twins, and the bulk + // AddDependencies) set it; create-with-deps and reparent call Insert/Delete + // directly with it unset, so an implicit parent-child / --deps / waits-for + // edge produces no event. + // The embedded plumbing matches edge-for-edge: its structural paths // wire edges through the plain AddDependency/tx.AddDependency, whose // issueops.AddDependencyInTx EmitEvent gate is unset, while only the explicit // bd dep add / bd link / bd dep remove verbs pass EmitEvent. @@ -151,11 +153,21 @@ type DependencySQLRepository interface { CycleThroughEdges(ctx context.Context, edges [][2]string) (string, error) GetDependencyRecordsForIssues(ctx context.Context, issueIDs []string) (map[string][]*types.Dependency, error) GetWispDependencyRecordsForIDs(ctx context.Context, wispIDs []string) (map[string][]*types.Dependency, error) + + // WispSourceIDs returns the subset of ids that are currently wisps, in one + // scoped query rather than a probe per id. + WispSourceIDs(ctx context.Context, ids []string) (map[string]struct{}, error) } type DependencyUseCase interface { AddDependency(ctx context.Context, dep *types.Dependency, actor string) error RemoveDependency(ctx context.Context, issueID, dependsOnID, actor string) error + // RemoveDependencyBySource removes one edge from the plane its SOURCE + // lives in, the way AddDependencies writes one. There is deliberately no + // plane flag: `bd dep remove` names an id, not a table, and a removal + // cannot put an edge anywhere, so reading the plane is always safer than + // pinning it. + RemoveDependencyBySource(ctx context.Context, sourceID, dependsOnID, actor string) (bool, error) Reparent(ctx context.Context, childID, newParentID, actor string) error ListByIssueIDs(ctx context.Context, issueIDs []string, filter DepListFilter) (DepBulkResult, error) ListWithIssueMetadata(ctx context.Context, issueID string, filter DepListFilter) ([]*types.IssueWithDependencyMetadata, error) @@ -168,10 +180,16 @@ type DependencyUseCase interface { DetectCycles(ctx context.Context) ([][]*types.Issue, error) GetDependencyTree(ctx context.Context, rootID string, opts DepTreeOpts) ([]*types.TreeNode, error) + // AddDependencies asserts a batch of edges, each landing in the plane its + // own SOURCE lives in. There is deliberately no plane-pinned variant: + // `bd dep add` takes whatever ids the caller names and one request may + // legitimately mix them, so routing the whole batch by a flag would put an + // edge on a row the target table does not have. It is ONE pass, not one + // pass per plane: the parent-child-first ordering and the whole-graph + // cycle gate both have to see the request as a single graph. AddDependencies(ctx context.Context, deps []*types.Dependency, actor string, opts BulkAddDepsOpts) (BulkAddDepsResult, error) GetIssueDependencyRecords(ctx context.Context, issueIDs []string) (map[string][]*types.Dependency, error) - AddWispDependencies(ctx context.Context, deps []*types.Dependency, actor string, opts BulkAddDepsOpts) (BulkAddDepsResult, error) GetWispDependencyRecords(ctx context.Context, wispIDs []string) (map[string][]*types.Dependency, error) AddWispDependency(ctx context.Context, dep *types.Dependency, actor string) error @@ -264,6 +282,31 @@ func (u *dependencyUseCaseImpl) RemoveWispDependency(ctx context.Context, wispID return u.removeDep(ctx, wispID, dependsOnID, actor, true) } +// RemoveDependencyBySource removes one edge from the plane its SOURCE lives in +// and reports whether there was an edge to remove. +// +// It is the source-routed twin of AddDependencies, and exists for the same +// reason: `bd dep remove` takes whatever id the caller names, and pinning the +// removal to the durable table means failing to remove an edge whose source is +// a wisp while reporting that it was never there (bd-yby99.17). The delete IS +// the verdict, the way the store-backed body reads it off RemoveDependencyInTx +// rather than from a separate lookup. +func (u *dependencyUseCaseImpl) RemoveDependencyBySource(ctx context.Context, sourceID, dependsOnID, actor string) (bool, error) { + if sourceID == "" || dependsOnID == "" { + return false, fmt.Errorf("remove dep: sourceID and dependsOnID must not be empty") + } + wispSources, err := u.depRepo.WispSourceIDs(ctx, []string{sourceID}) + if err != nil { + return false, fmt.Errorf("remove dep: classify source: %w", err) + } + _, sourceIsWisp := wispSources[sourceID] + res, err := u.depRepo.Delete(ctx, sourceID, dependsOnID, actor, DepInsertOpts{UseWispsTable: sourceIsWisp, EmitEvent: true}) + if err != nil { + return false, fmt.Errorf("remove dep %s -> %s: %w", sourceID, dependsOnID, err) + } + return res.Found, nil +} + func (u *dependencyUseCaseImpl) removeDep(ctx context.Context, sourceID, dependsOnID, actor string, useWisp bool) error { if sourceID == "" || dependsOnID == "" { return fmt.Errorf("remove dep: sourceID and dependsOnID must not be empty") @@ -300,37 +343,71 @@ func (u *dependencyUseCaseImpl) reparent(ctx context.Context, childID, newParent return fmt.Errorf("reparent: list current parent: %w", err) } - var oldParentID string + // A child can carry MORE THAN ONE parent-child edge — Create accepts + // CreateRequest.ParentID and an explicit parent-child entry in + // Dependencies in the same request — so this is a set replacement, not a + // swap of one edge. Diffing the whole existing set against the target set + // is the same rule the store-backed backends apply in + // issueops.ApplyParentPatch; that body cannot be called from here because + // internal/storage/issueops imports this package (bd-yby99.26). + existing := map[string]struct{}{} for _, dep := range res.Outgoing[childID] { if dep.Type == types.DepParentChild { - oldParentID = dep.DependsOnID - break + existing[dep.DependsOnID] = struct{}{} } } - - if oldParentID == newParentID { + target := map[string]struct{}{} + if newParentID != "" { + target[newParentID] = struct{}{} + } + if sameStringSet(existing, target) { return nil } - if oldParentID != "" { + for _, oldParentID := range sortedSetDifference(existing, target) { if _, err := u.depRepo.Delete(ctx, childID, oldParentID, actor, opts); err != nil { return fmt.Errorf("reparent: remove old parent %s: %w", oldParentID, err) } } - if newParentID != "" { + for _, addParentID := range sortedSetDifference(target, existing) { dep := &types.Dependency{ IssueID: childID, - DependsOnID: newParentID, + DependsOnID: addParentID, Type: types.DepParentChild, } if err := u.depRepo.Insert(ctx, dep, actor, opts); err != nil { - return fmt.Errorf("reparent: add new parent %s: %w", newParentID, err) + return fmt.Errorf("reparent: add new parent %s: %w", addParentID, err) } } return nil } +func sameStringSet(left, right map[string]struct{}) bool { + if len(left) != len(right) { + return false + } + for value := range left { + if _, ok := right[value]; !ok { + return false + } + } + return true +} + +// sortedSetDifference returns the members of left absent from right, sorted so +// the writes it drives land in a deterministic order. +func sortedSetDifference(left, right map[string]struct{}) []string { + values := make([]string, 0, len(left)) + for value := range left { + if _, ok := right[value]; !ok { + values = append(values, value) + } + } + sort.Strings(values) + return values +} + func (u *dependencyUseCaseImpl) ListByIssueIDs(ctx context.Context, issueIDs []string, filter DepListFilter) (DepBulkResult, error) { return u.list(ctx, issueIDs, filter, false) } @@ -528,23 +605,14 @@ func (u *dependencyUseCaseImpl) GetDependencyTree(ctx context.Context, rootID st return out, nil } +// AddDependencies asserts every edge in one pass, writing each to the plane its +// own source lives in. The ordering and the final cycle gate deliberately do +// not partition by plane, because the hierarchy a blocking edge is checked +// against and the graph the gate walks both span the two tables. func (u *dependencyUseCaseImpl) AddDependencies(ctx context.Context, deps []*types.Dependency, actor string, opts BulkAddDepsOpts) (BulkAddDepsResult, error) { - return u.addBulk(ctx, deps, actor, opts, false) -} - -func (u *dependencyUseCaseImpl) AddWispDependencies(ctx context.Context, deps []*types.Dependency, actor string, opts BulkAddDepsOpts) (BulkAddDepsResult, error) { - return u.addBulk(ctx, deps, actor, opts, true) -} - -func (u *dependencyUseCaseImpl) addBulk(ctx context.Context, deps []*types.Dependency, actor string, opts BulkAddDepsOpts, useWisp bool) (BulkAddDepsResult, error) { if len(deps) == 0 { return BulkAddDepsResult{Added: []*types.Dependency{}}, nil } - // AddDependencies is the explicit `bd dep add` / `bd link` verb on the - // proxied server (cmd/bd/dep_proxied_server.go, link_proxied_server.go), so - // each genuine new edge records a dependency_added event — unlike - // create-with-deps, which calls depRepo.Insert directly without EmitEvent. - insertOpts := DepInsertOpts{UseWispsTable: useWisp, HierarchyValidated: true, CycleValidated: true, EmitEvent: true} // Validate the entire input shape before the first write. Multi-edge callers // run in a UOW, but this also avoids an avoidable partial prefix for direct // use-case consumers. @@ -566,6 +634,17 @@ func (u *dependencyUseCaseImpl) addBulk(ctx context.Context, deps []*types.Depen return BulkAddDepsResult{}, fmt.Errorf("%w: %s cannot depend on itself", ErrSelfDependency, dep.IssueID) } } + sources := make([]string, 0, len(deps)) + for _, dep := range deps { + sources = append(sources, dep.IssueID) + } + // One query for the batch, read before the first write. Nothing an edge + // write does moves a source between planes, so the answer stays true for + // the rest of the unit of work. + wispSources, err := u.depRepo.WispSourceIDs(ctx, sources) + if err != nil { + return BulkAddDepsResult{}, fmt.Errorf("add deps: classify sources: %w", err) + } // Parent-child edges must be visible before blocking edges in the same // request. The shared repository guard can then evaluate existing + planned // ancestry without widening #4034 into #4035's combined-graph cycle check. @@ -591,7 +670,19 @@ func (u *dependencyUseCaseImpl) addBulk(ctx context.Context, deps []*types.Depen return BulkAddDepsResult{}, cycleErrorf("add deps[%d]: adding %s -> %s would create a cycle", i, dep.IssueID, dep.DependsOnID) } } - if err := u.depRepo.Insert(ctx, dep, actor, insertOpts); err != nil { + // The explicit `bd dep add` / `bd link` verb on the proxied server + // (cmd/bd/dep_proxied_server.go, link_proxied_server.go) records a + // dependency_added event for each genuine new edge — unlike + // create-with-deps, which calls depRepo.Insert directly without + // EmitEvent. UseWispsTable routes both the edge and that event to + // the source's own pair of tables. + _, sourceIsWisp := wispSources[dep.IssueID] + if err := u.depRepo.Insert(ctx, dep, actor, DepInsertOpts{ + UseWispsTable: sourceIsWisp, + HierarchyValidated: true, + CycleValidated: true, + EmitEvent: true, + }); err != nil { var hierarchyConflict *DependencyHierarchyConflictError if errors.As(err, &hierarchyConflict) { return BulkAddDepsResult{}, err diff --git a/internal/storage/domain/issue.go b/internal/storage/domain/issue.go index fd842e239..ecab72345 100644 --- a/internal/storage/domain/issue.go +++ b/internal/storage/domain/issue.go @@ -10,6 +10,7 @@ import ( "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/storage/dberrors" "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" ) type InsertIssueOpts struct { @@ -552,23 +553,47 @@ func (u *issueUseCaseImpl) claim(ctx context.Context, id, actor string, useWisp if row.CurrentAssignee == actor && row.CurrentStatus == types.StatusInProgress { return ClaimResult{AlreadyClaimed: true, PriorAssignee: actor}, nil } + // The refusal carries the assignee and status the repository read back in + // THIS transaction, so a caller reports who won without parsing the + // message. The copy lives on the typed error, shared with the twin + // (issueops.ClaimIssueInTx) that used to restate it — that is what bd-at6rc + // asked for. The sentinel stays matchable through Unwrap, which the proxied + // batch exit code keys on. + // + // A pool-assigned issue only loses the CAS for a non-assignee reason + // (status changed underneath us), so it refuses on the status rather than + // with a misleading held-by refusal. + // Composed here rather than on the typed error, for the reason + // issueops.ClaimIssueInTx gives: ClaimConflictError passes its wrapped + // refusal through unchanged, so the fragments have to be in the wrapped + // error or beads.ParseClaimConflict recovers nothing. This is the + // domain-stack twin of that producer and must answer the same three ways + // (bd-at6rc). + refusal := fmt.Errorf("%w%s%s", storage.ErrNotClaimable, storage.NotClaimableStatusFragment, row.CurrentStatus) if row.CurrentAssignee != "" && row.CurrentAssignee != actor { - // A pool-assigned issue only loses the CAS for a non-assignee - // reason (status changed underneath us): report the status, not a - // misleading held-by refusal (mirrors issueops.ClaimIssueInTx). - if row.CurrentAssigneeIsPool { - return ClaimResult{}, fmt.Errorf("%w: status %s", storage.ErrNotClaimable, row.CurrentStatus) + switch { + // Pool aliases refuse on the STATUS, checked first so a pool never + // reaches the holder-steering copy below. + case row.CurrentAssigneeIsPool: + // refusal already names the status. + case row.CurrentStatus == types.StatusOpen: + // Never name a release command here (wy-yuclk): copy that names + // one gets pattern-matched by batch agents into an unclaim+claim + // steamroller of live claims. bd reclaim is safe to name because + // it only recovers claims whose lease has already expired. The + // parseable " by " tail is deliberately absent, so the + // holder is recovered from the typed field instead. + refusal = fmt.Errorf("%w: already assigned to %q — coordinate with the holder; if their claim is abandoned (crashed agent), lease expiry will surface it for bd reclaim", storage.ErrAlreadyClaimed, row.CurrentAssignee) + default: + refusal = fmt.Errorf("%w%s%s", storage.ErrAlreadyClaimed, storage.ClaimedByFragment, row.CurrentAssignee) } - if row.CurrentStatus == types.StatusOpen { - // Same guidance as issueops.ClaimIssueInTx's open-but-assigned - // refusal (bd-at6rc): steer toward the holder, never name an - // eviction command. Keep the %w wrap — the proxied batch exit - // code keys on errors.Is(err, ErrAlreadyClaimed). - return ClaimResult{}, fmt.Errorf("%w: already assigned to %q — coordinate with the holder; if their claim is abandoned (crashed agent), lease expiry will surface it for bd reclaim", storage.ErrAlreadyClaimed, row.CurrentAssignee) - } - return ClaimResult{}, fmt.Errorf("%w by %s", storage.ErrAlreadyClaimed, row.CurrentAssignee) } - return ClaimResult{}, fmt.Errorf("%w: status %s", storage.ErrNotClaimable, row.CurrentStatus) + return ClaimResult{}, &publicops.ClaimConflictError{ + IssueID: id, + Assignee: row.CurrentAssignee, + Status: row.CurrentStatus, + Err: refusal, + } } func (u *issueUseCaseImpl) ApplyUpdate(ctx context.Context, id string, spec UpdateSpec, actor string) (*types.Issue, error) { diff --git a/internal/storage/embeddeddolt/batch_closer.go b/internal/storage/embeddeddolt/batch_closer.go new file mode 100644 index 000000000..578f0b2d4 --- /dev/null +++ b/internal/storage/embeddeddolt/batch_closer.go @@ -0,0 +1,72 @@ +//go:build cgo + +package embeddeddolt + +import ( + "context" + "database/sql" + + "github.com/steveyegge/beads/internal/storage" + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/internal/workapi" + "github.com/steveyegge/beads/issueops" +) + +// BatchCloser returns the guarded close-many surface for this store. +func (s *EmbeddedDoltStore) BatchCloser() (issueops.BatchCloser, error) { + return NewBatchCloser(s) +} + +// NewBatchCloser returns a guarded batch closer backed by store. +func NewBatchCloser(store *EmbeddedDoltStore) (issueops.BatchCloser, error) { + if store == nil { + return nil, &storage.ErrUnsupported{Op: "NewBatchCloser", Backend: "nil"} + } + return &batchCloser{store: store}, nil +} + +type batchCloser struct{ store *EmbeddedDoltStore } + +// CloseBatch runs every close, and the optional claim, in ONE transaction with +// one commit. The message is composed inside the body because it names what +// LANDED, which is not knowable until the last item has been tried. +func (o *batchCloser) CloseBatch(ctx context.Context, request issueops.CloseBatchRequest) (issueops.CloseBatchResult, error) { + if err := storageissueops.ValidateCloseBatchRequest(request); err != nil { + return issueops.CloseBatchResult{}, err + } + claimFilter, err := batchClaimFilter(request.ClaimNext) + if err != nil { + return issueops.CloseBatchResult{}, err + } + + var result issueops.CloseBatchResult + err = o.store.runIssueOperationTxWithMessage(ctx, func(tx *sql.Tx) (storageissueops.ChangedTables, string, error) { + attempt, tables, err := storageissueops.ExecuteCloseBatch(ctx, tx, request, claimFilter) + if err != nil { + return nil, "", err + } + result = attempt + return tables, storageissueops.CloseBatchCommitMessage(attempt), nil + }) + if err != nil { + return issueops.CloseBatchResult{}, err + } + return result, nil +} + +// batchClaimFilter translates the request's optional claim into the filter the +// storage layer speaks, through the same builder Reader.Ready and +// ReadyClaimer.ClaimNext run. Nil in, nil out: no claim was asked for. +func batchClaimFilter(request *issueops.ReadyRequest) (*types.WorkFilter, error) { + if request == nil { + return nil, nil + } + filter, err := workapi.BuildReadyFilter(*request) + if err != nil { + return nil, err + } + return &filter, nil +} + +var _ issueops.BatchCloser = (*batchCloser)(nil) diff --git a/internal/storage/embeddeddolt/batch_closer_contract_test.go b/internal/storage/embeddeddolt/batch_closer_contract_test.go new file mode 100644 index 000000000..b498affcb --- /dev/null +++ b/internal/storage/embeddeddolt/batch_closer_contract_test.go @@ -0,0 +1,151 @@ +//go:build cgo + +package embeddeddolt_test + +import ( + "testing" + + "github.com/steveyegge/beads/backend/conformance" +) + +// The embedded store's wiring of the BatchCloser contract. It shares the +// validate/execute body with the server-backed store, so what this leg adds is +// the embedded transaction wrapper and the embedded engine, not a second +// independent reading of the contract. + +func TestEmbeddedBatchCloserOutcomesMirrorItemsIndexForIndex(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunBatchCloserOutcomesMirrorItemsIndexForIndex(t, ctx, newEmbeddedBatchCloserFixture(t, "bcmirror")) +} + +func TestEmbeddedBatchCloserPerItemRefusalIsAResultAndSurvivorsCommit(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunBatchCloserPerItemRefusalIsAResultAndSurvivorsCommit(t, ctx, newEmbeddedBatchCloserFixture(t, "bcrefusal")) +} + +func TestEmbeddedBatchCloserOutcomeSnapshotIsTheDocumentedShape(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunBatchCloserOutcomeSnapshotIsTheDocumentedShape(t, ctx, newEmbeddedBatchCloserFixture(t, "bcshape")) +} + +func TestEmbeddedBatchCloserRequestValidationReturnsZeroResultAndChangesNothing(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunBatchCloserRequestValidationReturnsZeroResultAndChangesNothing(t, ctx, newEmbeddedBatchCloserFixture(t, "bcvalid")) +} + +func TestEmbeddedBatchCloserClaimFilterValueFailureIsARequestValidationFailure(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunBatchCloserClaimFilterValueFailureIsARequestValidationFailure(t, ctx, newEmbeddedBatchCloserFixture(t, "bcbadsort")) +} + +func TestEmbeddedBatchCloserBackendFailureReturnsNoOutcomes(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunBatchCloserBackendFailureReturnsNoOutcomes(t, ctx, newEmbeddedBatchCloserFixture(t, "bcdeadctx")) +} + +func TestEmbeddedBatchCloserIdempotentRecloseIsAPerItemSuccess(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunBatchCloserIdempotentRecloseIsAPerItemSuccess(t, ctx, newEmbeddedBatchCloserFixture(t, "bcreclose")) +} + +func TestEmbeddedBatchCloserAllIdempotentBatchLandsNothing(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunBatchCloserAllIdempotentBatchLandsNothing(t, ctx, newEmbeddedBatchCloserFixture(t, "bcallidem")) +} + +func TestEmbeddedBatchCloserDuplicateItemRecloseAtItsOwnIndex(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunBatchCloserDuplicateItemRecloseAtItsOwnIndex(t, ctx, newEmbeddedBatchCloserFixture(t, "bcdup")) +} + +func TestEmbeddedBatchCloserWispItemClosesAndEarnsTheClaim(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunBatchCloserWispItemClosesAndEarnsTheClaim(t, ctx, newEmbeddedBatchCloserFixture(t, "bcwispclaim")) +} + +func TestEmbeddedBatchCloserDurableHistoryNeverNamesAWisp(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunBatchCloserDurableHistoryNeverNamesAWisp(t, ctx, newEmbeddedBatchCloserFixture(t, "bcwisphistory")) +} + +func TestEmbeddedBatchCloserForceBypassesOnlyClosePolicy(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunBatchCloserForceBypassesOnlyClosePolicy(t, ctx, newEmbeddedBatchCloserFixture(t, "bcforce")) +} + +func TestEmbeddedBatchCloserClaimNextHydratesWhenSomethingClosed(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunBatchCloserClaimNextHydratesWhenSomethingClosed(t, ctx, newEmbeddedBatchCloserFixture(t, "bcclaimhit")) +} + +func TestEmbeddedBatchCloserClaimNextIsNilWhenNothingClosed(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunBatchCloserClaimNextIsNilWhenNothingClosed(t, ctx, newEmbeddedBatchCloserFixture(t, "bcclaimnone")) +} + +func TestEmbeddedBatchCloserClaimNextIsNilWhenTheFrontIsEmpty(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunBatchCloserClaimNextIsNilWhenTheFrontIsEmpty(t, ctx, newEmbeddedBatchCloserFixture(t, "bcclaimempty")) +} + +func TestEmbeddedBatchCloserClaimNextSeesAnUnblockingFromItsOwnBatch(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunBatchCloserClaimNextSeesAnUnblockingFromItsOwnBatch(t, ctx, newEmbeddedBatchCloserFixture(t, "bcclaimunblock")) +} + +func TestEmbeddedBatchCloserRecordsOneHistoryEntryForWhatLanded(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunBatchCloserRecordsOneHistoryEntryForWhatLanded(t, ctx, newEmbeddedBatchCloserFixture(t, "bchistory")) +} + +func TestEmbeddedBatchCloserAllRefusedBatchRecordsNoHistory(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunBatchCloserAllRefusedBatchRecordsNoHistory(t, ctx, newEmbeddedBatchCloserFixture(t, "bcnohistory")) +} + +func TestEmbeddedBatchCloserDoesNotMutateTheCallerRequest(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunBatchCloserDoesNotMutateTheCallerRequest(t, ctx, newEmbeddedBatchCloserFixture(t, "bcsnapshot")) +} + +func newEmbeddedBatchCloserFixture(t *testing.T, prefix string) conformance.BatchCloserFixture { + t.Helper() + te := newTestEnv(t, prefix) + closer, err := te.store.BatchCloser() + if err != nil { + t.Fatalf("BatchCloser(): %v", err) + } + kit := newEmbeddedRoleFixtureKit(te, prefix) + return conformance.BatchCloserFixture{ + IssuePrefix: kit.IssuePrefix, + Closer: closer, + CreateIssue: kit.CreateIssue, + CreateWisp: kit.CreateWisp, + AddDependency: kit.AddDependency, + // Local, because the shared kit exposes no comment hook. Folding it in + // is an S0 follow-up (bd-kue5t); editing the frozen kit from this slice + // would collide with the five running beside it. + AddComment: te.store.AddComment, + QueryScalar: kit.QueryScalar, + CountHistory: kit.CountHistory, + } +} diff --git a/internal/storage/embeddeddolt/commenter.go b/internal/storage/embeddeddolt/commenter.go new file mode 100644 index 000000000..1f474db6f --- /dev/null +++ b/internal/storage/embeddeddolt/commenter.go @@ -0,0 +1,51 @@ +//go:build cgo + +package embeddeddolt + +import ( + "context" + "database/sql" + + "github.com/steveyegge/beads/internal/storage" + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/issueops" +) + +// Commenter returns the guarded add-comment surface for this store. +func (s *EmbeddedDoltStore) Commenter() (issueops.Commenter, error) { + return NewCommenter(s) +} + +// NewCommenter returns a guarded commenter backed by store. +func NewCommenter(store *EmbeddedDoltStore) (issueops.Commenter, error) { + if store == nil { + return nil, &storage.ErrUnsupported{Op: "NewCommenter", Backend: "nil"} + } + return &commenter{store: store}, nil +} + +type commenter struct{ store *EmbeddedDoltStore } + +// AddComment resolves the plane and appends the row in ONE transaction, so a +// comment cannot land on an issue that was promoted or demoted between the +// resolve and the insert. +func (c *commenter) AddComment(ctx context.Context, request issueops.AddCommentRequest) (issueops.AddCommentResult, error) { + if err := storageissueops.ValidateAddCommentRequest(request); err != nil { + return issueops.AddCommentResult{}, err + } + message := storageissueops.AddCommentCommitMessage(request.IssueID) + + var result issueops.AddCommentResult + err := c.store.runIssueOperationTx(ctx, message, func(tx *sql.Tx) (storageissueops.ChangedTables, error) { + var err error + var tables storageissueops.ChangedTables + result, tables, err = storageissueops.ExecuteAddComment(ctx, tx, request) + return tables, err + }) + if err != nil { + return issueops.AddCommentResult{}, err + } + return result, nil +} + +var _ issueops.Commenter = (*commenter)(nil) diff --git a/internal/storage/embeddeddolt/commenter_contract_test.go b/internal/storage/embeddeddolt/commenter_contract_test.go new file mode 100644 index 000000000..52a0bc99d --- /dev/null +++ b/internal/storage/embeddeddolt/commenter_contract_test.go @@ -0,0 +1,75 @@ +//go:build cgo + +package embeddeddolt_test + +import ( + "testing" + + "github.com/steveyegge/beads/backend/conformance" +) + +// TestCommenterContract runs the Commenter contract against the embedded +// store, which shares its validate/execute body with the server-backed store +// and differs in the transaction wrapper and the engine underneath. That is +// what this wiring catches; it is not an independent vote on the body. +// +// One environment for the whole suite: booting an embedded engine per case +// would dominate the runtime, the ids are prefix-namespaced, and the history +// deltas need the subtests sequential anyway. +func TestCommenterContract(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "cmt") + ctx := t.Context() + fixture := newEmbeddedCommenterFixture(t, te, "cmt") + + t.Run("StoresTextVerbatim", func(t *testing.T) { + conformance.RunCommenterStoresTextVerbatim(t, ctx, fixture) + }) + t.Run("ResultMirrorsTheStoredRow", func(t *testing.T) { + conformance.RunCommenterResultMirrorsTheStoredRow(t, ctx, fixture) + }) + t.Run("CommentOnAWispLandsOnTheWispThread", func(t *testing.T) { + conformance.RunCommenterCommentOnAWispLandsOnTheWispThread(t, ctx, fixture) + }) + t.Run("RefusesAnIDOnNeitherPlane", func(t *testing.T) { + conformance.RunCommenterRefusesAnIDOnNeitherPlane(t, ctx, fixture) + }) + t.Run("RefusesAnEmptyIssueID", func(t *testing.T) { + conformance.RunCommenterRefusesAnEmptyIssueID(t, ctx, fixture) + }) + t.Run("DoesNotResolvePrefixes", func(t *testing.T) { + conformance.RunCommenterDoesNotResolvePrefixes(t, ctx, fixture) + }) + t.Run("RecordsAtMostOneHistoryEntry", func(t *testing.T) { + conformance.RunCommenterRecordsAtMostOneHistoryEntry(t, ctx, fixture) + }) + t.Run("LeavesTheAnchorIssueUntouched", func(t *testing.T) { + conformance.RunCommenterLeavesTheAnchorIssueUntouched(t, ctx, fixture) + }) + t.Run("RefusesBlankText", func(t *testing.T) { + conformance.RunCommenterRefusesBlankText(t, ctx, fixture) + }) + t.Run("RefusesAnEmptyAuthor", func(t *testing.T) { + conformance.RunCommenterRefusesAnEmptyAuthor(t, ctx, fixture) + }) + t.Run("LeavesTheCallersRequestAlone", func(t *testing.T) { + conformance.RunCommenterLeavesTheCallersRequestAlone(t, ctx, fixture) + }) +} + +func newEmbeddedCommenterFixture(t *testing.T, te *testEnv, prefix string) conformance.CommenterFixture { + t.Helper() + commenter, err := te.store.Commenter() + if err != nil { + t.Fatalf("Commenter(): %v", err) + } + kit := newEmbeddedRoleFixtureKit(te, prefix) + return conformance.CommenterFixture{ + IssuePrefix: kit.IssuePrefix, + Commenter: commenter, + CreateIssue: kit.CreateIssue, + CreateWisp: kit.CreateWisp, + QueryScalar: kit.QueryScalar, + CountHistory: kit.CountHistory, + } +} diff --git a/internal/storage/embeddeddolt/dependency_editor.go b/internal/storage/embeddeddolt/dependency_editor.go new file mode 100644 index 000000000..073af83ba --- /dev/null +++ b/internal/storage/embeddeddolt/dependency_editor.go @@ -0,0 +1,73 @@ +//go:build cgo + +package embeddeddolt + +import ( + "context" + "database/sql" + + "github.com/steveyegge/beads/internal/storage" + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/issueops" +) + +// DependencyEditor returns the guarded dependency-edge surface for this store. +func (s *EmbeddedDoltStore) DependencyEditor() (issueops.DependencyEditor, error) { + return NewDependencyEditor(s) +} + +// NewDependencyEditor returns a guarded dependency editor backed by store. +func NewDependencyEditor(store *EmbeddedDoltStore) (issueops.DependencyEditor, error) { + if store == nil { + return nil, &storage.ErrUnsupported{Op: "NewDependencyEditor", Backend: "nil"} + } + return &dependencyEditor{store: store}, nil +} + +type dependencyEditor struct{ store *EmbeddedDoltStore } + +// AddDependencies asserts every edge in ONE transaction with one commit. The +// first refusal rolls the whole thing back, which is what makes the request +// all-or-nothing without any bookkeeping of its own. +func (e *dependencyEditor) AddDependencies(ctx context.Context, request issueops.AddDependenciesRequest) (issueops.AddDependenciesResult, error) { + if err := storageissueops.ValidateAddDependenciesRequest(request); err != nil { + return issueops.AddDependenciesResult{}, err + } + message := storageissueops.AddDependenciesCommitMessage(request) + + var result issueops.AddDependenciesResult + err := e.store.runIssueOperationTx(ctx, message, func(tx *sql.Tx) (storageissueops.ChangedTables, error) { + var err error + var tables storageissueops.ChangedTables + result, tables, err = storageissueops.ExecuteAddDependencies(ctx, tx, request) + return tables, err + }) + if err != nil { + return issueops.AddDependenciesResult{}, err + } + return result, nil +} + +// RemoveDependency removes one edge. The message is composed up front because +// a removal names the edge it was asked for; whether an entry is recorded at +// all is decided by the changed-table set, which is empty when no edge existed. +func (e *dependencyEditor) RemoveDependency(ctx context.Context, request issueops.RemoveDependencyRequest) (issueops.RemoveDependencyResult, error) { + if err := storageissueops.ValidateRemoveDependencyRequest(request); err != nil { + return issueops.RemoveDependencyResult{}, err + } + message := storageissueops.RemoveDependencyCommitMessage(request.IssueID, request.DependsOnID) + + var result issueops.RemoveDependencyResult + err := e.store.runIssueOperationTx(ctx, message, func(tx *sql.Tx) (storageissueops.ChangedTables, error) { + var err error + var tables storageissueops.ChangedTables + result, tables, err = storageissueops.ExecuteRemoveDependency(ctx, tx, request) + return tables, err + }) + if err != nil { + return issueops.RemoveDependencyResult{}, err + } + return result, nil +} + +var _ issueops.DependencyEditor = (*dependencyEditor)(nil) diff --git a/internal/storage/embeddeddolt/dependency_editor_contract_test.go b/internal/storage/embeddeddolt/dependency_editor_contract_test.go new file mode 100644 index 000000000..936933e1f --- /dev/null +++ b/internal/storage/embeddeddolt/dependency_editor_contract_test.go @@ -0,0 +1,193 @@ +//go:build cgo + +package embeddeddolt_test + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/backend/conformance" +) + +func TestEmbeddedDependencyEditorRoutesWispSourcedEdgeToTheWispPlane(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunDependencyEditorRoutesWispSourcedEdgeToTheWispPlane(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "wroute")) +} + +func TestEmbeddedDependencyEditorMixedBatchWritesBothPlanes(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunDependencyEditorMixedBatchWritesBothPlanes(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "wmixed")) +} + +func TestEmbeddedDependencyEditorMixedBatchRefusalRollsBackBothPlanes(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunDependencyEditorMixedBatchRefusalRollsBackBothPlanes(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "wrollback")) +} + +func TestEmbeddedDependencyEditorRefusesCrossPlaneCycle(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunDependencyEditorRefusesCrossPlaneCycle(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "wcycle")) +} + +func TestEmbeddedDependencyEditorAddedEchoesTheRequestOrder(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunDependencyEditorAddedEchoesTheRequestOrder(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "echo")) +} + +func TestEmbeddedDependencyEditorSameTypeReAddIsIdempotent(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunDependencyEditorSameTypeReAddIsIdempotent(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "idem")) +} + +func TestEmbeddedDependencyEditorRepeatsWithinOneRequestCollapse(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunDependencyEditorRepeatsWithinOneRequestCollapse(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "repeat")) +} + +func TestEmbeddedDependencyEditorAttributesItsEventsToTheActor(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunDependencyEditorAttributesItsEventsToTheActor(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "depactor")) +} + +func TestEmbeddedDependencyEditorRetypeRefusalLeavesTheOriginalEdge(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunDependencyEditorRetypeRefusalLeavesTheOriginalEdge(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "retype")) +} + +func TestEmbeddedDependencyEditorRefusalWritesNothing(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunDependencyEditorRefusalWritesNothing(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "refuse")) +} + +func TestEmbeddedDependencyEditorRemoveIsIdempotent(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunDependencyEditorRemoveIsIdempotent(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "rm")) +} + +func TestEmbeddedDependencyEditorAppliesParentChildBeforeBlockingEdges(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunDependencyEditorAppliesParentChildBeforeBlockingEdges(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "pcfirst")) +} + +func TestEmbeddedDependencyEditorAcceptsAnExternalTarget(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunDependencyEditorAcceptsAnExternalTarget(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "ext")) +} + +func TestEmbeddedDependencyEditorAcceptsAForeignRepoTarget(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunDependencyEditorAcceptsAForeignRepoTarget(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "foreign")) +} + +func TestEmbeddedDependencyEditorRefusesBlockingEdgeAcrossItsOwnHierarchy(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunDependencyEditorRefusesBlockingEdgeAcrossItsOwnHierarchy(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "hier")) +} + +func TestEmbeddedDependencyEditorRefusesSelfDependencyWithTheProbeSkipped(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunDependencyEditorRefusesSelfDependencyWithTheProbeSkipped(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "self")) +} + +func TestEmbeddedDependencyEditorRecordsOneHistoryEntryPerLandedRequest(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunDependencyEditorRecordsOneHistoryEntryPerLandedRequest(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "hist")) +} + +func TestEmbeddedDependencyEditorRecordsNoHistoryForAnAllEphemeralRequest(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunDependencyEditorRecordsNoHistoryForAnAllEphemeralRequest(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "ephhist")) +} + +func TestEmbeddedDependencyEditorSnapshotsTheRequest(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunDependencyEditorSnapshotsTheRequest(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "snap")) +} + +func TestEmbeddedDependencyEditorValidationRefusalsWriteNothing(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunDependencyEditorValidationRefusalsWriteNothing(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "valid")) +} + +func TestEmbeddedDependencyEditorRoutesWispSourcedRemovalToTheWispPlane(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunDependencyEditorRoutesWispSourcedRemovalToTheWispPlane(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "wrm")) +} + +func TestEmbeddedDependencyEditorRefusesAGhostSource(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunDependencyEditorRefusesAGhostSource(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "ghostsrc")) +} + +func TestEmbeddedDependencyEditorRefusesAMissingLocalTarget(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunDependencyEditorRefusesAMissingLocalTarget(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "notgt")) +} + +func TestEmbeddedDependencyEditorAcceptsATypeOutsideTheConstants(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunDependencyEditorAcceptsATypeOutsideTheConstants(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "opentype")) +} + +func TestEmbeddedDependencyEditorRemovesOnlyTheNamedEdge(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunDependencyEditorRemovesOnlyTheNamedEdge(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "rmnamed")) +} + +func TestEmbeddedDependencyEditorSkipPerEdgeCycleCheckDropsOnlyTheProbe(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunDependencyEditorSkipPerEdgeCycleCheckDropsOnlyTheProbe(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "skipok")) +} + +func TestEmbeddedDependencyEditorRecordsOneHistoryEntryForAMixedPlaneRequest(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunDependencyEditorRecordsOneHistoryEntryForAMixedPlaneRequest(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "mixhist")) +} + +// newEmbeddedDependencyEditorFixture composes the backend's role fixture kit +// with the accessor under test. Every hook but the accessor comes from the kit, +// so the seeding and scalar-query plumbing stays identical to the other roles'. +func newEmbeddedDependencyEditorFixture(t *testing.T, ctx context.Context, prefix string) conformance.DependencyEditorFixture { + t.Helper() + te := newTestEnv(t, prefix) + editor, err := te.store.DependencyEditor() + if err != nil { + t.Fatalf("DependencyEditor(): %v", err) + } + kit := newEmbeddedRoleFixtureKit(te, prefix) + return conformance.DependencyEditorFixture{ + IssuePrefix: kit.IssuePrefix, + Editor: editor, + CreateIssue: kit.CreateIssue, + CreateWisp: kit.CreateWisp, + QueryScalar: kit.QueryScalar, + CountHistory: kit.CountHistory, + } +} diff --git a/internal/storage/embeddeddolt/issue_operations.go b/internal/storage/embeddeddolt/issue_operations.go index 3050892cc..7b51fa4ea 100644 --- a/internal/storage/embeddeddolt/issue_operations.go +++ b/internal/storage/embeddeddolt/issue_operations.go @@ -51,7 +51,7 @@ func (o *issueOperations) Update(ctx context.Context, request issueops.UpdateReq var result issueops.UpdateResult // Same ID-bearing commit message as the server-backed store, so `bd dolt // log` reads the same on both backends. - err := o.store.runIssueOperationTx(ctx, updateCommitMessage(snapshot.IssueID), func(tx *sql.Tx) (storageissueops.ChangedTables, error) { + err := o.store.runIssueOperationTx(ctx, storageissueops.HistoryEntry(snapshot.Provenance, updateCommitMessage(snapshot.IssueID)), func(tx *sql.Tx) (storageissueops.ChangedTables, error) { var err error var tables storageissueops.ChangedTables result, tables, err = storageissueops.ExecuteUpdate(ctx, tx, snapshot) @@ -75,7 +75,7 @@ func (o *issueOperations) Close(ctx context.Context, request issueops.CloseReque func (o *issueOperations) Reopen(ctx context.Context, request issueops.ReopenRequest) (issueops.ReopenResult, error) { snapshot := storageissueops.CloneReopenRequest(request) var result issueops.ReopenResult - err := o.store.runIssueOperationTx(ctx, "bd: reopen issue", func(tx *sql.Tx) (storageissueops.ChangedTables, error) { + err := o.store.runIssueOperationTx(ctx, storageissueops.HistoryEntry(snapshot.Provenance, "bd: reopen issue"), func(tx *sql.Tx) (storageissueops.ChangedTables, error) { var err error var tables storageissueops.ChangedTables result, tables, err = storageissueops.ExecuteReopen(ctx, tx, snapshot) diff --git a/internal/storage/embeddeddolt/issue_operations_contract_test.go b/internal/storage/embeddeddolt/issue_operations_contract_test.go index 5dc10ba16..e905d4205 100644 --- a/internal/storage/embeddeddolt/issue_operations_contract_test.go +++ b/internal/storage/embeddeddolt/issue_operations_contract_test.go @@ -52,6 +52,83 @@ func TestEmbeddedIssueOperationsUpdateClosedFieldsMatchClose(t *testing.T) { conformance.RunIssueOperationsUpdateClosedFieldsMatchClose(t, ctx, newEmbeddedIssueOperationsFixture(t, ctx, te, "closedfields")) } +func TestEmbeddedIssueOperationsUpdateClaimConflictCarriesTheLosingState(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "claimconflict") + ctx := t.Context() + conformance.RunIssueOperationsUpdateClaimConflictCarriesTheLosingState(t, ctx, newEmbeddedIssueOperationsFixture(t, ctx, te, "claimconflict")) +} + +func TestEmbeddedIssueOperationsUpdateClaimHonorsConfiguredActiveStatuses(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "customclaim") + ctx := t.Context() + conformance.RunIssueOperationsUpdateClaimHonorsConfiguredActiveStatuses(t, ctx, newEmbeddedIssueOperationsFixture(t, ctx, te, "customclaim")) +} + +func TestEmbeddedIssueOperationsUpdateIssuePlaneOnlyRefusesWisps(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "planeonly") + ctx := t.Context() + conformance.RunIssueOperationsUpdateIssuePlaneOnlyRefusesWisps(t, ctx, newEmbeddedIssueOperationsFixture(t, ctx, te, "planeonly")) +} + +func TestEmbeddedIssueOperationsUpdateLabelPatchOrdering(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "labelpatch") + ctx := t.Context() + conformance.RunIssueOperationsUpdateLabelPatchOrdering(t, ctx, newEmbeddedIssueOperationsFixture(t, ctx, te, "labelpatch")) +} + +func TestEmbeddedIssueOperationsUpdateLabelPatchValueRules(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "labelvalues") + ctx := t.Context() + conformance.RunIssueOperationsUpdateLabelPatchValueRules(t, ctx, newEmbeddedIssueOperationsFixture(t, ctx, te, "labelvalues")) +} + +func TestEmbeddedIssueOperationsUpdateParentIDReplacesTheParentEdge(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "reparent") + ctx := t.Context() + conformance.RunIssueOperationsUpdateParentIDReplacesTheParentEdge(t, ctx, newEmbeddedIssueOperationsFixture(t, ctx, te, "reparent")) +} + +func TestEmbeddedIssueOperationsUpdateParentIDReplacesEveryParent(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "multiparent") + ctx := t.Context() + conformance.RunIssueOperationsUpdateParentIDReplacesEveryParent(t, ctx, newEmbeddedIssueOperationsFixture(t, ctx, te, "multiparent")) +} + +func TestEmbeddedIssueOperationsUpdateMetadataReplaceClearsAndValidates(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "metareplace") + ctx := t.Context() + conformance.RunIssueOperationsUpdateMetadataReplaceClearsAndValidates(t, ctx, newEmbeddedIssueOperationsFixture(t, ctx, te, "metareplace")) +} + +func TestEmbeddedIssueOperationsRequestValuesAreNotMutated(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "detach") + ctx := t.Context() + conformance.RunIssueOperationsRequestValuesAreNotMutated(t, ctx, newEmbeddedIssueOperationsFixture(t, ctx, te, "detach")) +} + +func TestEmbeddedIssueOperationsUpdateProvenanceLabelsHistory(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "provenance") + ctx := t.Context() + conformance.RunIssueOperationsUpdateProvenanceLabelsHistory(t, ctx, newEmbeddedIssueOperationsFixture(t, ctx, te, "provenance")) +} + +func TestEmbeddedIssueOperationsUpdatePersistentPreservesUnversionedClass(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "unversioned") + ctx := t.Context() + conformance.RunIssueOperationsUpdatePersistentPreservesUnversionedClass(t, ctx, newEmbeddedIssueOperationsFixture(t, ctx, te, "unversioned")) +} + func newEmbeddedIssueOperationsFixture(t *testing.T, ctx context.Context, te *testEnv, prefix string) conformance.IssueOperationsStagingFixture { t.Helper() operations, err := embeddeddolt.NewIssueOperations(te.store) diff --git a/internal/storage/embeddeddolt/issue_operations_tx.go b/internal/storage/embeddeddolt/issue_operations_tx.go index 9134d46a6..7865b9b4a 100644 --- a/internal/storage/embeddeddolt/issue_operations_tx.go +++ b/internal/storage/embeddeddolt/issue_operations_tx.go @@ -10,20 +10,31 @@ import ( ) func (s *EmbeddedDoltStore) runIssueOperationTx(ctx context.Context, commitMsg string, fn func(*sql.Tx) (storageissueops.ChangedTables, error)) error { - // An empty message is runTransaction's existing "write, but do not version - // commit" signal — the same one CLI batch mode already uses for its - // RunInTransaction writes. - if storageissueops.VersionCommitDeferred(ctx) { - commitMsg = "" - } - return s.runTransaction(ctx, commitMsg, func(tx *embeddedTransaction) error { - tables, err := fn(tx.tx) + return s.runIssueOperationTxWithMessage(ctx, func(tx *sql.Tx) (storageissueops.ChangedTables, string, error) { + tables, err := fn(tx) + return tables, commitMsg, err + }) +} + +// runIssueOperationTxWithMessage is runIssueOperationTx for an operation whose +// commit message is only known once the body has run — a ready claim names the +// id it won. Deferral still wins over whatever the body composes: an empty +// message is runTransaction's existing "write, but do not version commit" +// signal, the same one CLI batch mode already uses for its RunInTransaction +// writes. +func (s *EmbeddedDoltStore) runIssueOperationTxWithMessage(ctx context.Context, fn func(*sql.Tx) (storageissueops.ChangedTables, string, error)) error { + deferred := storageissueops.VersionCommitDeferred(ctx) + return s.runTransactionWithMessage(ctx, func(tx *embeddedTransaction) (string, error) { + tables, commitMsg, err := fn(tx.tx) if err != nil { - return err + return "", err } for table := range tables { tx.dirty.MarkDirty(table) } - return nil + if deferred { + return "", nil + } + return commitMsg, nil }) } diff --git a/internal/storage/embeddeddolt/lifecycle_close_reopen_contract_test.go b/internal/storage/embeddeddolt/lifecycle_close_reopen_contract_test.go new file mode 100644 index 000000000..c941f7721 --- /dev/null +++ b/internal/storage/embeddeddolt/lifecycle_close_reopen_contract_test.go @@ -0,0 +1,73 @@ +//go:build cgo + +package embeddeddolt_test + +import ( + "testing" + + "github.com/steveyegge/beads/backend/conformance" +) + +// TestLifecycleCloseReopenContract runs the Close/Reopen half of the Lifecycle +// contract against the embedded store, which shares its validate/execute body +// with the server-backed store and differs in the transaction wrapper and the +// engine underneath. That is what this wiring catches; it is not an independent +// vote on the body. +// +// One environment for the whole suite: booting an embedded engine per case +// would dominate the runtime, the ids are prefix-namespaced, and the event +// deltas need the subtests sequential anyway. +func TestLifecycleCloseReopenContract(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "lcr") + ctx := t.Context() + fixture := newEmbeddedLifecycleCloseReopenFixture(t, te, "lcr") + + t.Run("CloseRefusalsCarryTheirTypesAndWriteNothing", func(t *testing.T) { + conformance.RunLifecycleCloseRefusalsCarryTheirTypesAndWriteNothing(t, ctx, fixture) + }) + t.Run("CloseIsIdempotentAndKeepsTheFirstClose", func(t *testing.T) { + conformance.RunLifecycleCloseIsIdempotentAndKeepsTheFirstClose(t, ctx, fixture) + }) + t.Run("ReopenLeavesNonDoneStatusesUnchanged", func(t *testing.T) { + conformance.RunLifecycleReopenLeavesNonDoneStatusesUnchanged(t, ctx, fixture) + }) + t.Run("CloseAndReopenSpanTheConfiguredDoneCategory", func(t *testing.T) { + conformance.RunLifecycleCloseAndReopenSpanTheConfiguredDoneCategory(t, ctx, fixture) + }) + t.Run("ExpectedVersionIsCheckedBeforeTheNoOps", func(t *testing.T) { + conformance.RunLifecycleExpectedVersionIsCheckedBeforeTheNoOps(t, ctx, fixture) + }) + t.Run("ReopenRecordsItsReason", func(t *testing.T) { + conformance.RunLifecycleReopenRecordsItsReason(t, ctx, fixture) + }) + t.Run("ReopenProvenanceLabelsHistory", func(t *testing.T) { + conformance.RunLifecycleReopenProvenanceLabelsHistory(t, ctx, fixture) + }) + t.Run("ResultsAreHydratedPostStateSnapshots", func(t *testing.T) { + conformance.RunLifecycleResultsAreHydratedPostStateSnapshots(t, ctx, fixture) + }) + t.Run("CloseAndReopenRequireActorAndIssueID", func(t *testing.T) { + conformance.RunLifecycleCloseAndReopenRequireActorAndIssueID(t, ctx, fixture) + }) +} + +func newEmbeddedLifecycleCloseReopenFixture(t *testing.T, te *testEnv, prefix string) conformance.LifecycleCloseReopenFixture { + t.Helper() + // Through the capability accessor, not NewIssueOperations: a store that + // stopped offering the role is the regression, and a constructor call would + // hide it. + lifecycle, err := te.store.IssueLifecycle() + if err != nil { + t.Fatalf("IssueLifecycle(): %v", err) + } + kit := newEmbeddedRoleFixtureKit(te, prefix) + return conformance.LifecycleCloseReopenFixture{ + IssuePrefix: kit.IssuePrefix, + Lifecycle: lifecycle, + CreateIssue: kit.CreateIssue, + AddDependency: kit.AddDependency, + SetConfig: kit.SetConfig, + QueryScalar: kit.QueryScalar, + } +} diff --git a/internal/storage/embeddeddolt/reader_contract_test.go b/internal/storage/embeddeddolt/reader_contract_test.go new file mode 100644 index 000000000..ecdcb3af0 --- /dev/null +++ b/internal/storage/embeddeddolt/reader_contract_test.go @@ -0,0 +1,168 @@ +//go:build cgo + +package embeddeddolt_test + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/backend/conformance" +) + +// The Reader contract, wired at the embedded store. This accessor returns the +// same workapi/storereader body the server-backed store's does, so what this +// wiring buys is the ENGINE and the connection wrapper underneath it, not a +// second opinion on the body. It is still worth running: engine-level +// disagreement is the class the embedded wirings have caught before. + +func TestEmbeddedReaderReadyDefaultTypeExclusionsYieldToAnExplicitType(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReaderReadyDefaultTypeExclusionsYieldToAnExplicitType(t, ctx, newEmbeddedReaderFixture(t, "rdr")) +} + +func TestEmbeddedReaderReadyDeferredAndEphemeralGates(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReaderReadyDeferredAndEphemeralGates(t, ctx, newEmbeddedReaderFixture(t, "rdr")) +} + +func TestEmbeddedReaderReadyLimitBoundary(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReaderReadyLimitBoundary(t, ctx, newEmbeddedReaderFixture(t, "rdr")) +} + +func TestEmbeddedReaderOffsetIsHonoredOrRefused(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReaderOffsetIsHonoredOrRefused(t, ctx, newEmbeddedReaderFixture(t, "rdr")) +} + +func TestEmbeddedReaderReadySortPoliciesOrderTheSameRows(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReaderReadySortPoliciesOrderTheSameRows(t, ctx, newEmbeddedReaderFixture(t, "rdr")) +} + +func TestEmbeddedReaderListDefaultExclusionsAndTheirOverrides(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReaderListDefaultExclusionsAndTheirOverrides(t, ctx, newEmbeddedReaderFixture(t, "rdr")) +} + +func TestEmbeddedReaderListRejectsATypeOutsideTheWorkspaceVocabulary(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReaderListRejectsATypeOutsideTheWorkspaceVocabulary(t, ctx, newEmbeddedReaderFixture(t, "rdr")) +} + +func TestEmbeddedReaderListNaturalNumericIDSortTrimsAfterTheFetch(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReaderListNaturalNumericIDSortTrimsAfterTheFetch(t, ctx, newEmbeddedReaderFixture(t, "rdr")) +} + +func TestEmbeddedReaderListLimitBoundaryUnderASortTheDatabaseCanExpress(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReaderListLimitBoundaryUnderASortTheDatabaseCanExpress(t, ctx, newEmbeddedReaderFixture(t, "rdr")) +} + +func TestEmbeddedReaderReadySetOwnsItsStatusPinnedAndTemplateDecisions(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReaderReadySetOwnsItsStatusPinnedAndTemplateDecisions(t, ctx, newEmbeddedReaderFixture(t, "rdr")) +} + +func TestEmbeddedReaderListReadyFlagCarriesTheAssigneeAndPriorityFilters(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReaderListReadyFlagCarriesTheAssigneeAndPriorityFilters(t, ctx, newEmbeddedReaderFixture(t, "rdr")) +} + +func TestEmbeddedReaderListStatusAcceptsACommaSeparatedORSet(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReaderListStatusAcceptsACommaSeparatedORSet(t, ctx, newEmbeddedReaderFixture(t, "rdr")) +} + +func TestEmbeddedReaderListKeysetPositionResumesTheCreatedDescIDAscOrder(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReaderListKeysetPositionResumesTheCreatedDescIDAscOrder(t, ctx, newEmbeddedReaderFixture(t, "rdr")) +} + +func TestEmbeddedReaderListReadyFlagAnswersTheBlockerAwareSet(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReaderListReadyFlagAnswersTheBlockerAwareSet(t, ctx, newEmbeddedReaderFixture(t, "rdr")) +} + +func TestEmbeddedReaderListReadyFlagRefusesAFilterItCannotCarry(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReaderListReadyFlagRefusesAFilterItCannotCarry(t, ctx, newEmbeddedReaderFixture(t, "rdr")) +} + +func TestEmbeddedReaderListEmptyPageIsWellFormed(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReaderListEmptyPageIsWellFormed(t, ctx, newEmbeddedReaderFixture(t, "rdr")) +} + +func TestEmbeddedReaderGetResolvesTheExactIDAcrossBothPlanes(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReaderGetResolvesTheExactIDAcrossBothPlanes(t, ctx, newEmbeddedReaderFixture(t, "rdr")) +} + +func TestEmbeddedReaderGetMissIsNotFoundAndBackendFailureDoesNotDecay(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReaderGetMissIsNotFoundAndBackendFailureDoesNotDecay(t, ctx, newEmbeddedReaderFixture(t, "rdr")) +} + +func TestEmbeddedReaderGetOptionalRowListsAreOffByDefault(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReaderGetOptionalRowListsAreOffByDefault(t, ctx, newEmbeddedReaderFixture(t, "rdr")) +} + +func TestEmbeddedReaderGetDetailShapeMatchesTheSeededIssue(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReaderGetDetailShapeMatchesTheSeededIssue(t, ctx, newEmbeddedReaderFixture(t, "rdr")) +} + +func TestEmbeddedReaderDoesNotMutateTheCallerRequest(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReaderDoesNotMutateTheCallerRequest(t, ctx, newEmbeddedReaderFixture(t, "rdr")) +} + +// newEmbeddedReaderFixture composes the shared role kit with the reader +// accessor. One environment per case: newTestEnv clones a pristine template +// into the test's own temp dir, which costs a fraction of a second once the +// template exists. +func newEmbeddedReaderFixture(t *testing.T, prefix string) conformance.ReaderFixture { + t.Helper() + te := newTestEnv(t, prefix) + reader, err := te.store.IssueReader() + if err != nil { + t.Fatalf("IssueReader(): %v", err) + } + kit := newEmbeddedRoleFixtureKit(te, prefix) + return conformance.ReaderFixture{ + IssuePrefix: kit.IssuePrefix, + Reader: reader, + CreateIssue: kit.CreateIssue, + CreateWisp: kit.CreateWisp, + AddDependency: kit.AddDependency, + // Not on the kit; see the same note in the server-backed wiring. + AddComment: func(ctx context.Context, issueID, author, text string) error { + _, err := te.store.AddIssueComment(ctx, issueID, author, text) + return err + }, + } +} diff --git a/internal/storage/embeddeddolt/ready_claimer.go b/internal/storage/embeddeddolt/ready_claimer.go new file mode 100644 index 000000000..135f51ea6 --- /dev/null +++ b/internal/storage/embeddeddolt/ready_claimer.go @@ -0,0 +1,63 @@ +//go:build cgo + +package embeddeddolt + +import ( + "context" + "database/sql" + + "github.com/steveyegge/beads/internal/storage" + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/internal/workapi" + "github.com/steveyegge/beads/issueops" +) + +// ReadyClaimer returns the guarded take-ready-work surface for this store. +func (s *EmbeddedDoltStore) ReadyClaimer() (issueops.ReadyClaimer, error) { + return NewReadyClaimer(s) +} + +// NewReadyClaimer returns a guarded ready claimer backed by store. +func NewReadyClaimer(store *EmbeddedDoltStore) (issueops.ReadyClaimer, error) { + if store == nil { + return nil, &storage.ErrUnsupported{Op: "NewReadyClaimer", Backend: "nil"} + } + return &readyClaimer{store: store}, nil +} + +type readyClaimer struct{ store *EmbeddedDoltStore } + +// ClaimNext runs selection, the compare-and-set and hydration in one +// transaction. There is no verify-after-write wrapper here, and that is not an +// omission: the embedded store is in-process, so the commit-phase ambiguity +// the server-backed store recovers from cannot arise. +func (c *readyClaimer) ClaimNext(ctx context.Context, request issueops.ClaimNextRequest) (issueops.ClaimNextResult, error) { + if err := storageissueops.ValidateClaimNextRequest(request); err != nil { + return issueops.ClaimNextResult{}, err + } + filter, err := workapi.BuildReadyFilter(request.Filter) + if err != nil { + return issueops.ClaimNextResult{}, err + } + + var result issueops.ClaimNextResult + err = c.store.runIssueOperationTxWithMessage(ctx, func(tx *sql.Tx) (storageissueops.ChangedTables, string, error) { + attempt, tables, err := storageissueops.ExecuteClaimNext(ctx, tx, request.Actor, filter) + if err != nil { + return nil, "", err + } + result = attempt + if attempt.Claimed == nil { + return tables, "", nil + } + // Same id-bearing commit message as the server-backed store, so `bd + // dolt log` reads the same on both backends. + return tables, storageissueops.ClaimNextCommitMessage(attempt.Claimed.ID), nil + }) + if err != nil { + return issueops.ClaimNextResult{}, err + } + return result, nil +} + +var _ issueops.ReadyClaimer = (*readyClaimer)(nil) diff --git a/internal/storage/embeddeddolt/ready_claimer_contract_test.go b/internal/storage/embeddeddolt/ready_claimer_contract_test.go new file mode 100644 index 000000000..f68b36452 --- /dev/null +++ b/internal/storage/embeddeddolt/ready_claimer_contract_test.go @@ -0,0 +1,98 @@ +//go:build cgo + +package embeddeddolt_test + +import ( + "testing" + + "github.com/steveyegge/beads/backend/conformance" +) + +func TestEmbeddedReadyClaimerRejectsLimitOffsetAndEmptyActor(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReadyClaimerRejectsLimitOffsetAndEmptyActor(t, ctx, newEmbeddedReadyClaimerFixture(t, "rcrej")) +} + +func TestEmbeddedReadyClaimerEmptyFrontIsNormal(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReadyClaimerEmptyFrontIsNormal(t, ctx, newEmbeddedReadyClaimerFixture(t, "rcempty")) +} + +func TestEmbeddedReadyClaimerClaimsTheFrontRowAndReturnsThePostClaimState(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReadyClaimerClaimsTheFrontRowAndReturnsThePostClaimState(t, ctx, newEmbeddedReadyClaimerFixture(t, "rcwin")) +} + +func TestEmbeddedReadyClaimerClaimsAnEphemeralRowTheFilterAdmits(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReadyClaimerClaimsAnEphemeralRowTheFilterAdmits(t, ctx, newEmbeddedReadyClaimerFixture(t, "rcwisp")) +} + +func TestEmbeddedReadyClaimerLeavesEphemeralRowsOutOfTheDefaultReadySet(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReadyClaimerLeavesEphemeralRowsOutOfTheDefaultReadySet(t, ctx, newEmbeddedReadyClaimerFixture(t, "rcdefault")) +} + +func TestEmbeddedReadyClaimerLeasesADurableWinButNotAnEphemeralOne(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReadyClaimerLeasesADurableWinButNotAnEphemeralOne(t, ctx, newEmbeddedReadyClaimerFixture(t, "rclease")) +} + +func TestEmbeddedReadyClaimerAnswersTheQuestionReaderReadyLists(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReadyClaimerAnswersTheQuestionReaderReadyLists(t, ctx, newEmbeddedReadyClaimerFixture(t, "rcagree")) +} + +func TestEmbeddedReadyClaimerSkipsIneligibleFrontRows(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReadyClaimerSkipsIneligibleFrontRows(t, ctx, newEmbeddedReadyClaimerFixture(t, "rcskip")) +} + +func TestEmbeddedReadyClaimerRecordsOneHistoryEntryForAWin(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReadyClaimerRecordsOneHistoryEntryForAWin(t, ctx, newEmbeddedReadyClaimerFixture(t, "rchist")) +} + +func TestEmbeddedReadyClaimerDoesNotMutateTheCallerRequest(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunReadyClaimerDoesNotMutateTheCallerRequest(t, ctx, newEmbeddedReadyClaimerFixture(t, "rcsnap")) +} + +// newEmbeddedReadyClaimerFixture composes the frozen role kit with this +// backend's two accessors. An environment per case is affordable here — each +// newTestEnv clones a pristine template rather than booting a server — which is +// why this wiring keeps one test function per case while the unit-of-work one +// cannot. +func newEmbeddedReadyClaimerFixture(t *testing.T, prefix string) conformance.ReadyClaimerFixture { + t.Helper() + te := newTestEnv(t, prefix) + claimer, err := te.store.ReadyClaimer() + if err != nil { + t.Fatalf("ReadyClaimer(): %v", err) + } + reader, err := te.store.IssueReader() + if err != nil { + t.Fatalf("IssueReader(): %v", err) + } + kit := newEmbeddedRoleFixtureKit(te, prefix) + return conformance.ReadyClaimerFixture{ + IssuePrefix: kit.IssuePrefix, + Claimer: claimer, + Reader: reader, + CreateIssue: kit.CreateIssue, + CreateWisp: kit.CreateWisp, + AddDependency: kit.AddDependency, + QueryScalar: kit.QueryScalar, + CountHistory: kit.CountHistory, + } +} diff --git a/internal/storage/embeddeddolt/relations.go b/internal/storage/embeddeddolt/relations.go new file mode 100644 index 000000000..44b89c987 --- /dev/null +++ b/internal/storage/embeddeddolt/relations.go @@ -0,0 +1,49 @@ +//go:build cgo + +package embeddeddolt + +import ( + "context" + "database/sql" + + "github.com/steveyegge/beads/internal/storage" + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" +) + +// IssueRelations returns the guarded neighbor-query surface for this store. +func (s *EmbeddedDoltStore) IssueRelations() (issueops.Relations, error) { + return NewIssueRelations(s) +} + +// NewIssueRelations returns guarded neighbor queries backed by store. +func NewIssueRelations(store *EmbeddedDoltStore) (issueops.Relations, error) { + if store == nil { + return nil, &storage.ErrUnsupported{Op: "NewIssueRelations", Backend: "nil"} + } + return &issueRelations{store: store}, nil +} + +type issueRelations struct{ store *EmbeddedDoltStore } + +// Related runs the anchor probe and the neighbor read on ONE connection, so +// an anchor cannot be reported missing by a probe that raced a create the +// neighbor read then saw. +func (r *issueRelations) Related(ctx context.Context, request issueops.RelatedRequest) ([]*issueops.RelatedIssue, error) { + if err := storageissueops.ValidateRelatedRequest(request); err != nil { + return nil, err + } + var items []*types.IssueWithDependencyMetadata + err := r.store.withConn(ctx, false, func(tx *sql.Tx) error { + var err error + items, err = storageissueops.ExecuteRelated(ctx, tx, request) + return err + }) + if err != nil { + return nil, err + } + return items, nil +} + +var _ issueops.Relations = (*issueRelations)(nil) diff --git a/internal/storage/embeddeddolt/relations_contract_test.go b/internal/storage/embeddeddolt/relations_contract_test.go new file mode 100644 index 000000000..27366f074 --- /dev/null +++ b/internal/storage/embeddeddolt/relations_contract_test.go @@ -0,0 +1,105 @@ +//go:build cgo + +package embeddeddolt_test + +import ( + "testing" + + "github.com/steveyegge/beads/backend/conformance" +) + +func TestEmbeddedRelationsAnswersInThePinnedOrder(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunRelationsAnswersInThePinnedOrder(t, ctx, newEmbeddedRelationsFixture(t, "relord")) +} + +func TestEmbeddedRelationsOrdersNeighborsFromBothPlanesTogether(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunRelationsOrdersNeighborsFromBothPlanesTogether(t, ctx, newEmbeddedRelationsFixture(t, "relplane")) +} + +func TestEmbeddedRelationsAnswersAWispTargetInTheOutDirection(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunRelationsAnswersAWispTargetInTheOutDirection(t, ctx, newEmbeddedRelationsFixture(t, "relwout")) +} + +func TestEmbeddedRelationsRefusesTheZeroDirection(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunRelationsRefusesTheZeroDirection(t, ctx, newEmbeddedRelationsFixture(t, "reldirnone")) +} + +func TestEmbeddedRelationsSeparatesNoNeighborsFromNoSuchIssue(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunRelationsSeparatesNoNeighborsFromNoSuchIssue(t, ctx, newEmbeddedRelationsFixture(t, "relmiss")) +} + +func TestEmbeddedRelationsResolvesAWispAnchor(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunRelationsResolvesAWispAnchor(t, ctx, newEmbeddedRelationsFixture(t, "relwisp")) +} + +func TestEmbeddedRelationsFiltersByAnOpenTypeVocabulary(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunRelationsFiltersByAnOpenTypeVocabulary(t, ctx, newEmbeddedRelationsFixture(t, "relfilter")) +} + +func TestEmbeddedRelationsRefusesAnUnusableTypeFilter(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunRelationsRefusesAnUnusableTypeFilter(t, ctx, newEmbeddedRelationsFixture(t, "relbadfilter")) +} + +func TestEmbeddedRelationsRefusesATypeFilterOverTheColumnLength(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunRelationsRefusesATypeFilterOverTheColumnLength(t, ctx, newEmbeddedRelationsFixture(t, "rellongfilter")) +} + +func TestEmbeddedRelationsDirectionSelectsTheInverseGraph(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunRelationsDirectionSelectsTheInverseGraph(t, ctx, newEmbeddedRelationsFixture(t, "reldir")) +} + +func TestEmbeddedRelationsLeavesTheCallersRequestAlone(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunRelationsLeavesTheCallersRequestAlone(t, ctx, newEmbeddedRelationsFixture(t, "relsnap")) +} + +func TestEmbeddedRelationsLeavesAnExternalTargetOutOfTheAnswer(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunRelationsLeavesAnExternalTargetOutOfTheAnswer(t, ctx, newEmbeddedRelationsFixture(t, "relext")) +} + +func TestEmbeddedRelationsResolvesTheAnchorIDExactly(t *testing.T) { + skipUnlessEmbeddedDolt(t) + ctx := t.Context() + conformance.RunRelationsResolvesTheAnchorIDExactly(t, ctx, newEmbeddedRelationsFixture(t, "relexact")) +} + +func newEmbeddedRelationsFixture(t *testing.T, prefix string) conformance.RelationsFixture { + t.Helper() + te := newTestEnv(t, prefix) + relations, err := te.store.IssueRelations() + if err != nil { + t.Fatalf("IssueRelations(): %v", err) + } + kit := newEmbeddedRoleFixtureKit(te, prefix) + return conformance.RelationsFixture{ + IssuePrefix: kit.IssuePrefix, + Relations: relations, + CreateIssue: kit.CreateIssue, + CreateWisp: kit.CreateWisp, + AddDependency: kit.AddDependency, + QueryScalar: kit.QueryScalar, + } +} diff --git a/internal/storage/embeddeddolt/role_fixture_kit_test.go b/internal/storage/embeddeddolt/role_fixture_kit_test.go new file mode 100644 index 000000000..b1bd6eef6 --- /dev/null +++ b/internal/storage/embeddeddolt/role_fixture_kit_test.go @@ -0,0 +1,252 @@ +//go:build cgo + +package embeddeddolt_test + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/backend/conformance" + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/storage/embeddeddolt" + "github.com/steveyegge/beads/internal/types" +) + +// roleFixtureKit is the embedded store's answer to the hooks every issueops +// role fixture in package conformance needs. A role's wiring file composes one +// of these with the accessor under test and the IssuePrefix, so the seeding and +// scalar-query plumbing is written once per backend instead of once per role. +// +// The field names and signatures are IDENTICAL across the three backends' +// kits, and identical to the fields the conformance fixtures declare, so a kit +// closure is assignable to any role fixture with no adapter in between. That +// sameness is the point of the type; changing a signature here is a change to +// all three backends and to every role wiring at once. +// +// FROZEN SURFACE. This file is owned by the scaffolding slice (bd-kue5t) and +// no role slice edits it. A role that needs a hook this kit does not expose +// routes the addition through a follow-up commit against that bead, so the +// three kits never drift apart in a worktree. +// +// NAMING CONVENTION FOR EVERYTHING BUILT ON THIS KIT: every unexported helper a +// role slice adds — in package conformance and in the per-backend wiring files — +// is ROLE-PREFIXED (seedRelationsAnchor, assertCommenterEventCount), the way the +// existing contract already names seedDependencyEditorIssue and +// assertDependencyEdgeCount. Five slices add files to one package from separate +// worktrees; two of them each defining a bare seedIssue would compile alone and +// break combined. The scaffolding's own helpers are prefixed roleFixtureKit for +// the same reason. +type roleFixtureKit struct { + // IssuePrefix namespaces the ids each assertion seeds, so several + // assertions can share one database. + IssuePrefix string + // CreateIssue seeds a durable issue in the issues plane. + CreateIssue func(context.Context, *types.Issue, string) error + // CreateWisp seeds an ephemeral issue in the wisps plane. It is a separate + // field rather than a flag because the three backends reach the two planes + // through different verbs. + CreateWisp func(context.Context, *types.Issue, string) error + // AddDependency seeds ONE edge, routed to the plane the edge's SOURCE lives + // in, and RECORDS a dependency_added event. + // + // The event is not incidental. The unit-of-work backend has no event-free + // route to the dependency tables — both domain.DependencyUseCase.add and + // AddDependencies hard-code EmitEvent: true — while the two store backends + // default the other way (dolt/dependencies.go:20-26 "adds a dependency + // between two issues WITHOUT recording a dependency_added event"). Rather + // than let the same seed leave different rows behind on different backends, + // all three kits emit. A contract case that counts events must therefore + // take a DELTA around the operation under test; an absolute count taken + // after seeding edges counts the seeds too. + // + // SPEC-GAP bd-yby99.1: no issueops leaf doc says whether a structural + // dependency insert records an event, so the kits normalise rather than + // pick a winner. The owner adjudicates it with the rest of the batch. + AddDependency func(context.Context, *types.Dependency, string) error + // SetConfig writes one workspace config key, which is how a case installs + // the vocabulary (excluded types, default limits) a request is read against. + SetConfig func(context.Context, string, string) error + // QueryScalar runs a single-row query and scans it, and RETURNS the error + // rather than failing the test, so a case can assert on a query that is + // expected to fail. + QueryScalar func(context.Context, string, []any, ...any) error + // CountHistory reports how many history entries the fixture's branch has, + // for the "at most one entry per call, none when nothing landed" clause the + // role contracts state. Cases take it before and after rather than reading + // the top of the log, because two commits made inside one second tie on + // date and their relative order is not something to rely on. + // + // A nil CountHistory means "this backend cannot observe history here". A + // case that needs it must then skip LOUDLY with that reason rather than + // pass quietly. It is non-nil on all three backends today; see + // uow/role_fixture_kit_test.go for the evidence on the awkward one. + CountHistory func(context.Context) (int, error) +} + +// roleFixtureKitComposesConformanceFixtures is the compile-time half of the +// kit's promise: every hook is assignable to the fixture field of the same +// name with NO adapter in between. A signature drifting apart from the +// conformance fixtures breaks here, in the frozen file that owns the +// signatures, instead of in five role wirings at once. +var roleFixtureKitComposesConformanceFixtures = func(kit roleFixtureKit) (conformance.DependencyEditorFixture, conformance.IssueOperationsStagingFixture) { + return conformance.DependencyEditorFixture{ + IssuePrefix: kit.IssuePrefix, + CreateIssue: kit.CreateIssue, + CreateWisp: kit.CreateWisp, + QueryScalar: kit.QueryScalar, + }, conformance.IssueOperationsStagingFixture{ + IssuePrefix: kit.IssuePrefix, + CreateIssue: kit.CreateIssue, + AddDependency: kit.AddDependency, + SetConfig: kit.SetConfig, + QueryScalar: kit.QueryScalar, + } +} + +// newEmbeddedRoleFixtureKit builds the kit for an environment from newTestEnv. +// The store's own create routes an ephemeral issue to the wisps plane, so the +// two seed verbs differ only by the flag already on the issue. +// +// The scalar hooks open their own short-lived SQL connection and RETURN the +// error, rather than delegating to testEnv.queryScalar, which fails the test +// on any error and so cannot express "this query was expected to fail". That +// keeps QueryScalar's meaning identical to the other two backends'. +func newEmbeddedRoleFixtureKit(te *testEnv, prefix string) roleFixtureKit { + queryScalar := func(ctx context.Context, query string, args []any, dest ...any) error { + db, cleanup, err := embeddeddolt.OpenSQL(ctx, te.dataDir, te.database, "main") + if err != nil { + return err + } + defer func() { _ = cleanup() }() + return db.QueryRowContext(ctx, query, args...).Scan(dest...) + } + return roleFixtureKit{ + IssuePrefix: prefix, + CreateIssue: te.store.CreateIssue, + CreateWisp: te.store.CreateIssue, + AddDependency: func(ctx context.Context, dep *types.Dependency, actor string) error { + return te.store.AddDependencyWithOptions(ctx, dep, actor, storage.DependencyAddOptions{EmitEvent: true}) + }, + SetConfig: te.store.SetConfig, + QueryScalar: queryScalar, + CountHistory: func(ctx context.Context) (int, error) { + var entries int + err := queryScalar(ctx, "SELECT COUNT(*) FROM dolt_log", nil, &entries) + return entries, err + }, + } +} + +// TestEmbeddedRoleFixtureKitHooksAreUsable is the scaffolding's own tripwire: +// every hook the role fixtures compose is exercised once here, so a kit broken +// by a signature change fails in one obvious place instead of five role suites. +func TestEmbeddedRoleFixtureKitHooksAreUsable(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "kit") + ctx := t.Context() + + assertRoleFixtureKitHooksAreUsable(t, ctx, newEmbeddedRoleFixtureKit(te, "kit")) +} + +// assertRoleFixtureKitHooksAreUsable drives every hook once and checks the rows +// landed where the field docs say they land. It pins the FIXTURE, not a role, +// and is deliberately a byte-for-byte sibling of the same helper in the other +// two backends' kit files so the three can be diffed. +func assertRoleFixtureKitHooksAreUsable(t *testing.T, ctx context.Context, kit roleFixtureKit) { + t.Helper() + issue := kit.IssuePrefix + "-kit-issue" + target := kit.IssuePrefix + "-kit-target" + wisp := kit.IssuePrefix + "-kit-wisp" + + for _, id := range []string{issue, target} { + if err := kit.CreateIssue(ctx, &types.Issue{ + ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, + }, "seed"); err != nil { + t.Fatalf("kit.CreateIssue(%s): %v", id, err) + } + } + if err := kit.CreateWisp(ctx, &types.Issue{ + ID: wisp, Title: wisp, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: true, + }, "seed"); err != nil { + t.Fatalf("kit.CreateWisp(%s): %v", wisp, err) + } + if err := kit.AddDependency(ctx, &types.Dependency{ + IssueID: issue, DependsOnID: target, Type: types.DepBlocks, + }, "seed"); err != nil { + t.Fatalf("kit.AddDependency: %v", err) + } + if err := kit.SetConfig(ctx, "role_fixture_kit_probe", "on"); err != nil { + t.Fatalf("kit.SetConfig: %v", err) + } + + var issues, wisps, edges int + if err := kit.QueryScalar(ctx, "SELECT COUNT(*) FROM issues WHERE id IN (?, ?)", []any{issue, target}, &issues); err != nil { + t.Fatalf("kit.QueryScalar issues: %v", err) + } + if issues != 2 { + t.Fatalf("seeded durable issues = %d, want 2", issues) + } + if err := kit.QueryScalar(ctx, "SELECT COUNT(*) FROM wisps WHERE id = ?", []any{wisp}, &wisps); err != nil { + t.Fatalf("kit.QueryScalar wisps: %v", err) + } + if wisps != 1 { + t.Fatalf("seeded wisps = %d, want 1 — CreateWisp did not reach the ephemeral plane", wisps) + } + if err := kit.QueryScalar(ctx, + // The target's own class decides which typed column holds it, so the + // contracts resolve it through this COALESCE rather than one column. + "SELECT COUNT(*) FROM dependencies WHERE issue_id = ? AND "+ + "COALESCE(depends_on_issue_id, depends_on_wisp_id, depends_on_external) = ?", + []any{issue, target}, &edges); err != nil { + t.Fatalf("kit.QueryScalar dependencies: %v", err) + } + if edges != 1 { + t.Fatalf("seeded edges = %d, want 1", edges) + } + var configured string + if err := kit.QueryScalar(ctx, "SELECT value FROM config WHERE `key` = ?", []any{"role_fixture_kit_probe"}, &configured); err != nil { + t.Fatalf("kit.QueryScalar config: %v", err) + } + if configured != "on" { + t.Fatalf("configured value = %q, want %q", configured, "on") + } + + if kit.CountHistory == nil { + t.Fatal("kit.CountHistory is nil — this backend cannot observe history, which the role contracts' entry-per-call clause needs") + } + entries, err := kit.CountHistory(ctx) + if err != nil { + t.Fatalf("kit.CountHistory: %v", err) + } + if entries < 1 { + t.Fatalf("history entries = %d, want at least the initializing commit", entries) + } +} + +// TestEmbeddedRoleFixtureKitCountHistoryMovesWithACommit is the other half of +// the history capability: CountHistory has to MOVE, not merely answer. The seed +// hooks are the wrong probe for it here — withConn takes a SQL commit, not a +// Dolt one, so an embedded AddDependency writes rows without versioning them — +// so the delta is proven with the store's own committing verb. +func TestEmbeddedRoleFixtureKitCountHistoryMovesWithACommit(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "kithist") + ctx := t.Context() + kit := newEmbeddedRoleFixtureKit(te, "kithist") + + seedIssues(t, ctx, te.store, "kithist-a") + before, err := kit.CountHistory(ctx) + if err != nil { + t.Fatalf("CountHistory before: %v", err) + } + if err := te.store.Commit(ctx, "bd: role fixture kit history probe"); err != nil { + t.Fatalf("Commit: %v", err) + } + after, err := kit.CountHistory(ctx) + if err != nil { + t.Fatalf("CountHistory after: %v", err) + } + if after != before+1 { + t.Fatalf("history entries went %d -> %d across one commit, want exactly one more", before, after) + } +} diff --git a/internal/storage/embeddeddolt/role_test_helpers_test.go b/internal/storage/embeddeddolt/role_test_helpers_test.go new file mode 100644 index 000000000..1a69a2b53 --- /dev/null +++ b/internal/storage/embeddeddolt/role_test_helpers_test.go @@ -0,0 +1,44 @@ +//go:build cgo + +package embeddeddolt_test + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/internal/storage/embeddeddolt" + "github.com/steveyegge/beads/internal/types" +) + +// This file holds the test helpers the issueops role tests share. They live +// here, in a file that owns no test of its own, because the per-role duplicate +// files that used to define them are being folded into the shared conformance +// contracts one role at a time: a helper defined inside a file that is about to +// be deleted takes its siblings' compilation with it. + +// seedIssues creates durable issues with the given ids. +func seedIssues(t *testing.T, ctx context.Context, store *embeddeddolt.EmbeddedDoltStore, ids ...string) { + t.Helper() + for _, id := range ids { + issue := &types.Issue{ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask} + if err := store.CreateIssue(ctx, issue, "seed"); err != nil { + t.Fatalf("CreateIssue(%s): %v", id, err) + } + } +} + +// skipKnownDivergence parks one conformance case on the backend that disagrees +// with the leaf contract's doc comment. +// +// The contract case asserts what the doc promises, so a genuine disagreement is +// a behaviour-unification decision for the owner rather than something a test +// slice may settle by weakening the assertion. Parking at the WIRING site (never +// inside the shared Run function) keeps the case running and passing on the +// backends that agree, so their behaviour is pinned the day the divergence is +// found. The "KNOWN DIVERGENCE" prefix is literal so `grep -r "KNOWN DIVERGENCE"` +// finds every parked case, and beadID names the child of bd-yby99 that records +// the three-way observed behaviour. +func skipKnownDivergence(t *testing.T, beadID, reason string) { + t.Helper() + t.Skipf("KNOWN DIVERGENCE %s: %s", beadID, reason) +} diff --git a/internal/storage/embeddeddolt/transaction.go b/internal/storage/embeddeddolt/transaction.go index 70fdf0fb2..174c08bd1 100644 --- a/internal/storage/embeddeddolt/transaction.go +++ b/internal/storage/embeddeddolt/transaction.go @@ -28,10 +28,22 @@ func (s *EmbeddedDoltStore) RunInIssueLifecycleTransaction(ctx context.Context, } func (s *EmbeddedDoltStore) runTransaction(ctx context.Context, commitMsg string, fn func(tx *embeddedTransaction) error) error { + return s.runTransactionWithMessage(ctx, func(tx *embeddedTransaction) (string, error) { + return commitMsg, fn(tx) + }) +} + +// runTransactionWithMessage is runTransaction for work whose commit message is +// only known once the body has run. A ready claim names the id it won, and +// nothing outside the transaction can predict which one that is. +func (s *EmbeddedDoltStore) runTransactionWithMessage(ctx context.Context, fn func(tx *embeddedTransaction) (string, error)) error { var tracker versioncontrolops.DirtyTableTracker + var commitMsg string if err := s.withConn(ctx, true, func(tx *sql.Tx) error { - return fn(&embeddedTransaction{tx: tx, dirty: &tracker}) + var err error + commitMsg, err = fn(&embeddedTransaction{tx: tx, dirty: &tracker}) + return err }); err != nil { return err } diff --git a/internal/storage/errors_unsupported.go b/internal/storage/errors_unsupported.go index 30d50b0f4..56fa1c89b 100644 --- a/internal/storage/errors_unsupported.go +++ b/internal/storage/errors_unsupported.go @@ -1,13 +1,11 @@ package storage -import "fmt" +import "github.com/steveyegge/beads/issueops" -// ErrUnsupported reports an operation unavailable on a storage backend. -type ErrUnsupported struct { - Op string // method name, e.g. "AddLabel" or "Transaction.CreateIssues" - Backend string // e.g. "sqlite" -} - -func (e *ErrUnsupported) Error() string { - return fmt.Sprintf("operation %q not supported by the %s backend", e.Op, e.Backend) -} +// ErrUnsupported reports an operation unavailable on a storage backend. It is +// declared and documented by the public contract package, +// github.com/steveyegge/beads/issueops, so that a caller holding only a role +// interface can classify a refusal without importing this package. This is the +// SAME type, so every storage.ErrUnsupported reference and every errors.As site +// keeps matching. +type ErrUnsupported = issueops.ErrUnsupported diff --git a/internal/storage/hook_batch_closer.go b/internal/storage/hook_batch_closer.go new file mode 100644 index 000000000..8e04bdc4b --- /dev/null +++ b/internal/storage/hook_batch_closer.go @@ -0,0 +1,49 @@ +package storage + +import ( + "context" + + "github.com/steveyegge/beads/issueops" +) + +// BatchCloser returns the inner store's batch-close surface with this +// decorator's completion hooks layered over it. +// +// It recurses instead of delegating, for the reason IssueLifecycle does: a +// blind delegation would hand back the inner store's closer and silently drop +// every on_close script the decorator exists to run. +func (h *HookFiringStore) BatchCloser() (issueops.BatchCloser, error) { + inner, err := h.inner.BatchCloser() + if err != nil { + return nil, err + } + return &hookBatchCloser{inner: inner, hooks: h}, nil +} + +type hookBatchCloser struct { + inner issueops.BatchCloser + hooks issueOperationHooks +} + +// CloseBatch fires the close hook once PER LANDED ITEM, in request order, and +// fires nothing for an item that refused. Per item rather than once for the +// batch because a hook script is written against one issue: collapsing N +// closes into one firing would silently stop reporting N-1 of them. +// +// The claim, when one happened, fires the update hook the claim paths fire, +// after the closes — the same order the transaction applied them in. +func (o *hookBatchCloser) CloseBatch(ctx context.Context, request issueops.CloseBatchRequest) (issueops.CloseBatchResult, error) { + result, err := o.inner.CloseBatch(ctx, request) + if err != nil { + return result, err + } + for _, outcome := range result.Outcomes { + if outcome.Err == nil { + o.hooks.CompleteIssueOperationClose(outcome.Issue) + } + } + if result.ClaimedNext != nil { + o.hooks.CompleteIssueOperationUpdate(result.ClaimedNext.Issue) + } + return result, nil +} diff --git a/internal/storage/hook_batch_closer_test.go b/internal/storage/hook_batch_closer_test.go new file mode 100644 index 000000000..0de4d6f44 --- /dev/null +++ b/internal/storage/hook_batch_closer_test.go @@ -0,0 +1,116 @@ +package storage + +import ( + "context" + "errors" + "reflect" + "testing" + + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" +) + +// fakeBatchCloser answers with a fixed result so the per-item firing rules can +// be checked without a database. +type fakeBatchCloser struct { + result issueops.CloseBatchResult + err error +} + +func (f *fakeBatchCloser) CloseBatch(context.Context, issueops.CloseBatchRequest) (issueops.CloseBatchResult, error) { + return f.result, f.err +} + +// batchCloserStore is a DoltStorage whose only real method is BatchCloser. +type batchCloserStore struct { + DoltStorage + closer issueops.BatchCloser + err error +} + +func (s batchCloserStore) BatchCloser() (issueops.BatchCloser, error) { return s.closer, s.err } + +// TestHookFiringStoreBatchCloserLayersHooksOverInner pins the recursion, for +// the reason its Lifecycle sibling pins it: delegating would compile, satisfy +// Storage, and silently stop running every on_close script. +func TestHookFiringStoreBatchCloserLayersHooksOverInner(t *testing.T) { + inner := &fakeBatchCloser{} + store := &HookFiringStore{inner: batchCloserStore{closer: inner}} + + closer, err := store.BatchCloser() + if err != nil { + t.Fatalf("BatchCloser() error = %v", err) + } + hooked, ok := closer.(*hookBatchCloser) + if !ok { + t.Fatalf("BatchCloser() = %T, want *hookBatchCloser", closer) + } + if hooked.inner != issueops.BatchCloser(inner) { + t.Fatalf("hook layer wraps %#v, want the inner store's closer", hooked.inner) + } + if hooked.hooks != issueOperationHooks(store) { + t.Fatalf("hook layer fires into %#v, want the decorator itself", hooked.hooks) + } +} + +func TestHookFiringStoreBatchCloserPropagatesInnerError(t *testing.T) { + want := errors.New("inner refused") + store := &HookFiringStore{inner: batchCloserStore{err: want}} + + closer, err := store.BatchCloser() + if !errors.Is(err, want) { + t.Fatalf("BatchCloser() error = %v, want %v", err, want) + } + if closer != nil { + t.Fatalf("BatchCloser() = %T, want nil", closer) + } +} + +// TestHookBatchCloserFiresOncePerLandedItem pins the rule that makes a batch +// close indistinguishable from N single closes as far as a hook script can +// tell: one firing per item that landed, in request order, and none for an +// item that refused. Collapsing the batch into one firing would silently stop +// reporting every close but one. +func TestHookBatchCloserFiresOncePerLandedItem(t *testing.T) { + issue := func(id string) *types.Issue { return &types.Issue{ID: id} } + inner := &fakeBatchCloser{result: issueops.CloseBatchResult{ + Outcomes: []issueops.CloseOutcome{ + {IssueID: "bd-1", Issue: issue("bd-1")}, + {IssueID: "bd-2", Err: errors.New("refused")}, + {IssueID: "bd-3", Issue: issue("bd-3")}, + }, + ClaimedNext: &types.IssueWithCounts{Issue: issue("bd-4")}, + }} + recorder := &recordingIssueOperationHooks{} + closer := &hookBatchCloser{inner: inner, hooks: recorder} + + if _, err := closer.CloseBatch(context.Background(), issueops.CloseBatchRequest{Actor: "worker"}); err != nil { + t.Fatalf("CloseBatch() error = %v", err) + } + + // The claim's update fires last, matching the order the transaction + // applied them in: the closes, then the claim. + want := []string{"close", "close", "update"} + if !reflect.DeepEqual(recorder.completions, want) { + t.Fatalf("hooks fired = %v, want %v", recorder.completions, want) + } +} + +// TestHookBatchCloserFiresNothingOnRequestFailure pins that a batch that never +// ran reports nothing: a method error means validation, cancellation or +// infrastructure, so there is no landed item to announce. +func TestHookBatchCloserFiresNothingOnRequestFailure(t *testing.T) { + inner := &fakeBatchCloser{ + result: issueops.CloseBatchResult{Outcomes: []issueops.CloseOutcome{{IssueID: "bd-1", Issue: &types.Issue{ID: "bd-1"}}}}, + err: errors.New("boom"), + } + recorder := &recordingIssueOperationHooks{} + closer := &hookBatchCloser{inner: inner, hooks: recorder} + + if _, err := closer.CloseBatch(context.Background(), issueops.CloseBatchRequest{Actor: "worker"}); err == nil { + t.Fatal("CloseBatch() error = nil, want the inner failure") + } + if recorder.completions != nil { + t.Fatalf("hooks fired = %v, want none", recorder.completions) + } +} diff --git a/internal/storage/hook_commenter.go b/internal/storage/hook_commenter.go new file mode 100644 index 000000000..042321723 --- /dev/null +++ b/internal/storage/hook_commenter.go @@ -0,0 +1,37 @@ +package storage + +import ( + "context" + + "github.com/steveyegge/beads/issueops" +) + +// Commenter returns the inner store's add-comment surface with this +// decorator's completion hooks layered over it. +// +// It recurses instead of delegating, for the reason IssueLifecycle does: the +// legacy AddIssueComment path fires the update hook, and a blind delegation +// would hand back the inner store's commenter and silently stop firing it. +func (h *HookFiringStore) Commenter() (issueops.Commenter, error) { + inner, err := h.inner.Commenter() + if err != nil { + return nil, err + } + return &hookCommenter{inner: inner, hooks: h}, nil +} + +type hookCommenter struct { + inner issueops.Commenter + hooks issueOperationHooks +} + +// AddComment fires the update hook for the commented issue, which is what the +// legacy comment path fires: a comment is a change to the issue as far as a +// hook script is concerned, and there is no on_comment event to fire instead. +func (c *hookCommenter) AddComment(ctx context.Context, request issueops.AddCommentRequest) (issueops.AddCommentResult, error) { + result, err := c.inner.AddComment(ctx, request) + if err == nil && result.Comment != nil { + c.hooks.CompleteIssueOperationComment(ctx, result.Comment.IssueID) + } + return result, err +} diff --git a/internal/storage/hook_commenter_test.go b/internal/storage/hook_commenter_test.go new file mode 100644 index 000000000..a83f26b1d --- /dev/null +++ b/internal/storage/hook_commenter_test.go @@ -0,0 +1,104 @@ +package storage + +import ( + "context" + "errors" + "reflect" + "testing" + + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" +) + +// fakeCommenter answers with a fixed comment so the firing rules can be +// checked without a database. +type fakeCommenter struct { + comment *types.Comment + err error +} + +func (f *fakeCommenter) AddComment(context.Context, issueops.AddCommentRequest) (issueops.AddCommentResult, error) { + return issueops.AddCommentResult{Comment: f.comment}, f.err +} + +// commenterStore is a DoltStorage whose only real method is Commenter. +type commenterStore struct { + DoltStorage + commenter issueops.Commenter + err error +} + +func (s commenterStore) Commenter() (issueops.Commenter, error) { return s.commenter, s.err } + +// TestHookFiringStoreCommenterLayersHooksOverInner pins the recursion. +// Delegating to the inner store instead would still compile and still satisfy +// Storage, and every guarded comment would silently stop firing the update +// hook AddIssueComment fires. +func TestHookFiringStoreCommenterLayersHooksOverInner(t *testing.T) { + inner := &fakeCommenter{} + store := &HookFiringStore{inner: commenterStore{commenter: inner}} + + commenter, err := store.Commenter() + if err != nil { + t.Fatalf("Commenter() error = %v", err) + } + hooked, ok := commenter.(*hookCommenter) + if !ok { + t.Fatalf("Commenter() = %T, want *hookCommenter", commenter) + } + if hooked.inner != issueops.Commenter(inner) { + t.Fatalf("hook layer wraps %#v, want the inner store's commenter", hooked.inner) + } + if hooked.hooks != issueOperationHooks(store) { + t.Fatalf("hook layer fires into %#v, want the decorator itself", hooked.hooks) + } +} + +func TestHookFiringStoreCommenterPropagatesInnerError(t *testing.T) { + want := errors.New("inner refused") + store := &HookFiringStore{inner: commenterStore{err: want}} + + commenter, err := store.Commenter() + if !errors.Is(err, want) { + t.Fatalf("Commenter() error = %v, want %v", err, want) + } + if commenter != nil { + t.Fatalf("Commenter() = %T, want nil", commenter) + } +} + +// TestHookCommenterFiresForTheCommentedIssue pins that the hook names the +// issue the STORED comment landed on rather than the id the caller asked for: +// the request's id may be a wisp alias the role resolved, and a script handed +// the unresolved one would look up the wrong row. +func TestHookCommenterFiresForTheCommentedIssue(t *testing.T) { + for _, tc := range []struct { + name string + commenter *fakeCommenter + want []string + }{ + { + name: "stored comment fires its own issue id", + commenter: &fakeCommenter{comment: &types.Comment{ID: "c1", IssueID: "bd-resolved"}}, + want: []string{"comment:bd-resolved"}, + }, + { + name: "error fires nothing", + commenter: &fakeCommenter{comment: &types.Comment{IssueID: "bd-1"}, err: errors.New("boom")}, + want: nil, + }, + } { + t.Run(tc.name, func(t *testing.T) { + recorder := &recordingIssueOperationHooks{} + commenter := &hookCommenter{inner: tc.commenter, hooks: recorder} + + _, _ = commenter.AddComment(context.Background(), issueops.AddCommentRequest{ + Author: "worker", IssueID: "bd-asked", Text: "hi", + }) + + if !reflect.DeepEqual(recorder.completions, tc.want) { + t.Fatalf("hooks fired = %v, want %v", recorder.completions, tc.want) + } + }) + } +} diff --git a/internal/storage/hook_decorator.go b/internal/storage/hook_decorator.go index 67cb8e08b..6c194e7fa 100644 --- a/internal/storage/hook_decorator.go +++ b/internal/storage/hook_decorator.go @@ -348,6 +348,22 @@ func (h *HookFiringStore) CompleteIssueOperationClose(issue *types.Issue) { h.fireHook(hooks.EventClose, cloneIssueForHook(issue)) } +// CompleteIssueOperationDependency fires the update hook for an issue whose +// edges a committed guarded edit changed. It re-reads the issue with its +// dependency records, exactly as AddDependency and RemoveDependency do, so a +// hook script sees the graph the edit produced rather than the row alone. +func (h *HookFiringStore) CompleteIssueOperationDependency(ctx context.Context, issueID string) { + h.fireDependencyHookByID(ctx, issueID) +} + +// CompleteIssueOperationComment fires the update hook for a committed guarded +// comment, which is the event AddIssueComment fires: there is no on_comment +// event, and a comment is a change to the issue as far as a script is +// concerned. +func (h *HookFiringStore) CompleteIssueOperationComment(ctx context.Context, issueID string) { + h.fireHookByID(ctx, hooks.EventUpdate, issueID) +} + func (h *HookFiringStore) fireHookByID(ctx context.Context, event, id string) { if h.runner == nil { return diff --git a/internal/storage/hook_dependency_editor.go b/internal/storage/hook_dependency_editor.go new file mode 100644 index 000000000..3e2d222e8 --- /dev/null +++ b/internal/storage/hook_dependency_editor.go @@ -0,0 +1,60 @@ +package storage + +import ( + "context" + + "github.com/steveyegge/beads/issueops" +) + +// DependencyEditor returns the inner store's dependency-edge surface with this +// decorator's completion hooks layered over it. +// +// It recurses instead of delegating. A dependency change is an update to the +// issue the edge leaves, so the legacy AddDependency and RemoveDependency +// paths fire the update hook with a dependency-hydrated snapshot; a blind +// delegation would silently stop firing it the moment a front door moved onto +// the role. +func (h *HookFiringStore) DependencyEditor() (issueops.DependencyEditor, error) { + inner, err := h.inner.DependencyEditor() + if err != nil { + return nil, err + } + return &hookDependencyEditor{inner: inner, hooks: h}, nil +} + +type hookDependencyEditor struct { + inner issueops.DependencyEditor + hooks issueOperationHooks +} + +// AddDependencies fires the update hook once per DISTINCT source issue, in the +// order those issues first appear in the request. Per source rather than per +// edge because a hook script is written against one issue: two edges leaving +// the same issue are one change to it, and firing twice would have a script +// react to a graph it already saw. +func (e *hookDependencyEditor) AddDependencies(ctx context.Context, request issueops.AddDependenciesRequest) (issueops.AddDependenciesResult, error) { + result, err := e.inner.AddDependencies(ctx, request) + if err != nil { + return result, err + } + seen := make(map[string]struct{}, len(result.Added)) + for _, edge := range result.Added { + if _, ok := seen[edge.IssueID]; ok { + continue + } + seen[edge.IssueID] = struct{}{} + e.hooks.CompleteIssueOperationDependency(ctx, edge.IssueID) + } + return result, nil +} + +// RemoveDependency fires the update hook only for an edge that was actually +// there. A no-op removal changed no graph, and a hook fired for it is a hook a +// replayed teardown runs on every pass. +func (e *hookDependencyEditor) RemoveDependency(ctx context.Context, request issueops.RemoveDependencyRequest) (issueops.RemoveDependencyResult, error) { + result, err := e.inner.RemoveDependency(ctx, request) + if err == nil && result.Removed { + e.hooks.CompleteIssueOperationDependency(ctx, request.IssueID) + } + return result, err +} diff --git a/internal/storage/hook_dependency_editor_test.go b/internal/storage/hook_dependency_editor_test.go new file mode 100644 index 000000000..10a5ab520 --- /dev/null +++ b/internal/storage/hook_dependency_editor_test.go @@ -0,0 +1,162 @@ +package storage + +import ( + "context" + "errors" + "reflect" + "testing" + + "github.com/steveyegge/beads/issueops" +) + +// fakeDependencyEditor answers with a fixed result so the firing rules can be +// checked without a database. +type fakeDependencyEditor struct { + added []issueops.DependencyEdge + removed bool + err error +} + +func (f *fakeDependencyEditor) AddDependencies(context.Context, issueops.AddDependenciesRequest) (issueops.AddDependenciesResult, error) { + return issueops.AddDependenciesResult{Added: f.added}, f.err +} + +func (f *fakeDependencyEditor) RemoveDependency(context.Context, issueops.RemoveDependencyRequest) (issueops.RemoveDependencyResult, error) { + return issueops.RemoveDependencyResult{Removed: f.removed}, f.err +} + +// dependencyEditorStore is a DoltStorage whose only real method is +// DependencyEditor. +type dependencyEditorStore struct { + DoltStorage + editor issueops.DependencyEditor + err error +} + +func (s dependencyEditorStore) DependencyEditor() (issueops.DependencyEditor, error) { + return s.editor, s.err +} + +// TestHookFiringStoreDependencyEditorLayersHooksOverInner pins the recursion. +// Delegating to the inner store instead would still compile and still satisfy +// Storage, and every guarded edge edit would silently stop firing the update +// hook that AddDependency and RemoveDependency fire. +func TestHookFiringStoreDependencyEditorLayersHooksOverInner(t *testing.T) { + inner := &fakeDependencyEditor{} + store := &HookFiringStore{inner: dependencyEditorStore{editor: inner}} + + editor, err := store.DependencyEditor() + if err != nil { + t.Fatalf("DependencyEditor() error = %v", err) + } + hooked, ok := editor.(*hookDependencyEditor) + if !ok { + t.Fatalf("DependencyEditor() = %T, want *hookDependencyEditor", editor) + } + if hooked.inner != issueops.DependencyEditor(inner) { + t.Fatalf("hook layer wraps %#v, want the inner store's editor", hooked.inner) + } + if hooked.hooks != issueOperationHooks(store) { + t.Fatalf("hook layer fires into %#v, want the decorator itself", hooked.hooks) + } +} + +func TestHookFiringStoreDependencyEditorPropagatesInnerError(t *testing.T) { + want := errors.New("inner refused") + store := &HookFiringStore{inner: dependencyEditorStore{err: want}} + + editor, err := store.DependencyEditor() + if !errors.Is(err, want) { + t.Fatalf("DependencyEditor() error = %v, want %v", err, want) + } + if editor != nil { + t.Fatalf("DependencyEditor() = %T, want nil", editor) + } +} + +// TestHookDependencyEditorFiresOncePerSource pins the de-duplication. A hook +// script is written against one issue, so two edges leaving the same issue are +// one change to it; firing twice would have a script react to a graph it +// already saw. +func TestHookDependencyEditorFiresOncePerSource(t *testing.T) { + edge := func(from, to string) issueops.DependencyEdge { + return issueops.DependencyEdge{IssueID: from, DependsOnID: to, Type: issueops.DepBlocks} + } + for _, tc := range []struct { + name string + editor *fakeDependencyEditor + want []string + }{ + { + name: "one edge fires its source", + editor: &fakeDependencyEditor{added: []issueops.DependencyEdge{edge("bd-1", "bd-2")}}, + want: []string{"dependency:bd-1"}, + }, + { + name: "two edges from one source fire once, in request order", + editor: &fakeDependencyEditor{added: []issueops.DependencyEdge{ + edge("bd-1", "bd-2"), edge("bd-3", "bd-4"), edge("bd-1", "bd-5"), + }}, + want: []string{"dependency:bd-1", "dependency:bd-3"}, + }, + { + name: "a refused request fires nothing", + editor: &fakeDependencyEditor{ + added: []issueops.DependencyEdge{edge("bd-1", "bd-2")}, + err: errors.New("boom"), + }, + want: nil, + }, + } { + t.Run(tc.name, func(t *testing.T) { + recorder := &recordingIssueOperationHooks{} + editor := &hookDependencyEditor{inner: tc.editor, hooks: recorder} + + _, _ = editor.AddDependencies(context.Background(), issueops.AddDependenciesRequest{Actor: "worker"}) + + if !reflect.DeepEqual(recorder.completions, tc.want) { + t.Fatalf("hooks fired = %v, want %v", recorder.completions, tc.want) + } + }) + } +} + +// TestHookDependencyEditorRemoveFiresOnlyForARemovedEdge pins the idempotent +// case. A removal that found nothing changed no graph, and a hook fired for it +// is a hook a replayed teardown runs on every pass. +func TestHookDependencyEditorRemoveFiresOnlyForARemovedEdge(t *testing.T) { + for _, tc := range []struct { + name string + editor *fakeDependencyEditor + want []string + }{ + { + name: "removed edge fires", + editor: &fakeDependencyEditor{removed: true}, + want: []string{"dependency:bd-1"}, + }, + { + name: "no such edge fires nothing", + editor: &fakeDependencyEditor{}, + want: nil, + }, + { + name: "error fires nothing", + editor: &fakeDependencyEditor{removed: true, err: errors.New("boom")}, + want: nil, + }, + } { + t.Run(tc.name, func(t *testing.T) { + recorder := &recordingIssueOperationHooks{} + editor := &hookDependencyEditor{inner: tc.editor, hooks: recorder} + + _, _ = editor.RemoveDependency(context.Background(), issueops.RemoveDependencyRequest{ + Actor: "worker", IssueID: "bd-1", DependsOnID: "bd-2", + }) + + if !reflect.DeepEqual(recorder.completions, tc.want) { + t.Fatalf("hooks fired = %v, want %v", recorder.completions, tc.want) + } + }) + } +} diff --git a/internal/storage/hook_issue_operations.go b/internal/storage/hook_issue_operations.go index 5f0d23f10..e4a2c6c32 100644 --- a/internal/storage/hook_issue_operations.go +++ b/internal/storage/hook_issue_operations.go @@ -31,6 +31,8 @@ type issueOperationHooks interface { CompleteIssueOperationCreate(ctx context.Context, issue *types.Issue, dependencies []*types.Dependency) CompleteIssueOperationUpdate(issue *types.Issue) CompleteIssueOperationClose(issue *types.Issue) + CompleteIssueOperationDependency(ctx context.Context, issueID string) + CompleteIssueOperationComment(ctx context.Context, issueID string) } var _ issueOperationHooks = (*HookFiringStore)(nil) diff --git a/internal/storage/hook_issue_operations_test.go b/internal/storage/hook_issue_operations_test.go index 252491b58..2455daaa2 100644 --- a/internal/storage/hook_issue_operations_test.go +++ b/internal/storage/hook_issue_operations_test.go @@ -51,6 +51,12 @@ func (r *recordingIssueOperationHooks) CompleteIssueOperationUpdate(*types.Issue func (r *recordingIssueOperationHooks) CompleteIssueOperationClose(*types.Issue) { r.completions = append(r.completions, "close") } +func (r *recordingIssueOperationHooks) CompleteIssueOperationDependency(_ context.Context, issueID string) { + r.completions = append(r.completions, "dependency:"+issueID) +} +func (r *recordingIssueOperationHooks) CompleteIssueOperationComment(_ context.Context, issueID string) { + r.completions = append(r.completions, "comment:"+issueID) +} // lifecycleStore is a DoltStorage whose only real method is IssueLifecycle. type lifecycleStore struct { diff --git a/internal/storage/hook_ready_claimer.go b/internal/storage/hook_ready_claimer.go new file mode 100644 index 000000000..389071158 --- /dev/null +++ b/internal/storage/hook_ready_claimer.go @@ -0,0 +1,38 @@ +package storage + +import ( + "context" + + "github.com/steveyegge/beads/issueops" +) + +// ReadyClaimer returns the inner store's claim surface with this decorator's +// completion hooks layered over it. +// +// It recurses instead of delegating. A claim is an update to an issue — it +// sets the assignee and moves the status — so the legacy claim paths fire the +// update hook, and a blind delegation would silently stop firing it the moment +// a front door moved onto the role. +func (h *HookFiringStore) ReadyClaimer() (issueops.ReadyClaimer, error) { + inner, err := h.inner.ReadyClaimer() + if err != nil { + return nil, err + } + return &hookReadyClaimer{inner: inner, hooks: h}, nil +} + +type hookReadyClaimer struct { + inner issueops.ReadyClaimer + hooks issueOperationHooks +} + +// ClaimNext fires the update hook for the row it won, and nothing at all for +// an empty front: there is no issue to report, and a hook fired for "nothing +// happened" is a hook a polling agent runs forever. +func (c *hookReadyClaimer) ClaimNext(ctx context.Context, request issueops.ClaimNextRequest) (issueops.ClaimNextResult, error) { + result, err := c.inner.ClaimNext(ctx, request) + if err == nil && result.Claimed != nil { + c.hooks.CompleteIssueOperationUpdate(result.Claimed.Issue) + } + return result, err +} diff --git a/internal/storage/hook_ready_claimer_test.go b/internal/storage/hook_ready_claimer_test.go new file mode 100644 index 000000000..7571c7aa2 --- /dev/null +++ b/internal/storage/hook_ready_claimer_test.go @@ -0,0 +1,107 @@ +package storage + +import ( + "context" + "errors" + "reflect" + "testing" + + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" +) + +// fakeReadyClaimer answers with a fixed claim, or with nothing, or with an +// error, so the firing rules can be checked without a database. +type fakeReadyClaimer struct { + claimed *types.IssueWithCounts + err error +} + +func (f *fakeReadyClaimer) ClaimNext(context.Context, issueops.ClaimNextRequest) (issueops.ClaimNextResult, error) { + return issueops.ClaimNextResult{Claimed: f.claimed}, f.err +} + +// readyClaimerStore is a DoltStorage whose only real method is ReadyClaimer. +type readyClaimerStore struct { + DoltStorage + claimer issueops.ReadyClaimer + err error +} + +func (s readyClaimerStore) ReadyClaimer() (issueops.ReadyClaimer, error) { return s.claimer, s.err } + +// TestHookFiringStoreReadyClaimerLayersHooksOverInner pins the recursion. +// Delegating to the inner store instead would still compile and still satisfy +// Storage, and every claim would silently stop firing the update hook the +// legacy claim paths fire. +func TestHookFiringStoreReadyClaimerLayersHooksOverInner(t *testing.T) { + inner := &fakeReadyClaimer{} + store := &HookFiringStore{inner: readyClaimerStore{claimer: inner}} + + claimer, err := store.ReadyClaimer() + if err != nil { + t.Fatalf("ReadyClaimer() error = %v", err) + } + hooked, ok := claimer.(*hookReadyClaimer) + if !ok { + t.Fatalf("ReadyClaimer() = %T, want *hookReadyClaimer", claimer) + } + if hooked.inner != issueops.ReadyClaimer(inner) { + t.Fatalf("hook layer wraps %#v, want the inner store's claimer", hooked.inner) + } + if hooked.hooks != issueOperationHooks(store) { + t.Fatalf("hook layer fires into %#v, want the decorator itself", hooked.hooks) + } +} + +func TestHookFiringStoreReadyClaimerPropagatesInnerError(t *testing.T) { + want := errors.New("inner refused") + store := &HookFiringStore{inner: readyClaimerStore{err: want}} + + claimer, err := store.ReadyClaimer() + if !errors.Is(err, want) { + t.Fatalf("ReadyClaimer() error = %v, want %v", err, want) + } + if claimer != nil { + t.Fatalf("ReadyClaimer() = %T, want nil", claimer) + } +} + +// TestHookReadyClaimerFiresOnlyForAWonRow pins the empty-front rule. An empty +// ready front is the steady state of a drained queue and a polling agent hits +// it constantly; firing a hook for it would run every on_update script on a +// loop for an issue that does not exist. +func TestHookReadyClaimerFiresOnlyForAWonRow(t *testing.T) { + for _, tc := range []struct { + name string + claimer *fakeReadyClaimer + want []string + }{ + { + name: "won row fires update", + claimer: &fakeReadyClaimer{claimed: &types.IssueWithCounts{Issue: &types.Issue{ID: "bd-1"}}}, + want: []string{"update"}, + }, + { + name: "empty front fires nothing", + claimer: &fakeReadyClaimer{}, + want: nil, + }, + { + name: "error fires nothing", + claimer: &fakeReadyClaimer{claimed: &types.IssueWithCounts{Issue: &types.Issue{ID: "bd-1"}}, err: errors.New("boom")}, + want: nil, + }, + } { + t.Run(tc.name, func(t *testing.T) { + recorder := &recordingIssueOperationHooks{} + claimer := &hookReadyClaimer{inner: tc.claimer, hooks: recorder} + + _, _ = claimer.ClaimNext(context.Background(), issueops.ClaimNextRequest{Actor: "worker"}) + + if !reflect.DeepEqual(recorder.completions, tc.want) { + t.Fatalf("hooks fired = %v, want %v", recorder.completions, tc.want) + } + }) + } +} diff --git a/internal/storage/hook_relations.go b/internal/storage/hook_relations.go new file mode 100644 index 000000000..8c9ca58c5 --- /dev/null +++ b/internal/storage/hook_relations.go @@ -0,0 +1,17 @@ +package storage + +import ( + "github.com/steveyegge/beads/issueops" +) + +// IssueRelations returns the inner store's neighbor-query surface. +// +// It recurses, like every other accessor on this decorator, rather than being +// absent: the accessor set is uniform across the chain, so a caller never has +// to know which decorators a store is wearing. What it does NOT do is wrap the +// result — reads fire no completion hooks, because there is no completion to +// report. That is the same statement hook_issue_reader.go makes, and it is why +// both files are three lines. +func (h *HookFiringStore) IssueRelations() (issueops.Relations, error) { + return h.inner.IssueRelations() +} diff --git a/internal/storage/hook_relations_test.go b/internal/storage/hook_relations_test.go new file mode 100644 index 000000000..4bea9c7c4 --- /dev/null +++ b/internal/storage/hook_relations_test.go @@ -0,0 +1,50 @@ +package storage + +import ( + "errors" + "testing" + + "github.com/steveyegge/beads/issueops" +) + +type fakeIssueRelations struct{ issueops.Relations } + +// relationsStore is a DoltStorage whose only real method is IssueRelations. +type relationsStore struct { + DoltStorage + relations issueops.Relations + err error +} + +func (s relationsStore) IssueRelations() (issueops.Relations, error) { return s.relations, s.err } + +// TestHookFiringStoreIssueRelationsReturnsTheInnerSurfaceUnwrapped pins the +// same decision hook_issue_reader_test.go pins, for the other read role: reads +// fire no completion hooks, so the surface comes back UNWRAPPED. A future edit +// that "made the accessors consistent" by wrapping would put a hook layer on a +// path with nothing to fire. +func TestHookFiringStoreIssueRelationsReturnsTheInnerSurfaceUnwrapped(t *testing.T) { + inner := &fakeIssueRelations{} + store := &HookFiringStore{inner: relationsStore{relations: inner}} + + relations, err := store.IssueRelations() + if err != nil { + t.Fatalf("IssueRelations() error = %v", err) + } + if relations != issueops.Relations(inner) { + t.Fatalf("IssueRelations() = %#v, want the inner store's surface unwrapped", relations) + } +} + +func TestHookFiringStoreIssueRelationsPropagatesInnerError(t *testing.T) { + want := errors.New("inner refused") + store := &HookFiringStore{inner: relationsStore{err: want}} + + relations, err := store.IssueRelations() + if !errors.Is(err, want) { + t.Fatalf("IssueRelations() error = %v, want %v", err, want) + } + if relations != nil { + t.Fatalf("IssueRelations() = %T, want nil", relations) + } +} diff --git a/internal/storage/issueops/aggregate.go b/internal/storage/issueops/aggregate.go index 67169c26e..12ea0616d 100644 --- a/internal/storage/issueops/aggregate.go +++ b/internal/storage/issueops/aggregate.go @@ -284,10 +284,30 @@ func ApplyLabelPatch(ctx context.Context, tx DBTX, current *types.Issue, patch p target[label] = struct{}{} } } + // An empty-string entry is DROPPED rather than written or refused + // (bd-yby99.29). A label row carrying '' is junk that renders as nothing + // and matches nothing, so the two useful answers were dropping it and + // refusing it; dropping keeps a stray empty entry from failing an + // otherwise-good multi-label edit. + // + // Skipping here rather than at the insert is what makes it a no-op instead + // of a silent partial write: an Add of only '' leaves target equal to + // existing, so the sameStringSet check below reports Changed false and + // writes nothing at all. + // + // Entries already in existing are deliberately untouched. A legacy '' row + // survives an Add/Remove patch and is cleared by a Replace that omits it, + // which is the ordinary set semantics rather than a migration. for _, label := range patch.Replace.Value { + if label == "" { + continue + } target[label] = struct{}{} } for _, label := range patch.Add { + if label == "" { + continue + } target[label] = struct{}{} } for _, label := range patch.Remove { diff --git a/internal/storage/issueops/claim.go b/internal/storage/issueops/claim.go index 3d4dd71e5..6355a9983 100644 --- a/internal/storage/issueops/claim.go +++ b/internal/storage/issueops/claim.go @@ -12,6 +12,7 @@ import ( "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" ) // ClaimResult holds the result of a ClaimIssueInTx call. @@ -130,31 +131,48 @@ func ClaimIssueInTx(ctx context.Context, tx DBTX, id string, actor string) (*Cla if assignee == actor && currentStatus == types.StatusInProgress { return &ClaimResult{OldIssue: oldIssue, IsWisp: isWisp}, nil } + // The refusal carries the state that lost the CAS, read just above in + // THIS transaction, so a caller learns who won without parsing the + // message. The typed wrapper carries the fields; the PROSE is composed + // here, because ClaimConflictError.Error() passes its wrapped refusal + // through byte-for-byte — a bare sentinel would reach the caller as + // "issue already claimed" with the holder dropped and + // beads.ParseClaimConflict unable to recover it. The fragments are the + // storage layer's exported ones, which is what keeps the parser and + // this producer in step. The sentinel stays matchable through both + // wraps, which errors.Is, ParseClaimConflict and the proxied batch + // exit code all key on. + refusal := fmt.Errorf("%w%s%s", storage.ErrNotClaimable, storage.NotClaimableStatusFragment, currentStatus) if assignee != "" && assignee != actor { + switch { // A pool-assigned issue reaches here only when the CAS lost for a // non-assignee reason (status changed underneath us): report the - // status rather than a misleading held-by-someone refusal. - if slices.Contains(pools, assignee) { - return nil, fmt.Errorf("%w%s%s", storage.ErrNotClaimable, storage.NotClaimableStatusFragment, currentStatus) - } - if currentStatus == types.StatusOpen { + // status rather than a misleading held-by-someone refusal. Checked + // FIRST, so a pool alias never falls into the holder-steering copy. + case slices.Contains(pools, assignee): + // refusal already names the status. + case currentStatus == types.StatusOpen: // Do not name a release command here — not `bd unclaim`, not // `bd unclaim --force`. Refusal copy that names one gets // pattern-matched by batch agents into an unclaim+claim // steamroller of live claims (wy-yuclk). Point at the holder; // bd reclaim is safe to name because it only recovers claims - // whose lease has already expired. Keep the %w wrap so this - // open-but-assigned refusal is still a classifiable claim - // conflict: the public IssueClaimer contract promises wrapped - // ErrAlreadyClaimed, and errors.Is / ParseClaimConflict (and the - // proxied batch exit code) key on it. This mirrors the - // domain-stack twin (domain.issueUseCaseImpl.claim, bd-at6rc), - // which already wraps the same message. - return nil, fmt.Errorf("%w: already assigned to %q — coordinate with the holder; if their claim is abandoned (crashed agent), lease expiry will surface it for bd reclaim", storage.ErrAlreadyClaimed, assignee) + // whose lease has already expired. + // + // This copy deliberately omits the parseable " by " + // tail, so ParseClaimConflict recovers the holder from the + // typed field rather than the prose (bd-at6rc). + refusal = fmt.Errorf("%w: already assigned to %q — coordinate with the holder; if their claim is abandoned (crashed agent), lease expiry will surface it for bd reclaim", storage.ErrAlreadyClaimed, assignee) + default: + refusal = fmt.Errorf("%w%s%s", storage.ErrAlreadyClaimed, storage.ClaimedByFragment, assignee) } - return nil, fmt.Errorf("%w%s%s", storage.ErrAlreadyClaimed, storage.ClaimedByFragment, assignee) } - return nil, fmt.Errorf("%w%s%s", storage.ErrNotClaimable, storage.NotClaimableStatusFragment, currentStatus) + return nil, &publicops.ClaimConflictError{ + IssueID: id, + Assignee: assignee, + Status: currentStatus, + Err: refusal, + } } // Grant the lease: what makes the claim recoverable — a worker that dies diff --git a/internal/storage/issueops/claim_next.go b/internal/storage/issueops/claim_next.go new file mode 100644 index 000000000..11514dd41 --- /dev/null +++ b/internal/storage/issueops/claim_next.go @@ -0,0 +1,112 @@ +package issueops + +import ( + "context" + "database/sql" + "fmt" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// ClaimNextCommitMessage names the claim in the Dolt commit message, matching +// what the CLI's own per-command commit wrote before the claim moved onto the +// role. It is the only spelling: the id it names is the one the claim WON, so +// no caller could have composed it before the call. +func ClaimNextCommitMessage(issueID string) string { + return "bd: claim ready " + issueID +} + +// ValidateClaimNextRequest applies the request rules every ReadyClaimer +// implementation shares. It lives here rather than in each of them because a +// rule enforced on one backend and not the other is not a contract. +func ValidateClaimNextRequest(request publicops.ClaimNextRequest) error { + if request.Actor == "" { + return fmt.Errorf("%w: claim next requires an actor", storage.ErrValidation) + } + if request.Filter.Limit != nil { + return fmt.Errorf("%w: claim next does not take a limit", storage.ErrValidation) + } + if request.Filter.Offset != 0 { + return fmt.Errorf("%w: claim next does not take an offset", storage.ErrValidation) + } + return nil +} + +// ExecuteClaimNext claims the first ready issue matching filter in tx, hydrates +// it in that same transaction, and reports the durable tables changed. +// +// It takes the filter rather than the public request because this package +// speaks WorkFilter: the request-to-filter translation is internal/workapi's, +// and the same builder that answers Reader.Ready is what the accessor +// implementations run before calling in here. That is what keeps the claim's +// predicate and the listing's predicate the same predicate. +// +// A nil claim with a nil error is the ordinary empty-front outcome. It reports +// no changed tables, so the caller's transaction commits nothing and no +// history entry is recorded. +func ExecuteClaimNext(ctx context.Context, tx *sql.Tx, actor string, filter types.WorkFilter) (publicops.ClaimNextResult, ChangedTables, error) { + claimed, err := ClaimReadyIssueInTx(ctx, tx, filter, actor) + if err != nil { + return publicops.ClaimNextResult{}, nil, err + } + if claimed == nil { + return publicops.ClaimNextResult{}, nil, nil + } + hydrated, err := HydrateReadyRowInTx(ctx, tx, claimed) + if err != nil { + return publicops.ClaimNextResult{}, nil, err + } + tables := ChangedTables{} + tables.Add("issues", "events") + return publicops.ClaimNextResult{Claimed: hydrated}, tables, nil +} + +// HydrateReadyRowInTx fills in the relationship cardinalities a ready row +// carries, reading them in the caller's transaction so the counts describe the +// state that transaction is about to commit. +// +// A failed count read is an error rather than a zero. The CLI's pre-role +// hydration swallowed all three, which meant a broken database reported a +// claimed issue with no dependencies rather than saying the read failed; here +// the whole claim rolls back instead, because a result nobody can hydrate is +// not a result. +func HydrateReadyRowInTx(ctx context.Context, tx *sql.Tx, issue *types.Issue) (*types.IssueWithCounts, error) { + if issue == nil { + return nil, nil + } + ids := []string{issue.ID} + depCounts, err := GetDependencyCountsInTx(ctx, tx, ids) + if err != nil { + return nil, fmt.Errorf("hydrate ready row %s: dependency counts: %w", issue.ID, err) + } + records, err := GetDependencyRecordsForIssuesInTx(ctx, tx, ids) + if err != nil { + return nil, fmt.Errorf("hydrate ready row %s: dependency records: %w", issue.ID, err) + } + commentCounts, err := GetCommentCountsInTx(ctx, tx, ids) + if err != nil { + return nil, fmt.Errorf("hydrate ready row %s: comment counts: %w", issue.ID, err) + } + + issue.Dependencies = records[issue.ID] + counts := depCounts[issue.ID] + if counts == nil { + counts = &types.DependencyCounts{} + } + var parent *string + for _, dep := range records[issue.ID] { + if dep.Type == types.DepParentChild { + parent = &dep.DependsOnID + break + } + } + return &types.IssueWithCounts{ + Issue: issue, + DependencyCount: counts.DependencyCount, + DependentCount: counts.DependentCount, + CommentCount: commentCounts[issue.ID], + Parent: parent, + }, nil +} diff --git a/internal/storage/issueops/close_batch.go b/internal/storage/issueops/close_batch.go new file mode 100644 index 000000000..5fce1ff91 --- /dev/null +++ b/internal/storage/issueops/close_batch.go @@ -0,0 +1,156 @@ +package issueops + +import ( + "context" + "database/sql" + "fmt" + "strings" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// ValidateCloseBatchRequest applies the request rules every BatchCloser +// implementation shares, so a rule is a contract rather than one backend's +// habit. It rejects the request outright; a per-item refusal is a result, not +// a validation failure, and never reaches here. +func ValidateCloseBatchRequest(request publicops.CloseBatchRequest) error { + if request.Actor == "" { + return fmt.Errorf("%w: close batch requires an actor", storage.ErrValidation) + } + if len(request.Items) == 0 { + return fmt.Errorf("%w: close batch requires at least one item", storage.ErrValidation) + } + for i, item := range request.Items { + if item.IssueID == "" { + return fmt.Errorf("%w: close batch item %d requires an issue ID", storage.ErrValidation, i) + } + } + if request.ClaimNext != nil { + if err := ValidateClaimNextRequest(publicops.ClaimNextRequest{Actor: request.Actor, Filter: *request.ClaimNext}); err != nil { + return err + } + } + return nil +} + +// CloseBatchCommitMessage is the history entry a batch records. It is the +// only spelling — the request carries no label to override it, and could not +// compose this one, because it names what LANDED rather than what was asked for, +// which is why it is composed from the result and not from the request: a +// batch that skipped a mistyped id must not claim it in the log. +// +// LANDED is Changed, not "no error": an idempotent re-close persisted nothing, +// so naming it would put an id in `bd dolt log` under a commit that did not +// touch it. +// +// IT NAMES DURABLE LANDINGS ONLY. The wisp tables are dolt-ignored precisely so +// ephemeral work never ships, so an entry naming a wisp is the sync artifact +// ignoring them exists to prevent (issueops/batchcloser.go:128-135). An +// ephemeral landing is reported as a COUNT instead of being dropped, because +// the message is also the callers' commit-or-not signal: the unit-of-work +// backend reads "" as "roll this attempt back", and a batch that closed a wisp +// and nothing else must still keep the close (measured — a durable-only message +// leaves the wisp open there). +// +// It returns "" when nothing landed, which is how the callers spell "commit +// nothing" — a batch that wrote nothing records no history entry. +func CloseBatchCommitMessage(result publicops.CloseBatchResult) string { + ids := make([]string, 0, len(result.Outcomes)) + ephemeral := 0 + for _, outcome := range result.Outcomes { + if outcome.Err != nil || !outcome.Changed { + continue + } + if closeOutcomeIsEphemeral(outcome) { + ephemeral++ + continue + } + ids = append(ids, outcome.IssueID) + } + + var parts []string + switch { + case len(ids) > 0: + parts = append(parts, "close "+strings.Join(ids, ", ")) + case ephemeral == 1: + parts = append(parts, "close 1 ephemeral item") + case ephemeral > 1: + parts = append(parts, fmt.Sprintf("close %d ephemeral items", ephemeral)) + } + if result.ClaimedNext != nil { + parts = append(parts, "claim "+result.ClaimedNext.ID) + } + if len(parts) == 0 { + return "" + } + return "bd: " + strings.Join(parts, "; ") +} + +// closeOutcomeIsEphemeral reports whether this landing was on the wisps plane, +// read off the snapshot the close hydrated rather than off a flag the outcome +// does not carry. +// +// A nil Issue counts as DURABLE. The role contract pins Issue non-nil whenever +// Err is nil, so this is unreachable; if it ever happens, naming an id is the +// safer of the two wrong answers, because the alternative silently shortens a +// message the unit-of-work backend reads as "commit nothing". +func closeOutcomeIsEphemeral(outcome publicops.CloseOutcome) bool { + return outcome.Issue != nil && IsWisp(outcome.Issue) +} + +// ExecuteCloseBatch closes every item it can in tx and reports the durable +// tables changed. It is the store-backed body behind the BatchCloser accessor; +// the unit-of-work provider has its own, for the same reason Lifecycle does. +// +// A per-item failure lands in that item's outcome and the loop CONTINUES — +// skipping a refused id and committing the survivors is what closing a list of +// issues has always done, and it is the behavior the CLI's per-id stderr +// reports. Only a request-level failure aborts, and it aborts by returning an +// error, which rolls the whole transaction back. +// +// claimFilter is request.ClaimNext already translated by the caller's request +// builder, because this package speaks WorkFilter. A nil filter skips the +// claim, and so does a batch in which nothing landed — landed meaning an item +// that CHANGED, so a batch whose items were all already closed earns no claim. +func ExecuteCloseBatch(ctx context.Context, tx *sql.Tx, request publicops.CloseBatchRequest, claimFilter *types.WorkFilter) (publicops.CloseBatchResult, ChangedTables, error) { + result := publicops.CloseBatchResult{Outcomes: make([]publicops.CloseOutcome, len(request.Items))} + tables := ChangedTables{} + landed := 0 + + for i, item := range request.Items { + closed, changedTables, err := ExecuteClose(ctx, tx, publicops.CloseRequest{ + Actor: request.Actor, + IssueID: item.IssueID, + Reason: item.Reason, + Session: request.Session, + Force: request.Force, + }) + if err != nil { + result.Outcomes[i] = publicops.CloseOutcome{IssueID: item.IssueID, Err: err} + continue + } + tables.Merge(changedTables) + if closed.Changed { + landed++ + } + result.Outcomes[i] = publicops.CloseOutcome{ + IssueID: item.IssueID, + Issue: closed.Issue, + Changed: closed.Changed, + OpenChildren: closed.OpenChildren, + } + } + + if claimFilter != nil && landed > 0 { + claim, claimTables, err := ExecuteClaimNext(ctx, tx, request.Actor, *claimFilter) + if err != nil { + return publicops.CloseBatchResult{}, nil, err + } + tables.Merge(claimTables) + result.ClaimedNext = claim.Claimed + } + + return result, tables, nil +} diff --git a/internal/storage/issueops/commenter.go b/internal/storage/issueops/commenter.go new file mode 100644 index 000000000..c64ee7b06 --- /dev/null +++ b/internal/storage/issueops/commenter.go @@ -0,0 +1,86 @@ +package issueops + +import ( + "context" + "database/sql" + "fmt" + "strings" + + "github.com/steveyegge/beads/internal/storage" + publicops "github.com/steveyegge/beads/issueops" +) + +// ValidateAddCommentRequest applies the request rules every Commenter +// implementation shares. +// +// Blankness is decided on a TRIMMED copy and the request's own Text is left +// alone: a comment of nothing but whitespace carries no information and is +// almost always a shell quoting accident, but a comment that merely begins +// with a newline is a comment. +func ValidateAddCommentRequest(request publicops.AddCommentRequest) error { + if request.Author == "" { + return fmt.Errorf("%w: add comment requires an author", storage.ErrValidation) + } + if request.IssueID == "" { + return fmt.Errorf("%w: add comment requires an issue ID", storage.ErrValidation) + } + if strings.TrimSpace(request.Text) == "" { + return fmt.Errorf("%w: comment text cannot be empty", storage.ErrValidation) + } + return nil +} + +// AddCommentCommitMessage is the history entry a comment records. It is the +// spelling both stores' own AddIssueComment already wrote. +func AddCommentCommitMessage(issueID string) string { + return "bd: comment " + issueID +} + +// ExecuteAddComment appends one comment in tx and reports the durable tables +// changed. It is the store-backed body behind the Commenter accessor; the +// unit-of-work provider has its own, for the reason Lifecycle does. +// +// A comment on an ephemeral row changes only wisp_comments, which +// ChangedTables drops, so the caller's transaction commits nothing and records +// no history entry: the wisp tables are dolt-ignored and there is nothing to +// version. +func ExecuteAddComment(ctx context.Context, tx *sql.Tx, request publicops.AddCommentRequest) (publicops.AddCommentResult, ChangedTables, error) { + commentTable, err := resolveCommentPlaneInTx(ctx, tx, request.IssueID) + if err != nil { + return publicops.AddCommentResult{}, nil, err + } + comment, err := AddIssueCommentInTx(ctx, tx, request.IssueID, request.Author, request.Text) + if err != nil { + return publicops.AddCommentResult{}, nil, err + } + tables := ChangedTables{} + tables.Add(commentTable) + return publicops.AddCommentResult{Comment: comment}, tables, nil +} + +// resolveCommentPlaneInTx names the comment table the anchor's thread lives in, +// refusing an id that names neither an issue nor a wisp. +// +// The existence probe is here rather than left to the insert's own so the +// refusal is TYPED: AddIssueCommentInTx reports a missing anchor as prose, and +// a caller of this role classifies with errors.Is. It resolves the plane in +// the same transaction the insert runs in, so a comment cannot land on a row +// an earlier read saw and this one did not. +// +//nolint:gosec // G201: issueTable comes from WispTableRouting ("issues" or "wisps") +func resolveCommentPlaneInTx(ctx context.Context, tx *sql.Tx, issueID string) (string, error) { + isWisp := IsActiveWispInTx(ctx, tx, issueID) + issueTable, _, _, _ := WispTableRouting(isWisp) + var exists bool + if err := tx.QueryRowContext(ctx, + fmt.Sprintf(`SELECT EXISTS(SELECT 1 FROM %s WHERE id = ?)`, issueTable), issueID).Scan(&exists); err != nil { + return "", fmt.Errorf("check issue existence: %w", err) + } + if !exists { + return "", fmt.Errorf("%w: issue %s", storage.ErrNotFound, issueID) + } + if isWisp { + return "wisp_comments", nil + } + return "comments", nil +} diff --git a/internal/storage/issueops/dependencies.go b/internal/storage/issueops/dependencies.go index 5533279ee..5b6efb8d0 100644 --- a/internal/storage/issueops/dependencies.go +++ b/internal/storage/issueops/dependencies.go @@ -72,8 +72,25 @@ func depTargetIn(alias, placeholders string) string { return depTargetExpr(alias) + " IN (" + placeholders + ")" } +// IsExternalDepTarget reports whether a dependency target is one this database +// cannot hold a row for. Two shapes qualify: an "external:" reference, which +// names something outside beads entirely, and a target whose id prefix names +// ANOTHER REPOSITORY, which lives in that rig's database and not this one. +// Both belong in depends_on_external — the one target column carrying no +// foreign key into issues — so this is the single rule every backend must +// classify by, whether it writes through a tx (ClassifyDepTarget) or through +// the domain repository (db.pickDepTargetColumn). +func IsExternalDepTarget(sourceID, targetID string) bool { + return strings.HasPrefix(targetID, "external:") || + types.ExtractPrefix(sourceID) != types.ExtractPrefix(targetID) +} + +// ClassifyDepTarget picks the typed target column for an edge. isCrossPrefix is +// an override for callers that already know the answer from a cached prefix +// set; leaving it false is safe, because IsExternalDepTarget re-derives the +// same comparison from the edge itself. func ClassifyDepTarget(ctx context.Context, tx *sql.Tx, dep *types.Dependency, isCrossPrefix bool) DepTargetKind { - if isCrossPrefix || strings.HasPrefix(dep.DependsOnID, "external:") { + if isCrossPrefix || IsExternalDepTarget(dep.IssueID, dep.DependsOnID) { return DepTargetExternal } if IsActiveWispInTx(ctx, tx, dep.DependsOnID) { diff --git a/internal/storage/issueops/dependency_editor.go b/internal/storage/issueops/dependency_editor.go new file mode 100644 index 000000000..4571204fd --- /dev/null +++ b/internal/storage/issueops/dependency_editor.go @@ -0,0 +1,264 @@ +package issueops + +import ( + "context" + "database/sql" + "fmt" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// ValidateAddDependenciesRequest applies the request rules every +// DependencyEditor implementation shares. It lives here rather than in each of +// them because a rule enforced on one backend and not the other is not a +// contract. +// +// The self-dependency refusal is here, ahead of the per-edge cycle probe and +// for EVERY edge type, for the reason the domain path states: a blocking +// self-edge otherwise trips the cycle check and reports the wrong refusal, and +// SkipPerEdgeCycleCheck would skip it entirely. +// +// The type check is that there IS a type — non-empty, within the column's +// length. It is deliberately not a membership test: the vocabulary is an open, +// workspace-configurable set (see the Dep* constants), so refusing an unlisted +// type would refuse a workspace's own. +func ValidateAddDependenciesRequest(request publicops.AddDependenciesRequest) error { + if request.Actor == "" { + return fmt.Errorf("%w: add dependencies requires an actor", storage.ErrValidation) + } + if len(request.Edges) == 0 { + return fmt.Errorf("%w: add dependencies requires at least one edge", storage.ErrValidation) + } + for i, edge := range request.Edges { + if edge.IssueID == "" || edge.DependsOnID == "" { + return fmt.Errorf("%w: add dependencies edge %d requires both endpoints", storage.ErrValidation, i) + } + if !edge.Type.IsValid() { + return fmt.Errorf("%w: add dependencies edge %d requires a dependency type (max %d chars)", + storage.ErrValidation, i, types.MaxDependencyTypeLen) + } + if edge.IssueID == edge.DependsOnID { + return fmt.Errorf("%w: %s cannot depend on itself", domain.ErrSelfDependency, edge.IssueID) + } + } + return nil +} + +// ValidateRemoveDependencyRequest applies the request rules every +// DependencyEditor implementation shares for a removal. +func ValidateRemoveDependencyRequest(request publicops.RemoveDependencyRequest) error { + if request.Actor == "" { + return fmt.Errorf("%w: remove dependency requires an actor", storage.ErrValidation) + } + if request.IssueID == "" || request.DependsOnID == "" { + return fmt.Errorf("%w: remove dependency requires both endpoints", storage.ErrValidation) + } + return nil +} + +// AddDependenciesCommitMessage is the history entry an edge assertion records. +// +// Unlike CloseBatchCommitMessage it is composed from the REQUEST rather than +// the result, and that difference is the contract's: the request is +// all-or-nothing, so what was asked for is exactly what landed or nothing did. +// A batch close has to name what landed because it can skip an id; this cannot. +// +// The two spellings are the two the CLI already wrote — one edge names both +// endpoints, several name their count — because the role is what both `bd dep +// add ` and `bd dep add --file` now go through, and `bd dolt log` should +// keep reading the way it did. The count spelling is keyed on the EDGE COUNT +// and not on which flag was used, so a one-line bulk file now names its edge +// instead of reading "add 1 edges": one edge is one edge however it was +// spelled. +func AddDependenciesCommitMessage(request publicops.AddDependenciesRequest) string { + if len(request.Edges) == 1 { + return "bd: dep add " + request.Edges[0].IssueID + " " + request.Edges[0].DependsOnID + } + return fmt.Sprintf("dependency: add %d edges", len(request.Edges)) +} + +// RemoveDependencyCommitMessage is the history entry a removal records. +func RemoveDependencyCommitMessage(issueID, dependsOnID string) string { + return "bd: dep remove " + issueID + " " + dependsOnID +} + +// ExecuteAddDependencies asserts every requested edge in tx and reports the +// durable tables changed. It is the store-backed body behind the +// DependencyEditor accessor; the unit-of-work provider has its own, for the +// reason Lifecycle does. +// +// ALL-OR-NOTHING is enforced by doing nothing special: the first refusal +// returns an error, and the caller's transaction rolls every earlier edge back +// with it. There is no per-edge outcome to report because there is no outcome +// but the request's. +// +// Edges are applied PARENT-CHILD FIRST regardless of request order, so the +// complete planned hierarchy is visible before any blocking edge is validated +// against it — an ordering the direct bulk path already relies on. The +// whole-graph gate at the end runs even when the per-edge probe was skipped: +// per-edge checks cannot see a path that only exists once several of this +// request's own edges are in place. +// +// Both orderings hold ACROSS THE TWO PLANES, not within each: a request may +// mix wisp-sourced and issue-sourced edges, and the hierarchy a blocking edge +// is validated against, like the graph the final gate walks, spans both +// tables. That is why the phase loop and the gate are over the whole request +// and the plane is decided per edge, one level down. +func ExecuteAddDependencies(ctx context.Context, tx *sql.Tx, request publicops.AddDependenciesRequest) (publicops.AddDependenciesResult, ChangedTables, error) { + // One scoped query for the whole request instead of a probe per edge: a + // bulk `bd dep add --file` against a remote Dolt pays WAN latency per + // round-trip (GH#3414). Nothing an edge write does moves a source between + // planes, so a set read once up front stays true for the transaction. + sources := make([]string, 0, len(request.Edges)) + for _, edge := range request.Edges { + sources = append(sources, edge.IssueID) + } + wispSources, err := WispIDSetInTx(ctx, tx, sources) + if err != nil { + return publicops.AddDependenciesResult{}, nil, err + } + + tables := ChangedTables{} + for phase := 0; phase < 2; phase++ { + parentPhase := phase == 0 + for _, edge := range request.Edges { + if (edge.Type == types.DepParentChild) != parentPhase { + continue + } + _, sourceIsWisp := wispSources[edge.IssueID] + edgeTables, err := addDependencyEdgeInTx(ctx, tx, request, edge, sourceIsWisp) + if err != nil { + return publicops.AddDependenciesResult{}, nil, err + } + tables.Merge(edgeTables) + } + } + if err := checkAddedEdgesForCycles(ctx, tx, request.Edges); err != nil { + return publicops.AddDependenciesResult{}, nil, err + } + added := make([]publicops.DependencyEdge, len(request.Edges)) + copy(added, request.Edges) + return publicops.AddDependenciesResult{Added: added}, tables, nil +} + +// addDependencyEdgeInTx writes one edge and reports the durable tables it +// touched. +// +// The edge FOLLOWS ITS SOURCE, the same rule the removal reads and the same +// one the stores' own dependency verb applied before this role existed: a wisp +// has no row in the issues plane, so pinning the source there refused every +// `bd dep add ` with "issue not found". Source class decides +// the dependency table and, with it, the event table. The target's routing +// stays independently detected: either class may legitimately depend on the +// other. +// +// Refusals pass through UNWRAPPED. Every one of them — +// *DependencyTypeConflictError, *DependencyHierarchyConflictError, +// ErrDependencyCycle, a missing endpoint — is already a complete sentence, and +// the store's own dependency verb has always surfaced them verbatim. +func addDependencyEdgeInTx(ctx context.Context, tx *sql.Tx, request publicops.AddDependenciesRequest, edge publicops.DependencyEdge, sourceIsWisp bool) (ChangedTables, error) { + sourceTable, _, eventTable, depTable := WispTableRouting(sourceIsWisp) + + dep := &types.Dependency{IssueID: edge.IssueID, DependsOnID: edge.DependsOnID, Type: edge.Type} + eventWritten, err := AddDependencyInTx(ctx, tx, dep, request.Actor, AddDependencyOpts{ + SourceTable: sourceTable, + WriteTable: depTable, + IsCrossPrefix: types.ExtractPrefix(edge.IssueID) != types.ExtractPrefix(edge.DependsOnID), + SkipCycleCheck: request.SkipPerEdgeCycleCheck, + EmitEvent: true, + }) + if err != nil { + return nil, err + } + // Stage the source's dependency table always and its events table only + // when a row was recorded — the same selective staging the stores' own + // AddDependencyWithOptions does, so an idempotent re-add cannot sweep + // unrelated pending event rows into this commit (GH#2455). Naming the + // source's own pair rather than the durable pair is what keeps that true + // across the planes: ChangedTables drops the wisp tables itself, so a + // wisp-sourced edge stages nothing and a request made entirely of them + // commits nothing, which is right — the wisp plane is dolt-ignored and has + // no version history to write. + // + // This is NOT every table the edge wrote. A blocking edge also flips the + // source's is_blocked (markDirectBlockingDependencySourceInTx, then + // MarkIsBlockedInTx over the affected ids), and neither `issues` nor any + // other issue-plane table is ever staged here. On an issue-sourced + // blocking add the flip therefore stays in the working set and is swept up + // by whatever command auto-commits next — including one that was REFUSED, + // which then shows up in history having changed nothing of its own. That + // predates this role: origin/main's dolt.AddDependencyWithOptions staged + // the same {dependencies, events} pair. Tracked as bd-2y9ke; fixing it + // changes what every dep-add commit contains and belongs in its own change + // with its own tests, so do not widen the set here without reading that + // bead first. + tables := ChangedTables{} + tables.Add(depTable) + if eventWritten { + tables.Add(eventTable) + } + return tables, nil +} + +// checkAddedEdgesForCycles runs the whole-graph gate over the scheduling edges +// this request added. Per-edge probes cannot see a path that only closes once +// several of the request's own edges exist, and SkipPerEdgeCycleCheck turns +// them off entirely, so this is the check that actually holds the invariant. +// +// The message is built through domain.NewCycleError so it errors.Is-matches +// ErrDependencyCycle while rendering byte-for-byte what the direct bulk path +// already prints. +func checkAddedEdgesForCycles(ctx context.Context, tx *sql.Tx, edges []publicops.DependencyEdge) error { + var pairs [][2]string + for _, edge := range edges { + if !isSchedulingEdge(edge.Type) { + continue + } + pairs = append(pairs, [2]string{edge.IssueID, edge.DependsOnID}) + } + if len(pairs) == 0 { + return nil + } + graph := make(map[string][]string) + if err := AppendSchedulingGraphInTx(ctx, tx, cycleDetectionTables(), graph); err != nil { + return fmt.Errorf("final cycle check failed (no edges added): %w", err) + } + if cyclePath := CycleThroughEdgesInGraph(graph, pairs); cyclePath != "" { + return domain.NewCycleError("dependency cycle would be created: %s (no edges added; run 'bd dep cycles' for analysis)", cyclePath) + } + return nil +} + +// ExecuteRemoveDependency removes one edge in tx and reports the durable +// tables changed. +// +// A missing edge reports Removed false and NO changed tables, which is how the +// callers spell "commit nothing": removing an edge that was never there leaves +// the graph it already had, and a history entry for it would be a commit with +// nothing in it. +func ExecuteRemoveDependency(ctx context.Context, tx *sql.Tx, request publicops.RemoveDependencyRequest) (publicops.RemoveDependencyResult, ChangedTables, error) { + // Routing is READ here rather than pinned, unlike the add. A removal + // cannot put an edge anywhere, so pinning it would only mean failing to + // remove an edge the caller named — and the staging has to name the tables + // the delete actually touched or the commit sweeps rows it never wrote + // (GH#2455). ChangedTables drops the wisp tables itself. + sourceIsWisp := IsActiveWispInTx(ctx, tx, request.IssueID) + _, _, eventTable, depTable := WispTableRouting(sourceIsWisp) + + // RemoveDependencyInTx reports whether it recorded an event, which on the + // explicit-verb path is exactly "an edge was there and is gone" — it + // returns early without emitting when no row matched. + eventWritten, err := RemoveDependencyInTx(ctx, tx, request.IssueID, request.DependsOnID, request.Actor, true) + if err != nil { + return publicops.RemoveDependencyResult{}, nil, err + } + if !eventWritten { + return publicops.RemoveDependencyResult{Removed: false}, nil, nil + } + tables := ChangedTables{} + tables.Add(depTable, eventTable) + return publicops.RemoveDependencyResult{Removed: true}, tables, nil +} diff --git a/internal/storage/issueops/edge_role_requests_test.go b/internal/storage/issueops/edge_role_requests_test.go new file mode 100644 index 000000000..cb16c9d83 --- /dev/null +++ b/internal/storage/issueops/edge_role_requests_test.go @@ -0,0 +1,344 @@ +package issueops + +import ( + "errors" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +func edge(from, to string, depType types.DependencyType) publicops.DependencyEdge { + return publicops.DependencyEdge{IssueID: from, DependsOnID: to, Type: depType} +} + +func TestValidateAddDependenciesRequest(t *testing.T) { + valid := edge("bd-1", "bd-2", publicops.DepBlocks) + for _, tc := range []struct { + name string + request publicops.AddDependenciesRequest + wantErr bool + }{ + { + name: "one edge is valid", + request: publicops.AddDependenciesRequest{Actor: "worker", Edges: []publicops.DependencyEdge{valid}}, + }, + { + name: "missing actor", + request: publicops.AddDependenciesRequest{Edges: []publicops.DependencyEdge{valid}}, + wantErr: true, + }, + { + name: "no edges", + request: publicops.AddDependenciesRequest{Actor: "worker"}, + wantErr: true, + }, + { + name: "edge without a source", + request: publicops.AddDependenciesRequest{Actor: "worker", Edges: []publicops.DependencyEdge{edge("", "bd-2", publicops.DepBlocks)}}, + wantErr: true, + }, + { + name: "edge without a target", + request: publicops.AddDependenciesRequest{Actor: "worker", Edges: []publicops.DependencyEdge{edge("bd-1", "", publicops.DepBlocks)}}, + wantErr: true, + }, + { + name: "edge without a type", + request: publicops.AddDependenciesRequest{Actor: "worker", Edges: []publicops.DependencyEdge{edge("bd-1", "bd-2", "")}}, + wantErr: true, + }, + { + name: "edge with a type one character longer than the column", + request: publicops.AddDependenciesRequest{Actor: "worker", Edges: []publicops.DependencyEdge{edge("bd-1", "bd-2", types.DependencyType(strings.Repeat("x", types.MaxDependencyTypeLen+1)))}}, + wantErr: true, + }, + } { + t.Run(tc.name, func(t *testing.T) { + err := ValidateAddDependenciesRequest(tc.request) + if tc.wantErr != (err != nil) { + t.Fatalf("ValidateAddDependenciesRequest() error = %v, want error = %v", err, tc.wantErr) + } + if tc.wantErr && !errors.Is(err, storage.ErrValidation) { + t.Fatalf("ValidateAddDependenciesRequest() error = %v, want it to match ErrValidation", err) + } + }) + } +} + +// TestValidateAddDependenciesRequestAcceptsUnlistedTypes is the OWNER RULING +// as a test. The Dep* constants document an open, workspace-configurable set; +// they are not a whitelist. A validator that rejected a type merely because it +// is not one of them would refuse every workspace that configured its own, and +// it would do it at the contract boundary where nothing can route around it. +// +// The counterpart is the type check that DOES fire — that there is a type at +// all — pinned by the two cases above it. Membership is never asked about. +func TestValidateAddDependenciesRequestAcceptsUnlistedTypes(t *testing.T) { + for _, depType := range []types.DependencyType{ + "blocks-ish", // nothing like a built-in + "caused-by", // built-in, but deliberately absent from the leaf constants + types.DependencyType("私の型"), // a workspace that does not spell its vocabulary in ASCII + } { + request := publicops.AddDependenciesRequest{ + Actor: "worker", + Edges: []publicops.DependencyEdge{edge("bd-1", "bd-2", depType)}, + } + if err := ValidateAddDependenciesRequest(request); err != nil { + t.Fatalf("ValidateAddDependenciesRequest() with type %q error = %v, want the open set to accept it", depType, err) + } + } +} + +// TestValidateAddDependenciesRequestRefusesSelfEdges pins that the refusal is +// typed and that it fires ahead of any cycle probe. A blocking self-edge +// otherwise trips the cycle check and reports the wrong refusal, and +// SkipPerEdgeCycleCheck would skip the probe entirely — so this check cannot +// live inside it. +func TestValidateAddDependenciesRequestRefusesSelfEdges(t *testing.T) { + for _, skip := range []bool{false, true} { + request := publicops.AddDependenciesRequest{ + Actor: "worker", + Edges: []publicops.DependencyEdge{edge("bd-1", "bd-1", publicops.DepBlocks)}, + SkipPerEdgeCycleCheck: skip, + } + err := ValidateAddDependenciesRequest(request) + if !errors.Is(err, domain.ErrSelfDependency) { + t.Fatalf("ValidateAddDependenciesRequest(SkipPerEdgeCycleCheck=%v) error = %v, want ErrSelfDependency", skip, err) + } + } +} + +func TestValidateRemoveDependencyRequest(t *testing.T) { + for _, tc := range []struct { + name string + request publicops.RemoveDependencyRequest + wantErr bool + }{ + { + name: "both endpoints and an actor is valid", + request: publicops.RemoveDependencyRequest{Actor: "worker", IssueID: "bd-1", DependsOnID: "bd-2"}, + }, + { + name: "missing actor", + request: publicops.RemoveDependencyRequest{IssueID: "bd-1", DependsOnID: "bd-2"}, + wantErr: true, + }, + { + name: "missing source", + request: publicops.RemoveDependencyRequest{Actor: "worker", DependsOnID: "bd-2"}, + wantErr: true, + }, + { + name: "missing target", + request: publicops.RemoveDependencyRequest{Actor: "worker", IssueID: "bd-1"}, + wantErr: true, + }, + } { + t.Run(tc.name, func(t *testing.T) { + err := ValidateRemoveDependencyRequest(tc.request) + if tc.wantErr != (err != nil) { + t.Fatalf("ValidateRemoveDependencyRequest() error = %v, want error = %v", err, tc.wantErr) + } + if tc.wantErr && !errors.Is(err, storage.ErrValidation) { + t.Fatalf("ValidateRemoveDependencyRequest() error = %v, want it to match ErrValidation", err) + } + }) + } +} + +// TestAddDependenciesCommitMessageNamesTheRequest pins the two spellings the +// CLI already wrote, and the reason this message is composed from the REQUEST +// where the batch close's is composed from its result: the request is +// all-or-nothing, so what was asked for is exactly what landed. +func TestAddDependenciesCommitMessageNamesTheRequest(t *testing.T) { + for _, tc := range []struct { + name string + request publicops.AddDependenciesRequest + want string + }{ + { + name: "one edge names both endpoints", + request: publicops.AddDependenciesRequest{Edges: []publicops.DependencyEdge{edge("bd-1", "bd-2", publicops.DepBlocks)}}, + want: "bd: dep add bd-1 bd-2", + }, + { + name: "several edges name their count", + request: publicops.AddDependenciesRequest{Edges: []publicops.DependencyEdge{ + edge("bd-1", "bd-2", publicops.DepBlocks), edge("bd-3", "bd-4", publicops.DepParentChild), + }}, + want: "dependency: add 2 edges", + }, + } { + t.Run(tc.name, func(t *testing.T) { + if got := AddDependenciesCommitMessage(tc.request); got != tc.want { + t.Fatalf("AddDependenciesCommitMessage() = %q, want %q", got, tc.want) + } + }) + } +} + +func TestValidateAddCommentRequest(t *testing.T) { + for _, tc := range []struct { + name string + request publicops.AddCommentRequest + wantErr bool + }{ + { + name: "author, issue and text is valid", + request: publicops.AddCommentRequest{Author: "worker", IssueID: "bd-1", Text: "hi"}, + }, + { + name: "missing author", + request: publicops.AddCommentRequest{IssueID: "bd-1", Text: "hi"}, + wantErr: true, + }, + { + name: "missing issue", + request: publicops.AddCommentRequest{Author: "worker", Text: "hi"}, + wantErr: true, + }, + { + name: "empty text", + request: publicops.AddCommentRequest{Author: "worker", IssueID: "bd-1"}, + wantErr: true, + }, + { + name: "whitespace-only text", + request: publicops.AddCommentRequest{Author: "worker", IssueID: "bd-1", Text: " \n\t "}, + wantErr: true, + }, + { + // Blankness is decided on a trimmed copy; the value that lands in + // the row is not trimmed, so leading whitespace is content. + name: "text that merely starts blank is content", + request: publicops.AddCommentRequest{Author: "worker", IssueID: "bd-1", Text: "\n still a comment"}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + err := ValidateAddCommentRequest(tc.request) + if tc.wantErr != (err != nil) { + t.Fatalf("ValidateAddCommentRequest() error = %v, want error = %v", err, tc.wantErr) + } + if tc.wantErr && !errors.Is(err, storage.ErrValidation) { + t.Fatalf("ValidateAddCommentRequest() error = %v, want it to match ErrValidation", err) + } + }) + } +} + +// TestValidateRelatedRequestRefusesTheZeroDirection is the rule that makes the +// neighbor query honest. "out" and "in" answer inverse questions with +// identical shapes, so a defaulted direction hands a caller the wrong graph +// with nothing to notice. +func TestValidateRelatedRequestRefusesTheZeroDirection(t *testing.T) { + for _, tc := range []struct { + name string + request publicops.RelatedRequest + wantErr bool + }{ + { + name: "out is valid", + request: publicops.RelatedRequest{ID: "bd-1", Direction: publicops.RelationOut}, + }, + { + name: "in is valid", + request: publicops.RelatedRequest{ID: "bd-1", Direction: publicops.RelationIn}, + }, + { + name: "the zero direction is refused, not defaulted", + request: publicops.RelatedRequest{ID: "bd-1"}, + wantErr: true, + }, + { + name: "an unknown direction is refused", + request: publicops.RelatedRequest{ID: "bd-1", Direction: publicops.RelationDirection("both")}, + wantErr: true, + }, + { + name: "missing id", + request: publicops.RelatedRequest{Direction: publicops.RelationOut}, + wantErr: true, + }, + { + name: "an unusable type entry is refused", + request: publicops.RelatedRequest{ID: "bd-1", Direction: publicops.RelationOut, Types: []types.DependencyType{""}}, + wantErr: true, + }, + { + // The open set again: a filter has to be able to name a type this + // build has never heard of, or a workspace cannot filter by its own. + name: "an unlisted type entry filters", + request: publicops.RelatedRequest{ID: "bd-1", Direction: publicops.RelationOut, + Types: []types.DependencyType{"blocks-ish"}}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + err := ValidateRelatedRequest(tc.request) + if tc.wantErr != (err != nil) { + t.Fatalf("ValidateRelatedRequest() error = %v, want error = %v", err, tc.wantErr) + } + if tc.wantErr && !errors.Is(err, storage.ErrValidation) { + t.Fatalf("ValidateRelatedRequest() error = %v, want it to match ErrValidation", err) + } + }) + } +} + +// TestFinishRelatedPagePinsTheOrder covers the ordering both Relations +// implementations answer in. The underlying reads walk two dependency tables +// in sequence, so without this the order tracks which plane a neighbor +// happens to live on. +func TestFinishRelatedPagePinsTheOrder(t *testing.T) { + related := func(id string, depType types.DependencyType) *types.IssueWithDependencyMetadata { + return &types.IssueWithDependencyMetadata{ + Issue: types.Issue{ID: id}, + DependencyType: depType, + } + } + items := []*types.IssueWithDependencyMetadata{ + related("bd-9", publicops.DepBlocks), + related("bd-1", publicops.DepRelated), + related("bd-1", publicops.DepBlocks), + related("bd-5", publicops.DepParentChild), + } + + got := FinishRelatedPage(items, nil) + want := []string{"bd-1/blocks", "bd-1/related", "bd-5/parent-child", "bd-9/blocks"} + if keys := relatedKeys(got); !equalStrings(keys, want) { + t.Fatalf("FinishRelatedPage() order = %v, want %v", keys, want) + } + + filtered := FinishRelatedPage(items, []types.DependencyType{publicops.DepBlocks}) + want = []string{"bd-1/blocks", "bd-9/blocks"} + if keys := relatedKeys(filtered); !equalStrings(keys, want) { + t.Fatalf("FinishRelatedPage(blocks) = %v, want %v", keys, want) + } + + if empty := FinishRelatedPage(nil, nil); empty == nil { + t.Fatal("FinishRelatedPage(nil) = nil, want an empty slice so a marshalled answer is [] and not null") + } +} + +func relatedKeys(items []*types.IssueWithDependencyMetadata) []string { + keys := make([]string, 0, len(items)) + for _, item := range items { + keys = append(keys, item.ID+"/"+string(item.DependencyType)) + } + return keys +} + +func equalStrings(got, want []string) bool { + if len(got) != len(want) { + return false + } + for i := range got { + if got[i] != want[i] { + return false + } + } + return true +} diff --git a/internal/storage/issueops/execution.go b/internal/storage/issueops/execution.go index cb5850e2c..c0c09eb79 100644 --- a/internal/storage/issueops/execution.go +++ b/internal/storage/issueops/execution.go @@ -11,6 +11,22 @@ import ( publicops "github.com/steveyegge/beads/issueops" ) +// HistoryEntry names the version-control entry a guarded mutation records: the +// caller's own provenance label when it supplied one, otherwise the +// implementation's default. It decides how the entry READS, never whether one +// is recorded — that stays a question about what the mutation wrote. +// +// Every guarded mutation whose request carries a label calls this. Create is +// the one that does not: no surface has ever named the created issue in its +// commit message, so CreateRequest carries no label to spell and adding one +// would be a field with no caller. +func HistoryEntry(provenance, fallback string) string { + if provenance != "" { + return provenance + } + return fallback +} + // ExecuteCreate applies a guarded create in tx and reports durable tables changed. func ExecuteCreate(ctx context.Context, tx *sql.Tx, request publicops.CreateRequest) (publicops.CreateResult, ChangedTables, error) { attempt := CloneCreateRequest(request) @@ -111,6 +127,12 @@ func ExecuteUpdate(ctx context.Context, tx *sql.Tx, request publicops.UpdateRequ if err := ValidateMetadataPatch(attempt.Patch.Metadata); err != nil { return publicops.UpdateResult{}, nil, err } + // The plane restriction is resolved HERE, inside the update's own + // transaction, so a caller that serves durable issues only cannot be handed + // a wisp by a resolve that ran earlier. + if attempt.IssuePlaneOnly && IsActiveWispInTx(ctx, tx, attempt.IssueID) { + return publicops.UpdateResult{}, nil, fmt.Errorf("%w: issue %s", storage.ErrNotFound, attempt.IssueID) + } tables := ChangedTables{} before, err := GetIssueInTx(ctx, tx, attempt.IssueID) if err != nil { diff --git a/internal/storage/issueops/public_create_test.go b/internal/storage/issueops/public_create_test.go index af76de060..2c486e5d7 100644 --- a/internal/storage/issueops/public_create_test.go +++ b/internal/storage/issueops/public_create_test.go @@ -152,6 +152,51 @@ func TestValidatePublicCreateRequestAllowsEmptyWaitsForGate(t *testing.T) { } } +// TestValidatePublicCreateRequestRejectsUnknownWaitsForGate is the other half +// of the clause above: the leaf says an empty Gate defaults to +// WaitsForAllChildren and that "otherwise only the exported waits-for gate +// constants are valid" (issueops/issueops.go:149-152). Only the permissive +// half was pinned, so an unknown gate could have started defaulting silently — +// which is a readiness primitive quietly answering the wrong question rather +// than refusing. +// +// This lives at the shared validator rather than in the conformance contract +// because all three Lifecycle backends reach it: the two stores through +// ExecuteCreate and the unit-of-work one through its own Create +// (internal/storage/uow/issue_operations.go:64). +func TestValidatePublicCreateRequestRejectsUnknownWaitsForGate(t *testing.T) { + for _, gate := range []string{"bogus", "ALL_CHILDREN", " all_children"} { + t.Run(gate, func(t *testing.T) { + err := ValidatePublicCreateRequest(publicops.CreateRequest{ + Actor: "a", + Issue: &publicops.Issue{Title: "x"}, + WaitsFor: &publicops.WaitsFor{SpawnerID: "bd-spawner", Gate: gate}, + }) + if !errors.Is(err, storage.ErrValidation) { + t.Fatalf("ValidatePublicCreateRequest() with gate %q error = %v, want ErrValidation", gate, err) + } + }) + } +} + +// TestValidatePublicCreateRequestAcceptsTheExportedWaitsForGates keeps the +// refusal above honest: the two exported constants must still pass, so the +// check cannot be tightened into rejecting everything. +func TestValidatePublicCreateRequestAcceptsTheExportedWaitsForGates(t *testing.T) { + for _, gate := range []string{string(publicops.WaitsForAllChildren), string(publicops.WaitsForAnyChildren)} { + t.Run(gate, func(t *testing.T) { + err := ValidatePublicCreateRequest(publicops.CreateRequest{ + Actor: "a", + Issue: &publicops.Issue{Title: "x"}, + WaitsFor: &publicops.WaitsFor{SpawnerID: "bd-spawner", Gate: gate}, + }) + if err != nil { + t.Fatalf("ValidatePublicCreateRequest() with gate %q error = %v, want nil", gate, err) + } + }) + } +} + func TestValidatePublicCreateRequestRejectsInvalidImportedRelations(t *testing.T) { checks := []struct { name string diff --git a/internal/storage/issueops/relations.go b/internal/storage/issueops/relations.go new file mode 100644 index 000000000..2344683c3 --- /dev/null +++ b/internal/storage/issueops/relations.go @@ -0,0 +1,130 @@ +package issueops + +import ( + "context" + "fmt" + "sort" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// ValidateRelatedRequest applies the request rules every Relations +// implementation shares. +// +// The direction check is the load-bearing one: the zero value is refused +// rather than defaulted, because "out" and "in" answer inverse questions with +// identical shapes and a caller handed the wrong one has nothing to notice. +// +// A Types entry is checked for being a value at all — non-empty, within the +// column's length — and NEVER for membership of a known-types list. The +// vocabulary is an open, workspace-configurable set (see the Dep* constants), +// so a workspace's own type has to be able to filter; what is refused is an +// entry no edge could ever carry, which would otherwise be a filter that +// silently matches nothing. +func ValidateRelatedRequest(request publicops.RelatedRequest) error { + if request.ID == "" { + return fmt.Errorf("%w: related requires an issue ID", storage.ErrValidation) + } + switch request.Direction { + case publicops.RelationOut, publicops.RelationIn: + default: + return fmt.Errorf("%w: related requires a direction (%q or %q), and has no default", + storage.ErrValidation, publicops.RelationOut, publicops.RelationIn) + } + for i, depType := range request.Types { + if !depType.IsValid() { + return fmt.Errorf("%w: related type %d is not a usable dependency type (non-empty, max %d chars)", + storage.ErrValidation, i, types.MaxDependencyTypeLen) + } + } + return nil +} + +// ExecuteRelated returns the anchor's neighbors in tx. It is the store-backed +// body behind the Relations accessor; the unit-of-work provider has its own, +// which reaches the same two queries through its dependency use case. +// +// The anchor's EXISTENCE is checked first, on both planes, because an empty +// neighbor list is otherwise indistinguishable from a typo — and the empty +// list is the common case, so the typo would never surface. +func ExecuteRelated(ctx context.Context, tx DBTX, request publicops.RelatedRequest) ([]*types.IssueWithDependencyMetadata, error) { + if err := RequireIssueOrWispInTx(ctx, tx, request.ID); err != nil { + return nil, err + } + var ( + items []*types.IssueWithDependencyMetadata + err error + ) + if request.Direction == publicops.RelationIn { + items, err = GetDependentsWithMetadataInTx(ctx, tx, request.ID) + } else { + items, err = GetDependenciesWithMetadataInTx(ctx, tx, request.ID) + } + if err != nil { + return nil, err + } + return FinishRelatedPage(items, request.Types), nil +} + +// RequireIssueOrWispInTx refuses an id that names neither an issue nor a wisp, +// with the typed ErrNotFound a caller classifies on. It probes the two planes +// the way IsActiveWispInTx routes them, so an anchor cannot be reported +// missing on one plane while existing on the other. +func RequireIssueOrWispInTx(ctx context.Context, tx DBTX, id string) error { + for _, table := range []string{"issues", "wisps"} { + var exists bool + //nolint:gosec // G201: table is one of two hardcoded literals + err := tx.QueryRowContext(ctx, fmt.Sprintf(`SELECT EXISTS(SELECT 1 FROM %s WHERE id = ?)`, table), id).Scan(&exists) + if err != nil { + if isTableNotExistError(err) { + continue + } + return fmt.Errorf("check issue existence in %s: %w", table, err) + } + if exists { + return nil + } + } + return fmt.Errorf("%w: issue %s", storage.ErrNotFound, id) +} + +// FinishRelatedPage applies the type filter and the pinned order both +// Relations implementations answer in. It is one function rather than two +// copies for the reason workapi.FinishPage is: an ordering that each +// implementation applies for itself is an ordering the two will eventually +// disagree about. +// +// THE ORDER is ascending by the neighbor's id, with the edge type breaking a +// tie. The underlying reads walk the durable and wisp dependency tables in +// sequence, so their natural order tracks which plane a neighbor happens to +// live on — stable enough to look deliberate and not stable enough to rely on. +// +// The result is never nil, so a caller that marshals it emits an empty array +// rather than null. +func FinishRelatedPage(items []*types.IssueWithDependencyMetadata, depTypes []types.DependencyType) []*types.IssueWithDependencyMetadata { + out := make([]*types.IssueWithDependencyMetadata, 0, len(items)) + allowed := make(map[types.DependencyType]struct{}, len(depTypes)) + for _, depType := range depTypes { + allowed[depType] = struct{}{} + } + for _, item := range items { + if item == nil { + continue + } + if len(allowed) > 0 { + if _, ok := allowed[item.DependencyType]; !ok { + continue + } + } + out = append(out, item) + } + sort.SliceStable(out, func(i, j int) bool { + if out[i].ID != out[j].ID { + return out[i].ID < out[j].ID + } + return out[i].DependencyType < out[j].DependencyType + }) + return out +} diff --git a/internal/storage/issueops/role_requests_test.go b/internal/storage/issueops/role_requests_test.go new file mode 100644 index 000000000..b814fffac --- /dev/null +++ b/internal/storage/issueops/role_requests_test.go @@ -0,0 +1,192 @@ +package issueops + +import ( + "errors" + "testing" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// TestValidateClaimNextRequestRejectsPagingKnobs pins the rule that makes the +// claim's filter honest. The scan clears Limit and Offset itself, so accepting +// them would mean silently dropping a field a caller spelled — and a caller +// who wrote --limit 1 expecting a bounded claim would get an unbounded one +// with no way to find out. +func TestValidateClaimNextRequestRejectsPagingKnobs(t *testing.T) { + limit := 1 + for _, tc := range []struct { + name string + request publicops.ClaimNextRequest + wantErr bool + }{ + { + name: "actor and no paging is valid", + request: publicops.ClaimNextRequest{Actor: "worker"}, + }, + { + name: "missing actor", + request: publicops.ClaimNextRequest{}, + wantErr: true, + }, + { + name: "limit set, even to zero", + request: publicops.ClaimNextRequest{Actor: "worker", Filter: publicops.ReadyRequest{Limit: new(int)}}, + wantErr: true, + }, + { + name: "limit set to a real page size", + request: publicops.ClaimNextRequest{Actor: "worker", Filter: publicops.ReadyRequest{Limit: &limit}}, + wantErr: true, + }, + { + name: "offset set", + request: publicops.ClaimNextRequest{Actor: "worker", Filter: publicops.ReadyRequest{Offset: 3}}, + wantErr: true, + }, + } { + t.Run(tc.name, func(t *testing.T) { + err := ValidateClaimNextRequest(tc.request) + if tc.wantErr != (err != nil) { + t.Fatalf("ValidateClaimNextRequest() error = %v, want error = %v", err, tc.wantErr) + } + if tc.wantErr && !errors.Is(err, storage.ErrValidation) { + t.Fatalf("ValidateClaimNextRequest() error = %v, want it to match ErrValidation", err) + } + }) + } +} + +func TestValidateCloseBatchRequest(t *testing.T) { + item := publicops.BatchCloseItem{IssueID: "bd-1"} + limit := 1 + for _, tc := range []struct { + name string + request publicops.CloseBatchRequest + wantErr bool + }{ + { + name: "one item is valid", + request: publicops.CloseBatchRequest{Actor: "worker", Items: []publicops.BatchCloseItem{item}}, + }, + { + name: "missing actor", + request: publicops.CloseBatchRequest{Items: []publicops.BatchCloseItem{item}}, + wantErr: true, + }, + { + name: "no items", + request: publicops.CloseBatchRequest{Actor: "worker"}, + wantErr: true, + }, + { + name: "item without an id", + request: publicops.CloseBatchRequest{Actor: "worker", Items: []publicops.BatchCloseItem{item, {}}}, + wantErr: true, + }, + { + // The embedded claim answers to the claim's own rules, by + // reference: restating them here is how the two would drift. + name: "claim next carrying a limit", + request: publicops.CloseBatchRequest{ + Actor: "worker", + Items: []publicops.BatchCloseItem{item}, + ClaimNext: &publicops.ReadyRequest{Limit: &limit}, + }, + wantErr: true, + }, + } { + t.Run(tc.name, func(t *testing.T) { + err := ValidateCloseBatchRequest(tc.request) + if tc.wantErr != (err != nil) { + t.Fatalf("ValidateCloseBatchRequest() error = %v, want error = %v", err, tc.wantErr) + } + if tc.wantErr && !errors.Is(err, storage.ErrValidation) { + t.Fatalf("ValidateCloseBatchRequest() error = %v, want it to match ErrValidation", err) + } + }) + } +} + +// TestCloseBatchCommitMessageNamesWhatLanded pins that a skipped id stays out +// of the history entry. Composing the message from the REQUEST would put an id +// in `bd dolt log` that the commit never touched — and so would composing it +// from every nil-Err outcome, because an idempotent re-close is a per-item +// success that touched nothing (issueops/batchcloser.go:60-64, 119-122). +func TestCloseBatchCommitMessageNamesWhatLanded(t *testing.T) { + refused := publicops.CloseOutcome{IssueID: "bd-2", Err: errors.New("refused")} + landed := func(id string) publicops.CloseOutcome { + return publicops.CloseOutcome{IssueID: id, Changed: true, Issue: &types.Issue{ID: id}} + } + landedWisp := func(id string) publicops.CloseOutcome { + return publicops.CloseOutcome{IssueID: id, Changed: true, Issue: &types.Issue{ID: id, Ephemeral: true}} + } + for _, tc := range []struct { + name string + result publicops.CloseBatchResult + want string + }{ + { + name: "every id landed", + result: publicops.CloseBatchResult{Outcomes: []publicops.CloseOutcome{ + landed("bd-1"), landed("bd-2"), landed("bd-3"), + }}, + want: "bd: close bd-1, bd-2, bd-3", + }, + { + name: "a refused id is not named", + result: publicops.CloseBatchResult{Outcomes: []publicops.CloseOutcome{ + landed("bd-1"), refused, landed("bd-3"), + }}, + want: "bd: close bd-1, bd-3", + }, + { + name: "an idempotent re-close is not named", + result: publicops.CloseBatchResult{Outcomes: []publicops.CloseOutcome{ + landed("bd-1"), {IssueID: "bd-3"}, + }}, + want: "bd: close bd-1", + }, + { + name: "nothing landed records no entry", + result: publicops.CloseBatchResult{Outcomes: []publicops.CloseOutcome{refused}}, + want: "", + }, + { + name: "an all-idempotent batch records no entry", + result: publicops.CloseBatchResult{Outcomes: []publicops.CloseOutcome{ + {IssueID: "bd-1"}, {IssueID: "bd-3"}, + }}, + want: "", + }, + { + name: "a wisp landing is not named", + result: publicops.CloseBatchResult{Outcomes: []publicops.CloseOutcome{ + landed("bd-1"), landedWisp("bd-wisp-2"), + }}, + want: "bd: close bd-1", + }, + { + name: "an ephemeral-only batch is counted, never named", + result: publicops.CloseBatchResult{Outcomes: []publicops.CloseOutcome{ + landedWisp("bd-wisp-1"), landedWisp("bd-wisp-2"), + }}, + want: "bd: close 2 ephemeral items", + }, + { + name: "an ephemeral-only batch that claimed names the claim", + result: publicops.CloseBatchResult{ + Outcomes: []publicops.CloseOutcome{landedWisp("bd-wisp-1")}, + ClaimedNext: &publicops.IssueWithCounts{Issue: &types.Issue{ID: "bd-9"}}, + }, + want: "bd: close 1 ephemeral item; claim bd-9", + }, + } { + t.Run(tc.name, func(t *testing.T) { + if got := CloseBatchCommitMessage(tc.result); got != tc.want { + t.Fatalf("CloseBatchCommitMessage() = %q, want %q", got, tc.want) + } + }) + } +} diff --git a/internal/storage/role_accessor_decorator_test.go b/internal/storage/role_accessor_decorator_test.go new file mode 100644 index 000000000..844e2b54c --- /dev/null +++ b/internal/storage/role_accessor_decorator_test.go @@ -0,0 +1,219 @@ +package storage + +import ( + "context" + "errors" + "reflect" + "runtime" + "strings" + "testing" + + "github.com/steveyegge/beads/issueops" +) + +// roleAccessorNames is the seven-strong capability surface every storage +// decorator has to answer for. It is written out rather than derived so that +// adding an eighth role to DoltStorage without deciding what each decorator +// does with it is a compile-or-test failure somewhere, not silence. +var roleAccessorNames = []string{ + "IssueLifecycle", + "IssueReader", + "IssueRelations", + "Commenter", + "ReadyClaimer", + "BatchCloser", + "DependencyEditor", +} + +// TestHookFiringStoreDeclaresEveryRoleAccessor is the structural half of the +// decorator's conformance story. +// +// HookFiringStore embeds DoltStorage for pass-through, which means DELETING an +// accessor still compiles: the embedded interface supplies a promoted method +// with the same signature, the decorator silently hands back the inner store's +// surface, and every hook that surface should have fired stops firing. The +// compile-time `var _ interface{...}` blocks at the bottom of hook_decorator.go +// cannot see this — a promoted method satisfies them exactly as well as a +// declared one. Reflection can: the compiler reports a promoted method's +// implementation as living in "". +func TestHookFiringStoreDeclaresEveryRoleAccessor(t *testing.T) { + assertRoleAccessorsAreDeclared(t, reflect.TypeOf(&HookFiringStore{})) +} + +// assertRoleAccessorsAreDeclared fails for any role accessor the type inherits +// from an embedded field instead of declaring itself. Exported so the telemetry +// package, which cannot be imported from here, has a sibling of the same shape; +// see internal/telemetry/role_accessor_decorator_test.go. +func assertRoleAccessorsAreDeclared(t *testing.T, decorator reflect.Type) { + t.Helper() + for _, name := range roleAccessorNames { + method, ok := decorator.MethodByName(name) + if !ok { + t.Errorf("%s has no %s accessor at all", decorator, name) + continue + } + file, _ := runtime.FuncForPC(method.Func.Pointer()).FileLine(method.Func.Pointer()) + if strings.Contains(file, "") { + t.Errorf("%s.%s is promoted from the embedded store, not declared on the decorator: "+ + "the decorator hands back the inner surface undecorated", decorator, name) + } + } +} + +// roleAccessorStore is a DoltStorage whose only real methods are the seven role +// accessors, each answering with a distinguishable sentinel so a test can tell +// a decorated surface from a passed-through one. +type roleAccessorStore struct { + DoltStorage + lifecycle issueops.Lifecycle + reader issueops.Reader + relations issueops.Relations + commenter issueops.Commenter + claimer issueops.ReadyClaimer + closer issueops.BatchCloser + editor issueops.DependencyEditor + err error +} + +func newRoleAccessorStore() *roleAccessorStore { + sentinel := &roleAccessorSentinel{} + return &roleAccessorStore{ + lifecycle: sentinel, + reader: sentinel, + relations: sentinel, + commenter: sentinel, + claimer: sentinel, + closer: sentinel, + editor: sentinel, + } +} + +func (s *roleAccessorStore) IssueLifecycle() (issueops.Lifecycle, error) { return s.lifecycle, s.err } +func (s *roleAccessorStore) IssueReader() (issueops.Reader, error) { return s.reader, s.err } +func (s *roleAccessorStore) IssueRelations() (issueops.Relations, error) { return s.relations, s.err } +func (s *roleAccessorStore) Commenter() (issueops.Commenter, error) { return s.commenter, s.err } +func (s *roleAccessorStore) ReadyClaimer() (issueops.ReadyClaimer, error) { + return s.claimer, s.err +} +func (s *roleAccessorStore) BatchCloser() (issueops.BatchCloser, error) { return s.closer, s.err } +func (s *roleAccessorStore) DependencyEditor() (issueops.DependencyEditor, error) { + return s.editor, s.err +} + +// roleAccessorSentinel implements all seven roles at once. Nothing calls its +// methods; identity is the whole point. +type roleAccessorSentinel struct{} + +func (*roleAccessorSentinel) Create(context.Context, issueops.CreateRequest) (issueops.CreateResult, error) { + return issueops.CreateResult{}, nil +} +func (*roleAccessorSentinel) Update(context.Context, issueops.UpdateRequest) (issueops.UpdateResult, error) { + return issueops.UpdateResult{}, nil +} +func (*roleAccessorSentinel) Close(context.Context, issueops.CloseRequest) (issueops.CloseResult, error) { + return issueops.CloseResult{}, nil +} +func (*roleAccessorSentinel) Reopen(context.Context, issueops.ReopenRequest) (issueops.ReopenResult, error) { + return issueops.ReopenResult{}, nil +} +func (*roleAccessorSentinel) Ready(context.Context, issueops.ReadyRequest) (issueops.IssuePage, error) { + return issueops.IssuePage{}, nil +} +func (*roleAccessorSentinel) List(context.Context, issueops.ListRequest) (issueops.IssuePage, error) { + return issueops.IssuePage{}, nil +} +func (*roleAccessorSentinel) Get(context.Context, issueops.GetRequest) (*issueops.IssueDetails, error) { + return nil, nil +} +func (*roleAccessorSentinel) Related(context.Context, issueops.RelatedRequest) ([]*issueops.RelatedIssue, error) { + return nil, nil +} +func (*roleAccessorSentinel) AddComment(context.Context, issueops.AddCommentRequest) (issueops.AddCommentResult, error) { + return issueops.AddCommentResult{}, nil +} +func (*roleAccessorSentinel) ClaimNext(context.Context, issueops.ClaimNextRequest) (issueops.ClaimNextResult, error) { + return issueops.ClaimNextResult{}, nil +} +func (*roleAccessorSentinel) CloseBatch(context.Context, issueops.CloseBatchRequest) (issueops.CloseBatchResult, error) { + return issueops.CloseBatchResult{}, nil +} +func (*roleAccessorSentinel) AddDependencies(context.Context, issueops.AddDependenciesRequest) (issueops.AddDependenciesResult, error) { + return issueops.AddDependenciesResult{}, nil +} +func (*roleAccessorSentinel) RemoveDependency(context.Context, issueops.RemoveDependencyRequest) (issueops.RemoveDependencyResult, error) { + return issueops.RemoveDependencyResult{}, nil +} + +// TestHookFiringStoreWrapsTheWriteRolesAndPassesTheReadsThrough is the +// behavioural half, and it catches what reflection cannot: an accessor that IS +// declared but reads `return h.inner.Commenter()`. That edit compiles, keeps +// satisfying DoltStorage, and silently stops every completion hook on that +// role. +// +// The two read roles are asserted the OTHER way round on purpose. Reads fire no +// completion hooks, so IssueReader and IssueRelations deliberately return the +// inner surface unwrapped (hook_issue_reader.go, hook_relations.go); this test +// pins that as a decision rather than leaving it indistinguishable from the +// regression above. +func TestHookFiringStoreWrapsTheWriteRolesAndPassesTheReadsThrough(t *testing.T) { + inner := newRoleAccessorStore() + store := NewHookFiringStore(inner, nil) + + for _, test := range []struct { + name string + got func() (any, error) + want any + wrapped bool + }{ + {"IssueLifecycle", func() (any, error) { return store.IssueLifecycle() }, inner.lifecycle, true}, + {"Commenter", func() (any, error) { return store.Commenter() }, inner.commenter, true}, + {"ReadyClaimer", func() (any, error) { return store.ReadyClaimer() }, inner.claimer, true}, + {"BatchCloser", func() (any, error) { return store.BatchCloser() }, inner.closer, true}, + {"DependencyEditor", func() (any, error) { return store.DependencyEditor() }, inner.editor, true}, + {"IssueReader", func() (any, error) { return store.IssueReader() }, inner.reader, false}, + {"IssueRelations", func() (any, error) { return store.IssueRelations() }, inner.relations, false}, + } { + t.Run(test.name, func(t *testing.T) { + surface, err := test.got() + if err != nil { + t.Fatalf("%s() error = %v", test.name, err) + } + same := surface == test.want + switch { + case test.wrapped && same: + t.Fatalf("%s() returned the inner surface undecorated, so its completion hooks never fire", test.name) + case !test.wrapped && !same: + t.Fatalf("%s() = %T, want the inner surface unwrapped — reads fire no hooks", test.name, surface) + } + }) + } +} + +// TestHookFiringStoreRoleAccessorsPropagateInnerErrors pins the other half of +// the recursion: an accessor that recurses must not swallow the inner store's +// refusal on the way back. +func TestHookFiringStoreRoleAccessorsPropagateInnerErrors(t *testing.T) { + want := errors.New("inner refused") + inner := newRoleAccessorStore() + inner.err = want + store := NewHookFiringStore(inner, nil) + + for _, test := range []struct { + name string + got func() (any, error) + }{ + {"IssueLifecycle", func() (any, error) { return store.IssueLifecycle() }}, + {"Commenter", func() (any, error) { return store.Commenter() }}, + {"ReadyClaimer", func() (any, error) { return store.ReadyClaimer() }}, + {"BatchCloser", func() (any, error) { return store.BatchCloser() }}, + {"DependencyEditor", func() (any, error) { return store.DependencyEditor() }}, + {"IssueReader", func() (any, error) { return store.IssueReader() }}, + {"IssueRelations", func() (any, error) { return store.IssueRelations() }}, + } { + t.Run(test.name, func(t *testing.T) { + if _, err := test.got(); !errors.Is(err, want) { + t.Fatalf("%s() error = %v, want %v", test.name, err, want) + } + }) + } +} diff --git a/internal/storage/storage.go b/internal/storage/storage.go index bd9a551f2..883680058 100644 --- a/internal/storage/storage.go +++ b/internal/storage/storage.go @@ -45,13 +45,27 @@ type CloseOpenChildrenError = issueops.CloseOpenChildrenError var ErrNotOwner = errors.New("issue claimed by a different actor") // ClaimedByFragment and NotClaimableStatusFragment are the exact message -// fragments the claim path (issueops/claim.go) appends after the sentinel to -// carry the conflicting assignee/status: ErrAlreadyClaimed is wrapped as -// " by " and ErrNotClaimable as ": status -// ". They are the single source of truth for that format so producer -// (claim.go) and consumer (beads.ParseClaimConflict) cannot drift: the consumer -// reconstructs its marker as ErrAlreadyClaimed.Error()+ClaimedByFragment rather -// than hardcoding the literal. +// fragments a claim refusal puts after the sentinel to carry the conflicting +// assignee/status: ErrAlreadyClaimed reads " by " and +// ErrNotClaimable reads ": status ". They are the single +// source of truth for that format so producer and consumer +// (beads.ParseClaimConflict) cannot drift: the consumer reconstructs its marker +// as ErrAlreadyClaimed.Error()+ClaimedByFragment rather than hardcoding the +// literal. +// +// The producers are the two claim bodies — +// internal/storage/issueops.ClaimIssueInTx and +// internal/storage/domain.issueUseCaseImpl.claim — which compose the message +// before wrapping it in an issueops.ClaimConflictError. That type's Error() is +// a PASSTHROUGH, so the fragments must be in the wrapped error; a caller +// reading the type's FIELDS needs none of this. These stay for the parser, and +// TestClaimConflictFormatRoundTrip (internal/storage/dolt) plus the +// root-package ParseClaimConflict tests are the tripwires that producer and +// consumer still agree character for character. +// +// One refusal deliberately omits the " by " tail: an OPEN issue held +// by someone else answers with holder-steering copy instead (wy-yuclk), so its +// assignee is recovered from the typed field rather than the prose. const ( ClaimedByFragment = " by " NotClaimableStatusFragment = ": status " @@ -107,6 +121,41 @@ type Storage interface { // inner result. IssueClaimer() (issueops.Claimer, error) + // ReadyClaimer returns the guarded take-ready-work surface for this store. + // It is its own role rather than a fifth verb on IssueLifecycle because + // the caller names a question and the implementation picks the answer, so + // selection is part of the operation and not a patch. Like the other + // accessors, every decorator in a store's chain answers for itself. + ReadyClaimer() (issueops.ReadyClaimer, error) + + // BatchCloser returns the guarded close-many surface for this store: the + // role whose REQUEST is the transaction boundary, so N closes land as one + // durable act instead of N. It is its own role rather than a Close + // overload because a batch reports per-item outcomes that a single close + // has nowhere to put. + BatchCloser() (issueops.BatchCloser, error) + + // DependencyEditor returns the guarded dependency-edge surface for this + // store. It is its own role rather than more IssueLifecycle verbs because + // an edge has two endpoints and every refusal it raises is a statement + // about the graph they sit in, which a patch has nowhere to put. + DependencyEditor() (issueops.DependencyEditor, error) + + // Commenter returns the guarded add-comment surface for this store. It is + // its own role because a comment appends to a thread the issue owns and + // changes no field of the issue, so an IssuePatch has nothing to carry. + Commenter() (issueops.Commenter, error) + + // IssueRelations returns the guarded neighbor-query surface for this + // store: the read counterpart of DependencyEditor. It is its own role + // rather than a fourth IssueReader method because it answers a question + // about EDGES — anchored on one issue, directed, and carrying the edge + // type — where the reader answers with pages of issues. + // + // Reads fire no hooks, so the hook decorator's answer is its inner store's + // unchanged, as it is for IssueReader. + IssueRelations() (issueops.Relations, error) + // Issue CRUD CreateIssue(ctx context.Context, issue *types.Issue, actor string) error CreateIssues(ctx context.Context, issues []*types.Issue, actor string) error diff --git a/internal/storage/uow/batch_closer.go b/internal/storage/uow/batch_closer.go new file mode 100644 index 000000000..f9729aed7 --- /dev/null +++ b/internal/storage/uow/batch_closer.go @@ -0,0 +1,120 @@ +package uow + +import ( + "context" + "fmt" + + "github.com/steveyegge/beads/internal/storage/domain" + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/internal/workapi" + publicops "github.com/steveyegge/beads/issueops" +) + +// BatchCloserSource is the capability accessor a unit-of-work provider offers +// for the batch-close role, the sibling of IssueLifecycleSource and +// ReadyClaimerSource. +type BatchCloserSource interface { + BatchCloser() (publicops.BatchCloser, error) +} + +// batchCloser closes many issues through one unit of work. +type batchCloser struct { + provider UnitOfWorkProvider +} + +// BatchCloser returns the guarded close-many surface for this provider. +func (p *doltSQLProvider) BatchCloser() (publicops.BatchCloser, error) { + return NewBatchCloser(p) +} + +// NewBatchCloser constructs a public batch closer backed by provider. +func NewBatchCloser(provider UnitOfWorkProvider) (publicops.BatchCloser, error) { + if isNilUnitOfWorkProvider(provider) { + return nil, fmt.Errorf("new batch closer: unit-of-work provider must not be nil") + } + return &batchCloser{provider: provider}, nil +} + +var _ publicops.BatchCloser = (*batchCloser)(nil) + +// CloseBatch closes every item it can in ONE unit of work and commits them +// together. The request is the transaction: N ids are N closes and one commit, +// which is the whole reason this is not a loop over Lifecycle.Close. +// +// A per-item refusal lands in that item's outcome and the loop CONTINUES. The +// survivors still commit, because that is what closing a list of issues has +// always done here and the per-id report is what tells the caller which one to +// fix. Only a request-level failure returns an error, and that rolls the whole +// transaction back. +func (o *batchCloser) CloseBatch(ctx context.Context, request publicops.CloseBatchRequest) (publicops.CloseBatchResult, error) { + if err := storageissueops.ValidateCloseBatchRequest(request); err != nil { + return publicops.CloseBatchResult{}, err + } + var claimFilter *types.WorkFilter + if request.ClaimNext != nil { + filter, err := workapi.BuildReadyFilter(*request.ClaimNext) + if err != nil { + return publicops.CloseBatchResult{}, err + } + claimFilter = &filter + } + + return RunTxResult(ctx, o.provider, func(ctx context.Context, uw UnitOfWork) (publicops.CloseBatchResult, string, error) { + result := publicops.CloseBatchResult{Outcomes: make([]publicops.CloseOutcome, len(request.Items))} + landed := 0 + for i, item := range request.Items { + outcome := closeBatchItem(ctx, uw, request, item) + result.Outcomes[i] = outcome + // Changed, not "no error": an idempotent re-close persisted + // nothing, so a batch of them lands nothing and earns no claim. + if outcome.Err == nil && outcome.Changed { + landed++ + } + } + + if claimFilter != nil && landed > 0 { + claimed, err := ClaimNextInUOW(ctx, uw, request.Actor, *claimFilter) + if err != nil { + return publicops.CloseBatchResult{}, "", err + } + result.ClaimedNext = claimed + } + + return result, storageissueops.CloseBatchCommitMessage(result), nil + }) +} + +// closeBatchItem closes one item, reporting its refusal rather than raising +// it. The resolve and the close share the batch's transaction, so the +// is_blocked guard the checked close runs has no read-then-write window. +func closeBatchItem(ctx context.Context, uw UnitOfWork, request publicops.CloseBatchRequest, item publicops.BatchCloseItem) publicops.CloseOutcome { + current, isWisp, err := workapi.GetIssueOrWisp(ctx, workapi.NewUOWDetailSource(uw), item.IssueID) + if err != nil { + return publicops.CloseOutcome{IssueID: item.IssueID, Err: err} + } + + params := domain.CloseIssueParams{Reason: item.Reason, Session: request.Session} + var closed domain.CloseIssueResult + if isWisp { + closed, err = uw.IssueUseCase().CloseWispChecked(ctx, item.IssueID, params, request.Actor, request.Force) + } else { + closed, err = uw.IssueUseCase().CloseIssueChecked(ctx, item.IssueID, params, request.Actor, request.Force) + } + if err != nil { + return publicops.CloseOutcome{IssueID: item.IssueID, Err: err} + } + if closed.Issue != nil { + current = closed.Issue + } + hydrated, err := hydrateIssueOperation(ctx, uw, current, false, false) + if err != nil { + return publicops.CloseOutcome{IssueID: item.IssueID, Err: err} + } + return publicops.CloseOutcome{ + IssueID: item.IssueID, + Issue: hydrated, + Changed: closed.Closed, + OpenChildren: closed.OpenChildren, + } +} diff --git a/internal/storage/uow/batch_closer_contract_test.go b/internal/storage/uow/batch_closer_contract_test.go new file mode 100644 index 000000000..1d4ebbbe2 --- /dev/null +++ b/internal/storage/uow/batch_closer_contract_test.go @@ -0,0 +1,85 @@ +package uow + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/backend/conformance" +) + +// The unit-of-work backend's wiring of the BatchCloser contract, and the only +// one of the three that runs a genuinely separate body: the two store backends +// share internal/storage/issueops.ExecuteCloseBatch, while this one closes each +// item through the domain use cases inside one RunTxResult. +// +// ONE PROVIDER FOR THE WHOLE SUITE, subtests namespaced by IssuePrefix, because +// each provider boots a real Dolt sql-server. NO t.Parallel: this backend has no +// per-test copy-on-write branch, so dolt_log is database-global and a parallel +// subtest would move another subtest's history delta. The configured issue +// prefix is "bc" and every subtest prefix extends it, so the explicit ids the +// contract seeds pass this backend's prefix validation. +func TestBatchCloserContract(t *testing.T) { + ctx := context.Background() + provider := newUOWRoleFixtureProvider(t, ctx, "bc") + + for _, test := range []struct { + name string + prefix string + run func(*testing.T, context.Context, conformance.BatchCloserFixture) + }{ + {name: "OutcomesMirrorItemsIndexForIndex", prefix: "bc-mirror", run: conformance.RunBatchCloserOutcomesMirrorItemsIndexForIndex}, + {name: "PerItemRefusalIsAResultAndSurvivorsCommit", prefix: "bc-refusal", run: conformance.RunBatchCloserPerItemRefusalIsAResultAndSurvivorsCommit}, + {name: "OutcomeSnapshotIsTheDocumentedShape", prefix: "bc-shape", run: conformance.RunBatchCloserOutcomeSnapshotIsTheDocumentedShape}, + {name: "RequestValidationReturnsZeroResultAndChangesNothing", prefix: "bc-valid", run: conformance.RunBatchCloserRequestValidationReturnsZeroResultAndChangesNothing}, + {name: "ClaimFilterValueFailureIsARequestValidationFailure", prefix: "bc-badsort", run: conformance.RunBatchCloserClaimFilterValueFailureIsARequestValidationFailure}, + {name: "BackendFailureReturnsNoOutcomes", prefix: "bc-deadctx", run: conformance.RunBatchCloserBackendFailureReturnsNoOutcomes}, + {name: "IdempotentRecloseIsAPerItemSuccess", prefix: "bc-reclose", run: conformance.RunBatchCloserIdempotentRecloseIsAPerItemSuccess}, + {name: "AllIdempotentBatchLandsNothing", prefix: "bc-allidem", run: conformance.RunBatchCloserAllIdempotentBatchLandsNothing}, + {name: "DuplicateItemRecloseAtItsOwnIndex", prefix: "bc-dup", run: conformance.RunBatchCloserDuplicateItemRecloseAtItsOwnIndex}, + {name: "WispItemClosesAndEarnsTheClaim", prefix: "bc-wispclaim", run: conformance.RunBatchCloserWispItemClosesAndEarnsTheClaim}, + {name: "DurableHistoryNeverNamesAWisp", prefix: "bc-wisphistory", run: conformance.RunBatchCloserDurableHistoryNeverNamesAWisp}, + {name: "ForceBypassesOnlyClosePolicy", prefix: "bc-force", run: conformance.RunBatchCloserForceBypassesOnlyClosePolicy}, + {name: "ClaimNextHydratesWhenSomethingClosed", prefix: "bc-claimhit", run: conformance.RunBatchCloserClaimNextHydratesWhenSomethingClosed}, + {name: "ClaimNextIsNilWhenNothingClosed", prefix: "bc-claimnone", run: conformance.RunBatchCloserClaimNextIsNilWhenNothingClosed}, + {name: "ClaimNextIsNilWhenTheFrontIsEmpty", prefix: "bc-claimempty", run: conformance.RunBatchCloserClaimNextIsNilWhenTheFrontIsEmpty}, + {name: "ClaimNextSeesAnUnblockingFromItsOwnBatch", prefix: "bc-claimunblock", run: conformance.RunBatchCloserClaimNextSeesAnUnblockingFromItsOwnBatch}, + {name: "RecordsOneHistoryEntryForWhatLanded", prefix: "bc-history", run: conformance.RunBatchCloserRecordsOneHistoryEntryForWhatLanded}, + {name: "AllRefusedBatchRecordsNoHistory", prefix: "bc-nohistory", run: conformance.RunBatchCloserAllRefusedBatchRecordsNoHistory}, + {name: "DoesNotMutateTheCallerRequest", prefix: "bc-snapshot", run: conformance.RunBatchCloserDoesNotMutateTheCallerRequest}, + } { + t.Run(test.name, func(t *testing.T) { + test.run(t, ctx, newUOWBatchCloserFixture(t, provider, test.prefix)) + }) + } +} + +func newUOWBatchCloserFixture(t *testing.T, provider UnitOfWorkProvider, prefix string) conformance.BatchCloserFixture { + t.Helper() + source, ok := provider.(BatchCloserSource) + if !ok { + t.Fatalf("provider %T does not offer the BatchCloser accessor", provider) + } + closer, err := source.BatchCloser() + if err != nil { + t.Fatalf("BatchCloser(): %v", err) + } + kit := newUOWRoleFixtureKit(provider, prefix) + return conformance.BatchCloserFixture{ + IssuePrefix: kit.IssuePrefix, + Closer: closer, + CreateIssue: kit.CreateIssue, + CreateWisp: kit.CreateWisp, + AddDependency: kit.AddDependency, + // Local, because the shared kit exposes no comment hook. Folding it in + // is an S0 follow-up (bd-kue5t); editing the frozen kit from this slice + // would collide with the five running beside it. + AddComment: func(ctx context.Context, issueID, actor, text string) error { + return RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + _, err := uw.CommentUseCase().AddCommentToIssue(ctx, issueID, actor, text) + return "seed comment on " + issueID, err + }) + }, + QueryScalar: kit.QueryScalar, + CountHistory: kit.CountHistory, + } +} diff --git a/internal/storage/uow/commenter.go b/internal/storage/uow/commenter.go new file mode 100644 index 000000000..0ab3f9a4d --- /dev/null +++ b/internal/storage/uow/commenter.go @@ -0,0 +1,66 @@ +package uow + +import ( + "context" + "fmt" + + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/internal/workapi" + publicops "github.com/steveyegge/beads/issueops" +) + +// CommenterSource is the capability accessor a unit-of-work provider offers +// for the comment role, the sibling of IssueLifecycleSource and +// DependencyEditorSource. +type CommenterSource interface { + Commenter() (publicops.Commenter, error) +} + +// commenter appends comments through a unit of work. +type commenter struct { + provider UnitOfWorkProvider +} + +// Commenter returns the guarded add-comment surface for this provider. +func (p *doltSQLProvider) Commenter() (publicops.Commenter, error) { + return NewCommenter(p) +} + +// NewCommenter constructs a public commenter backed by provider. +func NewCommenter(provider UnitOfWorkProvider) (publicops.Commenter, error) { + if isNilUnitOfWorkProvider(provider) { + return nil, fmt.Errorf("new commenter: unit-of-work provider must not be nil") + } + return &commenter{provider: provider}, nil +} + +var _ publicops.Commenter = (*commenter)(nil) + +// AddComment resolves the plane and appends the row in ONE unit of work. +// +// The resolve is workapi.GetIssueOrWisp — the same issue-then-wisp fallback +// Reader.Get runs, through the same function, so the two roles cannot come to +// disagree about which plane an id names. It runs INSIDE the transaction the +// insert runs in, so a comment cannot land on a row an earlier read saw. +func (c *commenter) AddComment(ctx context.Context, request publicops.AddCommentRequest) (publicops.AddCommentResult, error) { + if err := storageissueops.ValidateAddCommentRequest(request); err != nil { + return publicops.AddCommentResult{}, err + } + return RunTxResult(ctx, c.provider, func(ctx context.Context, uw UnitOfWork) (publicops.AddCommentResult, string, error) { + issue, isWisp, err := workapi.GetIssueOrWisp(ctx, workapi.NewUOWDetailSource(uw), request.IssueID) + if err != nil { + return publicops.AddCommentResult{}, "", err + } + var comment *publicops.Comment + if isWisp { + comment, err = uw.CommentUseCase().AddCommentToWisp(ctx, issue.ID, request.Author, request.Text) + } else { + comment, err = uw.CommentUseCase().AddCommentToIssue(ctx, issue.ID, request.Author, request.Text) + } + if err != nil { + return publicops.AddCommentResult{}, "", err + } + return publicops.AddCommentResult{Comment: comment}, + storageissueops.AddCommentCommitMessage(issue.ID), nil + }) +} diff --git a/internal/storage/uow/commenter_contract_test.go b/internal/storage/uow/commenter_contract_test.go new file mode 100644 index 000000000..45c1b9fac --- /dev/null +++ b/internal/storage/uow/commenter_contract_test.go @@ -0,0 +1,81 @@ +package uow + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/backend/conformance" +) + +// TestCommenterContract runs the Commenter contract against the unit-of-work +// provider — the one Commenter implementation that does not share the +// validate/execute body the two stores share, so this is the wiring where a +// genuine body divergence shows up. +// +// One provider for the whole suite (each newUOWRoleFixtureProvider boots a +// real Dolt sql-server) and NO t.Parallel: this backend has no per-test +// copy-on-write branch, so dolt_log and the comment tables are database-global +// and a parallel subtest would corrupt another subtest's count deltas. +func TestCommenterContract(t *testing.T) { + ctx := context.Background() + fixture := newUOWCommenterFixture(t, ctx, "cmt") + + t.Run("StoresTextVerbatim", func(t *testing.T) { + conformance.RunCommenterStoresTextVerbatim(t, ctx, fixture) + }) + t.Run("ResultMirrorsTheStoredRow", func(t *testing.T) { + conformance.RunCommenterResultMirrorsTheStoredRow(t, ctx, fixture) + }) + t.Run("CommentOnAWispLandsOnTheWispThread", func(t *testing.T) { + conformance.RunCommenterCommentOnAWispLandsOnTheWispThread(t, ctx, fixture) + }) + t.Run("RefusesAnIDOnNeitherPlane", func(t *testing.T) { + conformance.RunCommenterRefusesAnIDOnNeitherPlane(t, ctx, fixture) + }) + t.Run("RefusesAnEmptyIssueID", func(t *testing.T) { + conformance.RunCommenterRefusesAnEmptyIssueID(t, ctx, fixture) + }) + t.Run("DoesNotResolvePrefixes", func(t *testing.T) { + conformance.RunCommenterDoesNotResolvePrefixes(t, ctx, fixture) + }) + t.Run("RecordsAtMostOneHistoryEntry", func(t *testing.T) { + conformance.RunCommenterRecordsAtMostOneHistoryEntry(t, ctx, fixture) + }) + t.Run("LeavesTheAnchorIssueUntouched", func(t *testing.T) { + conformance.RunCommenterLeavesTheAnchorIssueUntouched(t, ctx, fixture) + }) + t.Run("RefusesBlankText", func(t *testing.T) { + conformance.RunCommenterRefusesBlankText(t, ctx, fixture) + }) + t.Run("RefusesAnEmptyAuthor", func(t *testing.T) { + conformance.RunCommenterRefusesAnEmptyAuthor(t, ctx, fixture) + }) + t.Run("LeavesTheCallersRequestAlone", func(t *testing.T) { + conformance.RunCommenterLeavesTheCallersRequestAlone(t, ctx, fixture) + }) +} + +func newUOWCommenterFixture(t *testing.T, ctx context.Context, prefix string) conformance.CommenterFixture { + t.Helper() + provider := newUOWRoleFixtureProvider(t, ctx, prefix) + // Through the capability accessor, not NewCommenter: a provider that + // stopped offering the role is the regression, and a constructor call + // would hide it. + source, ok := provider.(CommenterSource) + if !ok { + t.Fatalf("provider %T does not offer the Commenter accessor", provider) + } + commenter, err := source.Commenter() + if err != nil { + t.Fatalf("Commenter(): %v", err) + } + kit := newUOWRoleFixtureKit(provider, prefix) + return conformance.CommenterFixture{ + IssuePrefix: kit.IssuePrefix, + Commenter: commenter, + CreateIssue: kit.CreateIssue, + CreateWisp: kit.CreateWisp, + QueryScalar: kit.QueryScalar, + CountHistory: kit.CountHistory, + } +} diff --git a/internal/storage/uow/dependency_editor.go b/internal/storage/uow/dependency_editor.go new file mode 100644 index 000000000..1723210a6 --- /dev/null +++ b/internal/storage/uow/dependency_editor.go @@ -0,0 +1,108 @@ +package uow + +import ( + "context" + "fmt" + + "github.com/steveyegge/beads/internal/storage/domain" + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// DependencyEditorSource is the capability accessor a unit-of-work provider +// offers for the dependency-edge role, the sibling of IssueLifecycleSource and +// BatchCloserSource. +type DependencyEditorSource interface { + DependencyEditor() (publicops.DependencyEditor, error) +} + +// dependencyEditor edits the dependency graph through a unit of work. +type dependencyEditor struct { + provider UnitOfWorkProvider +} + +// DependencyEditor returns the guarded dependency-edge surface for this provider. +func (p *doltSQLProvider) DependencyEditor() (publicops.DependencyEditor, error) { + return NewDependencyEditor(p) +} + +// NewDependencyEditor constructs a public dependency editor backed by provider. +func NewDependencyEditor(provider UnitOfWorkProvider) (publicops.DependencyEditor, error) { + if isNilUnitOfWorkProvider(provider) { + return nil, fmt.Errorf("new dependency editor: unit-of-work provider must not be nil") + } + return &dependencyEditor{provider: provider}, nil +} + +var _ publicops.DependencyEditor = (*dependencyEditor)(nil) + +// AddDependencies asserts every edge in ONE unit of work. The request is the +// transaction: N edges are one commit, and the first refusal returns an error +// that rolls every earlier edge back with it, which is what makes the request +// all-or-nothing without any bookkeeping of its own. +// +// The use case applies the parent-child-first ordering and the whole-graph +// final gate the store-backed sibling applies, through the same rules, so the +// two answer the same refusals to the same requests. It is the SOURCE-ROUTED +// bulk verb for the same reason: each edge follows the plane its source lives +// in, and a request may mix them, so the two implementations also land the +// same edges in the same tables. +func (e *dependencyEditor) AddDependencies(ctx context.Context, request publicops.AddDependenciesRequest) (publicops.AddDependenciesResult, error) { + if err := storageissueops.ValidateAddDependenciesRequest(request); err != nil { + return publicops.AddDependenciesResult{}, err + } + deps := make([]*types.Dependency, 0, len(request.Edges)) + for _, edge := range request.Edges { + deps = append(deps, &types.Dependency{ + IssueID: edge.IssueID, + DependsOnID: edge.DependsOnID, + Type: edge.Type, + }) + } + added := make([]publicops.DependencyEdge, len(request.Edges)) + copy(added, request.Edges) + + return RunTxResult(ctx, e.provider, func(ctx context.Context, uw UnitOfWork) (publicops.AddDependenciesResult, string, error) { + if _, err := uw.DependencyUseCase().AddDependencies(ctx, deps, request.Actor, domain.BulkAddDepsOpts{ + SkipPerEdgeCycleCheck: request.SkipPerEdgeCycleCheck, + }); err != nil { + return publicops.AddDependenciesResult{}, "", err + } + return publicops.AddDependenciesResult{Added: added}, + storageissueops.AddDependenciesCommitMessage(request), nil + }) +} + +// RemoveDependency removes one edge in one unit of work. +// +// It is SOURCE-ROUTED, like the add: an edge lives in the plane its source +// lives in, so the removal reads that plane rather than pinning the durable +// one — a pinned removal cannot see a wisp-sourced edge and would report an +// edge that is plainly there as missing (bd-yby99.17). +// +// The delete inside the transaction is the found/not-found verdict. Taking it +// from the write itself rather than from a lookup before it is what keeps the +// answer true: a separate check is a read-then-write window in which a racing +// writer could add or drop the very edge being reported on. +func (e *dependencyEditor) RemoveDependency(ctx context.Context, request publicops.RemoveDependencyRequest) (publicops.RemoveDependencyResult, error) { + if err := storageissueops.ValidateRemoveDependencyRequest(request); err != nil { + return publicops.RemoveDependencyResult{}, err + } + return RunTxResult(ctx, e.provider, func(ctx context.Context, uw UnitOfWork) (publicops.RemoveDependencyResult, string, error) { + removed, err := uw.DependencyUseCase().RemoveDependencyBySource(ctx, request.IssueID, request.DependsOnID, request.Actor) + if err != nil { + return publicops.RemoveDependencyResult{}, "", err + } + if !removed { + // Nothing to write, so nothing to version: an empty commit message + // is how RunTxResult is told to commit nothing. + return publicops.RemoveDependencyResult{Removed: false}, "", nil + } + // A wisp-plane removal touched no versioned table, so the commit this + // asks for finds nothing to commit and RunTxResult absorbs that — the + // same way the all-ephemeral add records no history entry. + return publicops.RemoveDependencyResult{Removed: true}, + storageissueops.RemoveDependencyCommitMessage(request.IssueID, request.DependsOnID), nil + }) +} diff --git a/internal/storage/uow/dependency_editor_contract_test.go b/internal/storage/uow/dependency_editor_contract_test.go new file mode 100644 index 000000000..80e189a97 --- /dev/null +++ b/internal/storage/uow/dependency_editor_contract_test.go @@ -0,0 +1,79 @@ +package uow + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/backend/conformance" +) + +// TestUOWDependencyEditorContract runs the shared DependencyEditor contract +// against the unit-of-work backend. +// +// ONE PROVIDER FOR THE WHOLE SUITE, subtests over it. Each provider boots a +// real Dolt sql-server, and the contract fixtures were built for sharing — +// IssuePrefix plus a per-case id tag namespaces every row a case seeds. NO +// t.Parallel: dolt_log and the event tables are database-global here, so a +// parallel subtest would corrupt another subtest's before/after arithmetic. +func TestUOWDependencyEditorContract(t *testing.T) { + ctx := context.Background() + fixture := newUOWDependencyEditorFixture(t, ctx) + + for _, test := range []struct { + name string + run func(*testing.T, context.Context, conformance.DependencyEditorFixture) + }{ + {name: "RoutesWispSourcedEdgeToTheWispPlane", run: conformance.RunDependencyEditorRoutesWispSourcedEdgeToTheWispPlane}, + {name: "MixedBatchWritesBothPlanes", run: conformance.RunDependencyEditorMixedBatchWritesBothPlanes}, + {name: "MixedBatchRefusalRollsBackBothPlanes", run: conformance.RunDependencyEditorMixedBatchRefusalRollsBackBothPlanes}, + {name: "RefusesCrossPlaneCycle", run: conformance.RunDependencyEditorRefusesCrossPlaneCycle}, + {name: "AddedEchoesTheRequestOrder", run: conformance.RunDependencyEditorAddedEchoesTheRequestOrder}, + {name: "SameTypeReAddIsIdempotent", run: conformance.RunDependencyEditorSameTypeReAddIsIdempotent}, + {name: "RepeatsWithinOneRequestCollapse", run: conformance.RunDependencyEditorRepeatsWithinOneRequestCollapse}, + {name: "AttributesItsEventsToTheActor", run: conformance.RunDependencyEditorAttributesItsEventsToTheActor}, + {name: "RetypeRefusalLeavesTheOriginalEdge", run: conformance.RunDependencyEditorRetypeRefusalLeavesTheOriginalEdge}, + {name: "RefusalWritesNothing", run: conformance.RunDependencyEditorRefusalWritesNothing}, + {name: "RemoveIsIdempotent", run: conformance.RunDependencyEditorRemoveIsIdempotent}, + {name: "AppliesParentChildBeforeBlockingEdges", run: conformance.RunDependencyEditorAppliesParentChildBeforeBlockingEdges}, + {name: "AcceptsAnExternalTarget", run: conformance.RunDependencyEditorAcceptsAnExternalTarget}, + {name: "AcceptsAForeignRepoTarget", run: conformance.RunDependencyEditorAcceptsAForeignRepoTarget}, + {name: "RefusesBlockingEdgeAcrossItsOwnHierarchy", run: conformance.RunDependencyEditorRefusesBlockingEdgeAcrossItsOwnHierarchy}, + {name: "RefusesSelfDependencyWithTheProbeSkipped", run: conformance.RunDependencyEditorRefusesSelfDependencyWithTheProbeSkipped}, + {name: "RecordsOneHistoryEntryPerLandedRequest", run: conformance.RunDependencyEditorRecordsOneHistoryEntryPerLandedRequest}, + {name: "RecordsNoHistoryForAnAllEphemeralRequest", run: conformance.RunDependencyEditorRecordsNoHistoryForAnAllEphemeralRequest}, + {name: "SnapshotsTheRequest", run: conformance.RunDependencyEditorSnapshotsTheRequest}, + {name: "ValidationRefusalsWriteNothing", run: conformance.RunDependencyEditorValidationRefusalsWriteNothing}, + {name: "RoutesWispSourcedRemovalToTheWispPlane", run: conformance.RunDependencyEditorRoutesWispSourcedRemovalToTheWispPlane}, + {name: "RefusesAGhostSource", run: conformance.RunDependencyEditorRefusesAGhostSource}, + {name: "RefusesAMissingLocalTarget", run: conformance.RunDependencyEditorRefusesAMissingLocalTarget}, + {name: "AcceptsATypeOutsideTheConstants", run: conformance.RunDependencyEditorAcceptsATypeOutsideTheConstants}, + {name: "RemovesOnlyTheNamedEdge", run: conformance.RunDependencyEditorRemovesOnlyTheNamedEdge}, + {name: "SkipPerEdgeCycleCheckDropsOnlyTheProbe", run: conformance.RunDependencyEditorSkipPerEdgeCycleCheckDropsOnlyTheProbe}, + {name: "RecordsOneHistoryEntryForAMixedPlaneRequest", run: conformance.RunDependencyEditorRecordsOneHistoryEntryForAMixedPlaneRequest}, + } { + t.Run(test.name, func(t *testing.T) { + test.run(t, ctx, fixture) + }) + } +} + +// newUOWDependencyEditorFixture composes the backend's role fixture kit with +// the accessor under test. Every hook but the accessor comes from the kit, so +// the seeding and scalar-query plumbing stays identical to the other roles'. +func newUOWDependencyEditorFixture(t *testing.T, ctx context.Context) conformance.DependencyEditorFixture { + t.Helper() + provider := newUOWRoleFixtureProvider(t, ctx, "bd") + editor, err := NewDependencyEditor(provider) + if err != nil { + t.Fatalf("NewDependencyEditor: %v", err) + } + kit := newUOWRoleFixtureKit(provider, "bd") + return conformance.DependencyEditorFixture{ + IssuePrefix: kit.IssuePrefix, + Editor: editor, + CreateIssue: kit.CreateIssue, + CreateWisp: kit.CreateWisp, + QueryScalar: kit.QueryScalar, + CountHistory: kit.CountHistory, + } +} diff --git a/internal/storage/uow/issue_operations.go b/internal/storage/uow/issue_operations.go index 726e8b5bb..cd43dddef 100644 --- a/internal/storage/uow/issue_operations.go +++ b/internal/storage/uow/issue_operations.go @@ -22,6 +22,13 @@ type issueOperations struct { provider UnitOfWorkProvider } +// IssueLifecycleSource is the write-side twin of IssueReaderSource: the +// accessor a unit-of-work provider offers so a consumer holding a provider by +// interface asks for the role instead of reaching for a constructor. +type IssueLifecycleSource interface { + IssueLifecycle() (publicops.Lifecycle, error) +} + // IssueLifecycle returns the guarded issue-lifecycle surface for this // provider. A unit of work is not a special case: callers reach the verbs // through the same accessor they use on a store. @@ -95,7 +102,7 @@ func (o *issueOperations) Create(ctx context.Context, request publicops.CreateRe if err != nil { return publicops.CreateResult{}, "", storageissueops.ClassifyPublicCreateError(err) } - issue, err := hydrateIssueOperation(ctx, uw, created.Issue, true) + issue, err := hydrateIssueOperation(ctx, uw, created.Issue, true, false) if err != nil { return publicops.CreateResult{}, "", err } @@ -132,11 +139,11 @@ func createParams(request publicops.CreateRequest) (domain.CreateIssueParams, bo return params, issue.Ephemeral || issue.NoHistory, nil } -func hydrateIssueOperation(ctx context.Context, uw UnitOfWork, issue *types.Issue, includeComments bool) (*types.Issue, error) { +func hydrateIssueOperation(ctx context.Context, uw UnitOfWork, issue *types.Issue, includeComments, issuePlaneOnly bool) (*types.Issue, error) { if issue == nil { return nil, fmt.Errorf("hydrate issue operation: created issue is nil") } - stored, useWisp, err := operationIssue(ctx, uw, issue.ID) + stored, useWisp, err := operationIssue(ctx, uw, issue.ID, issuePlaneOnly) if err != nil { return nil, fmt.Errorf("hydrate issue operation: %w", err) } @@ -201,11 +208,11 @@ func (o *issueOperations) Update(ctx context.Context, request publicops.UpdateRe if err != nil { return publicops.UpdateResult{}, "", validationError(err) } - before, _, err := operationIssue(ctx, uw, attempt.IssueID) + before, _, err := operationIssue(ctx, uw, attempt.IssueID, attempt.IssuePlaneOnly) if err != nil { return publicops.UpdateResult{}, "", err } - before, err = hydrateIssueOperation(ctx, uw, before, false) + before, err = hydrateIssueOperation(ctx, uw, before, false, attempt.IssuePlaneOnly) if err != nil { return publicops.UpdateResult{}, "", err } @@ -226,11 +233,12 @@ func (o *issueOperations) Update(ctx context.Context, request publicops.UpdateRe if err != nil { return publicops.UpdateResult{}, "", err } - issue, err := hydrateIssueOperation(ctx, uw, updated, false) + issue, err := hydrateIssueOperation(ctx, uw, updated, false, attempt.IssuePlaneOnly) if err != nil { return publicops.UpdateResult{}, "", err } - return publicops.UpdateResult{Issue: issue, Changed: claimChanged || !semanticIssueEqual(before, issue)}, "update issue", nil + changed := claimChanged || !semanticIssueEqual(before, issue) + return publicops.UpdateResult{Issue: issue, Changed: changed}, updateHistoryEntry(attempt, changed), nil }) } @@ -379,7 +387,7 @@ func (o *issueOperations) Close(ctx context.Context, request publicops.CloseRequ } return RunTxResult(ctx, o.provider, func(ctx context.Context, uw UnitOfWork) (publicops.CloseResult, string, error) { attempt := storageissueops.CloneCloseRequest(snapshot) - issue, useWisp, err := operationIssue(ctx, uw, attempt.IssueID) + issue, useWisp, err := operationIssue(ctx, uw, attempt.IssueID, false) if err != nil { return publicops.CloseResult{}, "", err } @@ -388,7 +396,7 @@ func (o *issueOperations) Close(ctx context.Context, request publicops.CloseRequ return publicops.CloseResult{}, "", err } } - before, err := hydrateIssueOperation(ctx, uw, issue, false) + before, err := hydrateIssueOperation(ctx, uw, issue, false, false) if err != nil { return publicops.CloseResult{}, "", err } @@ -404,11 +412,12 @@ func (o *issueOperations) Close(ctx context.Context, request publicops.CloseRequ if closed.Issue != nil { issue = closed.Issue } - hydrated, err := hydrateIssueOperation(ctx, uw, issue, false) + hydrated, err := hydrateIssueOperation(ctx, uw, issue, false, false) if err != nil { return publicops.CloseResult{}, "", err } - return publicops.CloseResult{Issue: hydrated, Changed: !semanticIssueEqual(before, hydrated), OpenChildren: closed.OpenChildren}, "close issue", nil + return publicops.CloseResult{Issue: hydrated, Changed: !semanticIssueEqual(before, hydrated), OpenChildren: closed.OpenChildren}, + "close issue", nil }) } @@ -420,7 +429,7 @@ func (o *issueOperations) Reopen(ctx context.Context, request publicops.ReopenRe } return RunTxResult(ctx, o.provider, func(ctx context.Context, uw UnitOfWork) (publicops.ReopenResult, string, error) { attempt := storageissueops.CloneReopenRequest(snapshot) - issue, useWisp, err := operationIssue(ctx, uw, attempt.IssueID) + issue, useWisp, err := operationIssue(ctx, uw, attempt.IssueID, false) if err != nil { return publicops.ReopenResult{}, "", err } @@ -429,7 +438,7 @@ func (o *issueOperations) Reopen(ctx context.Context, request publicops.ReopenRe return publicops.ReopenResult{}, "", err } } - before, err := hydrateIssueOperation(ctx, uw, issue, false) + before, err := hydrateIssueOperation(ctx, uw, issue, false, false) if err != nil { return publicops.ReopenResult{}, "", err } @@ -445,23 +454,45 @@ func (o *issueOperations) Reopen(ctx context.Context, request publicops.ReopenRe if reopened.Issue != nil { issue = reopened.Issue } - hydrated, err := hydrateIssueOperation(ctx, uw, issue, false) + hydrated, err := hydrateIssueOperation(ctx, uw, issue, false, false) if err != nil { return publicops.ReopenResult{}, "", err } - return publicops.ReopenResult{Issue: hydrated, Changed: !semanticIssueEqual(before, hydrated)}, "reopen issue", nil + return publicops.ReopenResult{Issue: hydrated, Changed: !semanticIssueEqual(before, hydrated)}, + storageissueops.HistoryEntry(attempt.Provenance, "reopen issue"), nil }) } -func operationIssue(ctx context.Context, uw UnitOfWork, id string) (*types.Issue, bool, error) { - issue, err := uw.IssueUseCase().GetWisp(ctx, id) - if err == nil && issue != nil { - return issue, true, nil +// updateHistoryEntry names the history entry an update records, or "" for the +// one update that records none. +// +// A request that asks for a CLAIM AND NOTHING ELSE and changed nothing wrote +// nothing: the compare-and-set matched no row, and the idempotent branch it +// took grants no lease and records no event. Naming an entry for it would let a +// polling caller mint one per call. Every other update names one even when its +// post-state compares equal, because a same-value write still touches the row. +func updateHistoryEntry(request publicops.UpdateRequest, changed bool) string { + if !changed && request.Claim && reflect.DeepEqual(request.Patch, publicops.IssuePatch{}) { + return "" } - if err != nil && !errors.Is(err, publicops.ErrNotFound) && !dberrors.IsNoRows(err) { - return nil, false, fmt.Errorf("read wisp %s: %w", id, err) + return storageissueops.HistoryEntry(request.Provenance, "update issue") +} + +// operationIssue resolves id to the row an operation is about. Both planes are +// searched unless issuePlaneOnly restricts it, in which case a wisp id is a +// miss rather than an ephemeral row to operate on. Every call runs inside the +// operation's own transaction. +func operationIssue(ctx context.Context, uw UnitOfWork, id string, issuePlaneOnly bool) (*types.Issue, bool, error) { + if !issuePlaneOnly { + issue, err := uw.IssueUseCase().GetWisp(ctx, id) + if err == nil && issue != nil { + return issue, true, nil + } + if err != nil && !errors.Is(err, publicops.ErrNotFound) && !dberrors.IsNoRows(err) { + return nil, false, fmt.Errorf("read wisp %s: %w", id, err) + } } - issue, err = uw.IssueUseCase().GetIssue(ctx, id) + issue, err := uw.IssueUseCase().GetIssue(ctx, id) if err != nil { if errors.Is(err, publicops.ErrNotFound) || dberrors.IsNoRows(err) { return nil, false, fmt.Errorf("%w: issue %s", publicops.ErrNotFound, id) diff --git a/internal/storage/uow/issue_operations_claim_contract_test.go b/internal/storage/uow/issue_operations_claim_contract_test.go new file mode 100644 index 000000000..bea4ab77c --- /dev/null +++ b/internal/storage/uow/issue_operations_claim_contract_test.go @@ -0,0 +1,264 @@ +package uow + +import ( + "context" + "database/sql" + "errors" + "slices" + "testing" + + "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// The three request completions this backend has to honour, over a stub unit of +// work: the plane restriction, the provenance label, and the one update that +// records no history entry. The claim's own CAS is proved against real Dolt +// elsewhere; what is unprovable there — that a wisp is never even PROBED, and +// that a polling re-claim mints nothing — is what these pin. + +type claimContractUOW struct { + UnitOfWork + issues *claimContractIssues + commits []string +} + +func (u *claimContractUOW) Close(context.Context) {} + +func (u *claimContractUOW) Commit(_ context.Context, message string) error { + u.commits = append(u.commits, message) + return nil +} + +func (u *claimContractUOW) IssueUseCase() domain.IssueUseCase { return u.issues } +func (u *claimContractUOW) LabelUseCase() domain.LabelUseCase { return claimContractLabels{} } +func (u *claimContractUOW) DependencyUseCase() domain.DependencyUseCase { + return claimContractDeps{} +} + +type claimContractLabels struct{ domain.LabelUseCase } + +func (claimContractLabels) GetLabels(context.Context, string) ([]string, error) { return nil, nil } +func (claimContractLabels) GetWispLabels(context.Context, string) ([]string, error) { + return nil, nil +} + +type claimContractDeps struct{ domain.DependencyUseCase } + +func (claimContractDeps) GetIssueDependencyRecords(context.Context, []string) (map[string][]*types.Dependency, error) { + return nil, nil +} + +func (claimContractDeps) GetWispDependencyRecords(context.Context, []string) (map[string][]*types.Dependency, error) { + return nil, nil +} + +// claimContractIssues answers from one row, in whichever plane it was seeded +// into, and applies the claim the way the real use case does. +type claimContractIssues struct { + domain.IssueUseCase + issue *types.Issue + isWisp bool + wispReads int +} + +func (s *claimContractIssues) GetIssue(_ context.Context, id string) (*types.Issue, error) { + if s.isWisp || s.issue == nil || s.issue.ID != id { + return nil, sql.ErrNoRows + } + clone := *s.issue + return &clone, nil +} + +func (s *claimContractIssues) GetWisp(_ context.Context, id string) (*types.Issue, error) { + s.wispReads++ + if !s.isWisp || s.issue == nil || s.issue.ID != id { + return nil, sql.ErrNoRows + } + clone := *s.issue + return &clone, nil +} + +func (s *claimContractIssues) CloseIssueChecked(ctx context.Context, id string, _ domain.CloseIssueParams, _ string, _ bool) (domain.CloseIssueResult, error) { + if s.issue == nil || s.issue.ID != id { + return domain.CloseIssueResult{}, sql.ErrNoRows + } + closed := s.issue.Status == types.StatusClosed + s.issue.Status = types.StatusClosed + issue, err := s.GetIssue(ctx, id) + return domain.CloseIssueResult{Issue: issue, Closed: !closed}, err +} + +func (s *claimContractIssues) ReopenIssue(ctx context.Context, id string, _ domain.ReopenIssueParams, _ string) (domain.ReopenIssueResult, error) { + if s.issue == nil || s.issue.ID != id { + return domain.ReopenIssueResult{}, sql.ErrNoRows + } + reopened := s.issue.Status == types.StatusClosed + s.issue.Status = types.StatusOpen + issue, err := s.GetIssue(ctx, id) + return domain.ReopenIssueResult{Issue: issue, Reopened: reopened}, err +} + +func (s *claimContractIssues) ApplyUpdate(ctx context.Context, id string, spec domain.UpdateSpec, actor string) (*types.Issue, error) { + if spec.Claim && s.issue != nil { + s.issue.Assignee, s.issue.Status = actor, types.StatusInProgress + } + if s.isWisp { + return s.GetWisp(ctx, id) + } + return s.GetIssue(ctx, id) +} + +func newClaimContract(t *testing.T, issue *types.Issue, isWisp bool) (publicops.Lifecycle, *claimContractUOW) { + t.Helper() + uw := &claimContractUOW{issues: &claimContractIssues{issue: issue, isWisp: isWisp}} + operations, err := NewIssueOperations(providerFunc(func(context.Context) (UnitOfWork, error) { return uw, nil })) + if err != nil { + t.Fatalf("NewIssueOperations: %v", err) + } + return operations, uw +} + +// providerFunc adapts one unit of work into a provider, so every attempt in a +// call sees the state the previous one left. +type providerFunc func(context.Context) (UnitOfWork, error) + +func (f providerFunc) NewUOW(ctx context.Context) (UnitOfWork, error) { return f(ctx) } +func (f providerFunc) Close(context.Context) error { return nil } + +func TestUpdateProvenanceNamesTheHistoryEntry(t *testing.T) { + for _, tc := range []struct { + name string + provenance string + want string + }{ + {"caller supplies one", "bd serve: claim bd-1 by alice", "bd serve: claim bd-1 by alice"}, + {"caller supplies none", "", "update issue"}, + } { + t.Run(tc.name, func(t *testing.T) { + operations, uw := newClaimContract(t, &types.Issue{ID: "bd-1", Status: types.StatusOpen}, false) + result, err := operations.Update(context.Background(), publicops.UpdateRequest{ + Actor: "alice", IssueID: "bd-1", Claim: true, Provenance: tc.provenance, + }) + if err != nil { + t.Fatalf("Update: %v", err) + } + if !result.Changed { + t.Error("a won claim reports no change") + } + if !slices.Equal(uw.commits, []string{tc.want}) { + t.Errorf("history entries = %q, want exactly [%s]", uw.commits, tc.want) + } + }) + } +} + +// Reopen answers to the same rule update does, and it needs its own coverage +// because this backend's default is the one that disagrees with the +// store-backed implementations: "reopen issue" here against "bd: reopen issue" +// there. A caller that spells a label gets the same entry from both. +// +// The close that sets each case up carries no label — CloseRequest has none — +// so it always records this backend's own default, which is asserted alongside. +func TestReopenProvenanceNamesTheHistoryEntry(t *testing.T) { + for _, tc := range []struct { + name string + provenance string + wantReopen string + }{ + {"caller supplies one", "bd: reopen bd-1", "bd: reopen bd-1"}, + {"caller supplies none", "", "reopen issue"}, + } { + t.Run(tc.name, func(t *testing.T) { + operations, uw := newClaimContract(t, &types.Issue{ID: "bd-1", Status: types.StatusOpen}, false) + + if _, err := operations.Close(context.Background(), publicops.CloseRequest{ + Actor: "alice", IssueID: "bd-1", + }); err != nil { + t.Fatalf("Close: %v", err) + } + if _, err := operations.Reopen(context.Background(), publicops.ReopenRequest{ + Actor: "alice", IssueID: "bd-1", Provenance: tc.provenance, + }); err != nil { + t.Fatalf("Reopen: %v", err) + } + + if want := []string{"close issue", tc.wantReopen}; !slices.Equal(uw.commits, want) { + t.Errorf("history entries = %q, want %q", uw.commits, want) + } + }) + } +} + +// A polling caller must not fill the history with entries for a claim it +// already holds: the CAS matched no row, so there is nothing to record. +func TestIdempotentClaimRecordsNoHistoryEntry(t *testing.T) { + held := &types.Issue{ID: "bd-1", Status: types.StatusInProgress, Assignee: "alice"} + operations, uw := newClaimContract(t, held, false) + + result, err := operations.Update(context.Background(), publicops.UpdateRequest{ + Actor: "alice", IssueID: "bd-1", Claim: true, Provenance: "bd serve: claim bd-1 by alice", + }) + if err != nil { + t.Fatalf("Update: %v", err) + } + if result.Changed { + t.Error("a re-claim by the holder reports a change") + } + if len(uw.commits) != 0 { + t.Errorf("history entries = %q, want none for a claim that wrote nothing", uw.commits) + } +} + +// An update that carries a patch still records its entry even when the +// post-state compares equal: the row was written, whatever the comparison says. +func TestSameValueUpdateStillRecordsItsHistoryEntry(t *testing.T) { + operations, uw := newClaimContract(t, &types.Issue{ID: "bd-1", Status: types.StatusOpen, Title: "same"}, false) + + if _, err := operations.Update(context.Background(), publicops.UpdateRequest{ + Actor: "alice", + IssueID: "bd-1", + Patch: publicops.IssuePatch{Title: publicops.Field[string]{Set: true, Value: "same"}}, + }); err != nil { + t.Fatalf("Update: %v", err) + } + if !slices.Equal(uw.commits, []string{"update issue"}) { + t.Errorf("history entries = %q, want the default entry", uw.commits) + } +} + +func TestIssuePlaneOnlyRefusesAWispWithoutProbingIt(t *testing.T) { + operations, uw := newClaimContract(t, &types.Issue{ID: "bd-w1", Status: types.StatusOpen, Ephemeral: true}, true) + + _, err := operations.Update(context.Background(), publicops.UpdateRequest{ + Actor: "alice", IssueID: "bd-w1", Claim: true, IssuePlaneOnly: true, + }) + if !errors.Is(err, publicops.ErrNotFound) { + t.Fatalf("Update error = %v, want ErrNotFound for a wisp id", err) + } + if uw.issues.wispReads != 0 { + t.Errorf("wisp reads = %d, want 0: an issue-plane-only update never probes the other plane", uw.issues.wispReads) + } + if len(uw.commits) != 0 { + t.Errorf("a refused update recorded %q", uw.commits) + } +} + +// The zero value keeps the both-plane resolve every caller gets today. +func TestBothPlaneResolveStaysTheDefault(t *testing.T) { + operations, uw := newClaimContract(t, &types.Issue{ID: "bd-w1", Status: types.StatusOpen, Ephemeral: true}, true) + + result, err := operations.Update(context.Background(), publicops.UpdateRequest{ + Actor: "alice", IssueID: "bd-w1", Claim: true, + }) + if err != nil { + t.Fatalf("Update: %v", err) + } + if result.Issue == nil || result.Issue.Assignee != "alice" { + t.Fatalf("Update result = %+v, want the claimed wisp", result.Issue) + } + if uw.issues.wispReads == 0 { + t.Error("the default resolve never looked in the wisp plane") + } +} diff --git a/internal/storage/uow/issue_operations_contract_test.go b/internal/storage/uow/issue_operations_contract_test.go index 57b07eff4..253db251d 100644 --- a/internal/storage/uow/issue_operations_contract_test.go +++ b/internal/storage/uow/issue_operations_contract_test.go @@ -5,6 +5,7 @@ import ( "fmt" "strconv" "testing" + "time" "github.com/steveyegge/beads/backend/conformance" "github.com/steveyegge/beads/internal/storage/domain" @@ -41,6 +42,61 @@ func TestIssueOperationsUpdateClosedFieldsMatchClose(t *testing.T) { conformance.RunIssueOperationsUpdateClosedFieldsMatchClose(t, ctx, newUOWIssueOperationsFixture(t, ctx)) } +func TestIssueOperationsUpdateClaimConflictCarriesTheLosingState(t *testing.T) { + ctx := context.Background() + conformance.RunIssueOperationsUpdateClaimConflictCarriesTheLosingState(t, ctx, newUOWIssueOperationsFixture(t, ctx)) +} + +func TestIssueOperationsUpdateClaimHonorsConfiguredActiveStatuses(t *testing.T) { + ctx := context.Background() + conformance.RunIssueOperationsUpdateClaimHonorsConfiguredActiveStatuses(t, ctx, newUOWIssueOperationsFixture(t, ctx)) +} + +func TestIssueOperationsUpdateIssuePlaneOnlyRefusesWisps(t *testing.T) { + ctx := context.Background() + conformance.RunIssueOperationsUpdateIssuePlaneOnlyRefusesWisps(t, ctx, newUOWIssueOperationsFixture(t, ctx)) +} + +func TestIssueOperationsUpdateLabelPatchOrdering(t *testing.T) { + ctx := context.Background() + conformance.RunIssueOperationsUpdateLabelPatchOrdering(t, ctx, newUOWIssueOperationsFixture(t, ctx)) +} + +func TestIssueOperationsUpdateLabelPatchValueRules(t *testing.T) { + ctx := context.Background() + conformance.RunIssueOperationsUpdateLabelPatchValueRules(t, ctx, newUOWIssueOperationsFixture(t, ctx)) +} + +func TestIssueOperationsUpdateParentIDReplacesTheParentEdge(t *testing.T) { + ctx := context.Background() + conformance.RunIssueOperationsUpdateParentIDReplacesTheParentEdge(t, ctx, newUOWIssueOperationsFixture(t, ctx)) +} + +func TestIssueOperationsUpdateParentIDReplacesEveryParent(t *testing.T) { + ctx := context.Background() + conformance.RunIssueOperationsUpdateParentIDReplacesEveryParent(t, ctx, newUOWIssueOperationsFixture(t, ctx)) +} + +func TestIssueOperationsUpdateMetadataReplaceClearsAndValidates(t *testing.T) { + ctx := context.Background() + conformance.RunIssueOperationsUpdateMetadataReplaceClearsAndValidates(t, ctx, newUOWIssueOperationsFixture(t, ctx)) +} + +func TestIssueOperationsRequestValuesAreNotMutated(t *testing.T) { + ctx := context.Background() + conformance.RunIssueOperationsRequestValuesAreNotMutated(t, ctx, newUOWIssueOperationsFixture(t, ctx)) +} + +func TestIssueOperationsUpdateProvenanceLabelsHistory(t *testing.T) { + ctx := context.Background() + conformance.RunIssueOperationsUpdateProvenanceLabelsHistory(t, ctx, newUOWIssueOperationsFixture(t, ctx)) +} + +func TestIssueOperationsUpdatePersistentPreservesUnversionedClass(t *testing.T) { + ctx := context.Background() + conformance.RunIssueOperationsUpdatePersistentPreservesUnversionedClass(t, ctx, newUOWIssueOperationsFixture(t, ctx)) +} + func newUOWIssueOperationsFixture(t *testing.T, ctx context.Context) conformance.IssueOperationsStagingFixture { t.Helper() operations, provider := newRealIssueOperationsWithProvider(t, ctx) @@ -96,7 +152,19 @@ func newUOWIssueOperationsFixture(t *testing.T, ctx context.Context) conformance } // scanRawSQLValue copies one raw SQL column into a destination pointer, -// covering the destination types the issue-operations contract scans into. +// covering the destination types the role conformance contracts scan into. +// +// The set of supported destinations is part of the frozen scaffolding surface +// (bd-kue5t): every uow role wiring reaches its scalar reads through here, so a +// role slice that needs a new destination type routes the addition through a +// follow-up commit against that bead rather than adding a second scanner of its +// own. +// +// A SQL NULL is not a valid source for any of the numeric or boolean +// destinations — it fails loudly instead of decaying to a zero value, because a +// count case reading zero from a NULL is a case that passes for the wrong +// reason. Read a nullable column through COALESCE, or into *string, where NULL +// is the empty string. func scanRawSQLValue(dest, value any) error { switch target := dest.(type) { case *int: @@ -105,6 +173,32 @@ func scanRawSQLValue(dest, value any) error { return fmt.Errorf("scan %v into *int: %w", value, err) } *target = parsed + case *int64: + parsed, err := strconv.ParseInt(rawSQLString(value), 10, 64) + if err != nil { + return fmt.Errorf("scan %v into *int64: %w", value, err) + } + *target = parsed + case *bool: + // Dolt reports a BOOLEAN column as a TINYINT, so the raw value arrives + // as 1/0 as often as it does as true/false; ParseBool takes both. + parsed, err := strconv.ParseBool(rawSQLString(value)) + if err != nil { + return fmt.Errorf("scan %v into *bool: %w", value, err) + } + *target = parsed + case *float64: + parsed, err := strconv.ParseFloat(rawSQLString(value), 64) + if err != nil { + return fmt.Errorf("scan %v into *float64: %w", value, err) + } + *target = parsed + case *time.Time: + parsed, err := parseRawSQLTime(value) + if err != nil { + return fmt.Errorf("scan %v into *time.Time: %w", value, err) + } + *target = parsed case *string: *target = rawSQLString(value) default: @@ -113,6 +207,32 @@ func scanRawSQLValue(dest, value any) error { return nil } +// rawSQLTimeLayouts are the shapes a Dolt DATETIME comes back as when the +// driver hands over a string rather than a time.Time — full precision first, +// because a result-mirrors-the-row assertion compares at column precision. +var rawSQLTimeLayouts = []string{ + "2006-01-02 15:04:05.999999", + "2006-01-02 15:04:05", + time.RFC3339Nano, + time.RFC3339, +} + +func parseRawSQLTime(value any) (time.Time, error) { + if typed, ok := value.(time.Time); ok { + return typed, nil + } + text := rawSQLString(value) + if text == "" { + return time.Time{}, fmt.Errorf("empty or NULL timestamp") + } + for _, layout := range rawSQLTimeLayouts { + if parsed, err := time.Parse(layout, text); err == nil { + return parsed, nil + } + } + return time.Time{}, fmt.Errorf("no known layout parses %q", text) +} + func rawSQLString(value any) string { switch typed := value.(type) { case nil: diff --git a/internal/storage/uow/issue_operations_test.go b/internal/storage/uow/issue_operations_test.go index 6d6638c6f..a606c9091 100644 --- a/internal/storage/uow/issue_operations_test.go +++ b/internal/storage/uow/issue_operations_test.go @@ -656,7 +656,7 @@ func TestOperationIssueFallsBackOnlyAfterNotFoundWispRead(t *testing.T) { }, }} - issue, isWisp, err := operationIssue(context.Background(), uw, "bd-durable") + issue, isWisp, err := operationIssue(context.Background(), uw, "bd-durable", false) if err != nil { t.Fatalf("operationIssue() error = %v", err) } @@ -677,7 +677,7 @@ func TestOperationIssueFallsBackToDurableAfterNoRowsWispRead(t *testing.T) { }, }} - issue, isWisp, err := operationIssue(context.Background(), uw, "bd-durable") + issue, isWisp, err := operationIssue(context.Background(), uw, "bd-durable", false) if err != nil { t.Fatalf("operationIssue() error = %v", err) } @@ -692,7 +692,7 @@ func TestOperationIssueBothMissingMatchesPublicNotFound(t *testing.T) { getIssue: func(context.Context, string) (*types.Issue, error) { return nil, sql.ErrNoRows }, }} - _, _, err := operationIssue(context.Background(), uw, "bd-missing") + _, _, err := operationIssue(context.Background(), uw, "bd-missing", false) if !errors.Is(err, issueops.ErrNotFound) { t.Fatalf("operationIssue() error = %v, want ErrNotFound", err) } @@ -711,7 +711,7 @@ func TestOperationIssuePropagatesWispReadFailure(t *testing.T) { }, }} - _, _, err := operationIssue(context.Background(), uw, "bd-durable") + _, _, err := operationIssue(context.Background(), uw, "bd-durable", false) if !errors.Is(err, wispReadErr) { t.Fatalf("operationIssue() error = %v, want wisp read error", err) } diff --git a/internal/storage/uow/lifecycle_close_reopen_contract_test.go b/internal/storage/uow/lifecycle_close_reopen_contract_test.go new file mode 100644 index 000000000..eee4482eb --- /dev/null +++ b/internal/storage/uow/lifecycle_close_reopen_contract_test.go @@ -0,0 +1,78 @@ +package uow + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/backend/conformance" +) + +// TestLifecycleCloseReopenContract runs the Close/Reopen half of the Lifecycle +// contract against the unit-of-work provider — the one Lifecycle implementation +// that does not share the validate/execute body the two stores share. It +// reaches the same row-level bodies through domain/db but derives Changed by +// comparing the post-state snapshot to the pre-state one instead of reading the +// row-write facts, so this is the wiring where a Changed or OpenChildren +// divergence shows up. +// +// One provider for the whole suite (each newUOWRoleFixtureProvider boots a real +// Dolt sql-server) and NO t.Parallel: this backend has no per-test +// copy-on-write branch, so the event tables are database-global and a parallel +// subtest would corrupt another subtest's count deltas. +func TestLifecycleCloseReopenContract(t *testing.T) { + ctx := context.Background() + fixture := newUOWLifecycleCloseReopenFixture(t, ctx, "lcr") + + t.Run("CloseRefusalsCarryTheirTypesAndWriteNothing", func(t *testing.T) { + conformance.RunLifecycleCloseRefusalsCarryTheirTypesAndWriteNothing(t, ctx, fixture) + }) + t.Run("CloseIsIdempotentAndKeepsTheFirstClose", func(t *testing.T) { + conformance.RunLifecycleCloseIsIdempotentAndKeepsTheFirstClose(t, ctx, fixture) + }) + t.Run("ReopenLeavesNonDoneStatusesUnchanged", func(t *testing.T) { + conformance.RunLifecycleReopenLeavesNonDoneStatusesUnchanged(t, ctx, fixture) + }) + t.Run("CloseAndReopenSpanTheConfiguredDoneCategory", func(t *testing.T) { + conformance.RunLifecycleCloseAndReopenSpanTheConfiguredDoneCategory(t, ctx, fixture) + }) + t.Run("ExpectedVersionIsCheckedBeforeTheNoOps", func(t *testing.T) { + conformance.RunLifecycleExpectedVersionIsCheckedBeforeTheNoOps(t, ctx, fixture) + }) + t.Run("ReopenRecordsItsReason", func(t *testing.T) { + conformance.RunLifecycleReopenRecordsItsReason(t, ctx, fixture) + }) + t.Run("ReopenProvenanceLabelsHistory", func(t *testing.T) { + conformance.RunLifecycleReopenProvenanceLabelsHistory(t, ctx, fixture) + }) + t.Run("ResultsAreHydratedPostStateSnapshots", func(t *testing.T) { + conformance.RunLifecycleResultsAreHydratedPostStateSnapshots(t, ctx, fixture) + }) + t.Run("CloseAndReopenRequireActorAndIssueID", func(t *testing.T) { + conformance.RunLifecycleCloseAndReopenRequireActorAndIssueID(t, ctx, fixture) + }) +} + +func newUOWLifecycleCloseReopenFixture(t *testing.T, ctx context.Context, prefix string) conformance.LifecycleCloseReopenFixture { + t.Helper() + provider := newUOWRoleFixtureProvider(t, ctx, prefix) + // Through the capability accessor, not NewIssueOperations: a provider that + // stopped offering the role is the regression, and a constructor call would + // hide it. + source, ok := provider.(IssueLifecycleSource) + if !ok { + t.Fatalf("provider %T does not offer the IssueLifecycle accessor", provider) + } + lifecycle, err := source.IssueLifecycle() + if err != nil { + t.Fatalf("IssueLifecycle(): %v", err) + } + kit := newUOWRoleFixtureKit(provider, prefix) + return conformance.LifecycleCloseReopenFixture{ + IssuePrefix: kit.IssuePrefix, + Lifecycle: lifecycle, + CreateIssue: kit.CreateIssue, + AddDependency: kit.AddDependency, + SetConfig: kit.SetConfig, + QueryScalar: kit.QueryScalar, + } +} diff --git a/internal/storage/uow/reader_contract_test.go b/internal/storage/uow/reader_contract_test.go new file mode 100644 index 000000000..a335ac2cd --- /dev/null +++ b/internal/storage/uow/reader_contract_test.go @@ -0,0 +1,127 @@ +package uow + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/backend/conformance" +) + +// The Reader contract, wired at the unit-of-work backend. This is the one +// wiring that runs a genuinely separate body: the two store accessors both hand +// back workapi/storereader.New(store), while internal/storage/uow/issue_reader.go +// builds its own filter, runs its own seam and feeds the shared epilogue a +// native has-more verdict instead of an over-fetched row. +// +// ONE PROVIDER, NAMESPACED SUBTESTS. Each newTestUOWProvider boots a real Dolt +// sql-server (measured at ~5s per boot on this machine, plus a one-time binary +// build), so a fixture per case would make this leg minutes long by itself. The +// conformance fixtures were designed for sharing — every case scopes its query +// to the rows it seeded, by id set, by label, or by exact id — so one database +// serves the suite. The subtests are deliberately NOT parallel: they share the +// database. + +func TestReaderContract(t *testing.T) { + ctx := context.Background() + provider := newUOWRoleFixtureProvider(t, ctx, "rdr") + fixture := newUOWReaderFixture(t, provider, "rdr") + + t.Run("ReadyDefaultTypeExclusionsYieldToAnExplicitType", func(t *testing.T) { + conformance.RunReaderReadyDefaultTypeExclusionsYieldToAnExplicitType(t, ctx, fixture) + }) + t.Run("ReadyDeferredAndEphemeralGates", func(t *testing.T) { + conformance.RunReaderReadyDeferredAndEphemeralGates(t, ctx, fixture) + }) + t.Run("ReadyLimitBoundary", func(t *testing.T) { + conformance.RunReaderReadyLimitBoundary(t, ctx, fixture) + }) + t.Run("OffsetIsHonoredOrRefused", func(t *testing.T) { + conformance.RunReaderOffsetIsHonoredOrRefused(t, ctx, fixture) + }) + t.Run("ReadySortPoliciesOrderTheSameRows", func(t *testing.T) { + conformance.RunReaderReadySortPoliciesOrderTheSameRows(t, ctx, fixture) + }) + t.Run("ListDefaultExclusionsAndTheirOverrides", func(t *testing.T) { + conformance.RunReaderListDefaultExclusionsAndTheirOverrides(t, ctx, fixture) + }) + t.Run("ListRejectsATypeOutsideTheWorkspaceVocabulary", func(t *testing.T) { + conformance.RunReaderListRejectsATypeOutsideTheWorkspaceVocabulary(t, ctx, fixture) + }) + t.Run("ListNaturalNumericIDSortTrimsAfterTheFetch", func(t *testing.T) { + conformance.RunReaderListNaturalNumericIDSortTrimsAfterTheFetch(t, ctx, fixture) + }) + t.Run("ListLimitBoundaryUnderASortTheDatabaseCanExpress", func(t *testing.T) { + conformance.RunReaderListLimitBoundaryUnderASortTheDatabaseCanExpress(t, ctx, fixture) + }) + t.Run("ReadySetOwnsItsStatusPinnedAndTemplateDecisions", func(t *testing.T) { + conformance.RunReaderReadySetOwnsItsStatusPinnedAndTemplateDecisions(t, ctx, fixture) + }) + t.Run("ListReadyFlagCarriesTheAssigneeAndPriorityFilters", func(t *testing.T) { + conformance.RunReaderListReadyFlagCarriesTheAssigneeAndPriorityFilters(t, ctx, fixture) + }) + t.Run("ListStatusAcceptsACommaSeparatedORSet", func(t *testing.T) { + conformance.RunReaderListStatusAcceptsACommaSeparatedORSet(t, ctx, fixture) + }) + t.Run("ListKeysetPositionResumesTheCreatedDescIDAscOrder", func(t *testing.T) { + conformance.RunReaderListKeysetPositionResumesTheCreatedDescIDAscOrder(t, ctx, fixture) + }) + t.Run("ListReadyFlagAnswersTheBlockerAwareSet", func(t *testing.T) { + conformance.RunReaderListReadyFlagAnswersTheBlockerAwareSet(t, ctx, fixture) + }) + t.Run("ListReadyFlagRefusesAFilterItCannotCarry", func(t *testing.T) { + conformance.RunReaderListReadyFlagRefusesAFilterItCannotCarry(t, ctx, fixture) + }) + t.Run("ListEmptyPageIsWellFormed", func(t *testing.T) { + conformance.RunReaderListEmptyPageIsWellFormed(t, ctx, fixture) + }) + t.Run("GetResolvesTheExactIDAcrossBothPlanes", func(t *testing.T) { + conformance.RunReaderGetResolvesTheExactIDAcrossBothPlanes(t, ctx, fixture) + }) + t.Run("GetOptionalRowListsAreOffByDefault", func(t *testing.T) { + conformance.RunReaderGetOptionalRowListsAreOffByDefault(t, ctx, fixture) + }) + t.Run("GetDetailShapeMatchesTheSeededIssue", func(t *testing.T) { + conformance.RunReaderGetDetailShapeMatchesTheSeededIssue(t, ctx, fixture) + }) + t.Run("DoesNotMutateTheCallerRequest", func(t *testing.T) { + conformance.RunReaderDoesNotMutateTheCallerRequest(t, ctx, fixture) + }) + // Last on purpose: the backend-failure half runs a request on a dead + // context, and this backend's provider is shared by every case above it. + t.Run("GetMissIsNotFoundAndBackendFailureDoesNotDecay", func(t *testing.T) { + conformance.RunReaderGetMissIsNotFoundAndBackendFailureDoesNotDecay(t, ctx, fixture) + }) +} + +// newUOWReaderFixture composes the shared role kit with the reader accessor. +// +// The role is reached through the provider's ACCESSOR, not NewIssueReader: the +// accessor is the door on this seam exactly as store.IssueReader() is on the +// other, and a wiring that called the constructor would be testing a reader no +// caller can obtain. +func newUOWReaderFixture(t *testing.T, provider UnitOfWorkProvider, prefix string) conformance.ReaderFixture { + t.Helper() + source, ok := provider.(IssueReaderSource) + if !ok { + t.Fatalf("provider %T does not offer the IssueReader accessor", provider) + } + reader, err := source.IssueReader() + if err != nil { + t.Fatalf("IssueReader(): %v", err) + } + kit := newUOWRoleFixtureKit(provider, prefix) + return conformance.ReaderFixture{ + IssuePrefix: kit.IssuePrefix, + Reader: reader, + CreateIssue: kit.CreateIssue, + CreateWisp: kit.CreateWisp, + AddDependency: kit.AddDependency, + // Not on the kit; see the same note in the server-backed wiring. + AddComment: func(ctx context.Context, issueID, author, text string) error { + return RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + _, err := uw.CommentUseCase().AddCommentToIssue(ctx, issueID, author, text) + return "bd: comment " + issueID, err + }) + }, + } +} diff --git a/internal/storage/uow/ready_claimer.go b/internal/storage/uow/ready_claimer.go new file mode 100644 index 000000000..835be8f8d --- /dev/null +++ b/internal/storage/uow/ready_claimer.go @@ -0,0 +1,129 @@ +package uow + +import ( + "context" + "fmt" + + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/internal/workapi" + publicops "github.com/steveyegge/beads/issueops" +) + +// ReadyClaimerSource is the capability accessor a unit-of-work provider offers +// for the claim role, named here for the same reason IssueReaderSource is: a +// consumer holding a provider by interface asks for the role instead of +// reaching for a constructor. +type ReadyClaimerSource interface { + ReadyClaimer() (publicops.ReadyClaimer, error) +} + +// readyClaimer takes ready work through a unit of work. +type readyClaimer struct { + provider UnitOfWorkProvider +} + +// ReadyClaimer returns the guarded take-ready-work surface for this provider. +func (p *doltSQLProvider) ReadyClaimer() (publicops.ReadyClaimer, error) { + return NewReadyClaimer(p) +} + +// NewReadyClaimer constructs a public ready claimer backed by provider. +func NewReadyClaimer(provider UnitOfWorkProvider) (publicops.ReadyClaimer, error) { + if isNilUnitOfWorkProvider(provider) { + return nil, fmt.Errorf("new ready claimer: unit-of-work provider must not be nil") + } + return &readyClaimer{provider: provider}, nil +} + +var _ publicops.ReadyClaimer = (*readyClaimer)(nil) + +// ClaimNext selects, claims and hydrates inside one unit of work. +// +// ONE UOW PER CALL, as it is for the reader: the method is request-granular, +// so a request and a transaction are the same span. A claim that found nothing +// names no commit message, which is how RunTxResult is told to commit nothing. +func (c *readyClaimer) ClaimNext(ctx context.Context, request publicops.ClaimNextRequest) (publicops.ClaimNextResult, error) { + if err := storageissueops.ValidateClaimNextRequest(request); err != nil { + return publicops.ClaimNextResult{}, err + } + // The same builder the sibling implementation and Reader.Ready run. + filter, err := workapi.BuildReadyFilter(request.Filter) + if err != nil { + return publicops.ClaimNextResult{}, err + } + return RunTxResult(ctx, c.provider, func(ctx context.Context, uw UnitOfWork) (publicops.ClaimNextResult, string, error) { + claimed, err := ClaimNextInUOW(ctx, uw, request.Actor, filter) + if err != nil { + return publicops.ClaimNextResult{}, "", err + } + if claimed == nil { + return publicops.ClaimNextResult{}, "", nil + } + // The same id-bearing message the store-backed sibling writes. The + // proxied route used to spell it "bd: ready --claim " while the + // direct route wrote "bd: claim ready "; one operation gets one + // entry, so the role settles it on the spelling both other backends + // already used. + return publicops.ClaimNextResult{Claimed: claimed}, + storageissueops.ClaimNextCommitMessage(claimed.ID), nil + }) +} + +// ClaimNextInUOW claims the first ready issue matching filter in uw and +// hydrates it there. It is shared with the batch closer, whose claim runs in +// the closes' transaction rather than one of its own — the same selection, the +// same hydration, reached the one way. +// +// A nil issue with a nil error is the ordinary empty-front outcome. +func ClaimNextInUOW(ctx context.Context, uw UnitOfWork, actor string, filter types.WorkFilter) (*types.IssueWithCounts, error) { + claimed, err := uw.IssueUseCase().ClaimReadyIssue(ctx, filter, actor) + if err != nil { + return nil, err + } + if !claimed.Claimed || claimed.Issue == nil { + return nil, nil + } + return hydrateReadyRow(ctx, uw, claimed.Issue) +} + +// hydrateReadyRow fills in the relationship cardinalities a ready row carries, +// reading them in the caller's unit of work so the counts describe the state +// that transaction is about to commit. A failed count read is an error rather +// than a zero, matching the store-backed sibling: a result nobody can hydrate +// is not a result. +func hydrateReadyRow(ctx context.Context, uw UnitOfWork, issue *types.Issue) (*types.IssueWithCounts, error) { + ids := []string{issue.ID} + depCounts, err := uw.DependencyUseCase().CountsByIssueIDs(ctx, ids) + if err != nil { + return nil, fmt.Errorf("hydrate ready row %s: dependency counts: %w", issue.ID, err) + } + records, err := uw.DependencyUseCase().GetForIssueIDs(ctx, ids) + if err != nil { + return nil, fmt.Errorf("hydrate ready row %s: dependency records: %w", issue.ID, err) + } + commentCounts, err := uw.CommentUseCase().GetCommentCounts(ctx, ids) + if err != nil { + return nil, fmt.Errorf("hydrate ready row %s: comment counts: %w", issue.ID, err) + } + + issue.Dependencies = records[issue.ID] + counts := depCounts[issue.ID] + if counts == nil { + counts = &types.DependencyCounts{} + } + var parent *string + for _, dep := range records[issue.ID] { + if dep.Type == types.DepParentChild { + parent = &dep.DependsOnID + break + } + } + return &types.IssueWithCounts{ + Issue: issue, + DependencyCount: counts.DependencyCount, + DependentCount: counts.DependentCount, + CommentCount: commentCounts[issue.ID], + Parent: parent, + }, nil +} diff --git a/internal/storage/uow/ready_claimer_contract_test.go b/internal/storage/uow/ready_claimer_contract_test.go new file mode 100644 index 000000000..5c7c030c9 --- /dev/null +++ b/internal/storage/uow/ready_claimer_contract_test.go @@ -0,0 +1,74 @@ +package uow + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/backend/conformance" +) + +// TestReadyClaimerContract runs the whole ReadyClaimer contract against ONE +// provider, as subtests, and that shape is the point rather than a detail. +// +// Every newTestUOWProvider boots a real Dolt sql-server, so a wiring with one +// test function per case pays that boot per case and a five-role suite pays it +// forty times; the conformance fixtures were designed to be shared precisely so +// it does not have to. IssuePrefix namespaces the ids each case seeds, and the +// contract additionally scopes every case's ready question to a label only that +// case uses, so cases cannot claim each other's rows out of the one database. +// +// NO t.Parallel, ANYWHERE IN HERE. This backend has no per-test copy-on-write +// branch, so dolt_log and the event tables are database-global; a parallel +// subtest would corrupt another subtest's history-delta arithmetic. The two +// store backends get isolation for free and their wirings are one function per +// case; this one buys it with sequencing. +func TestReadyClaimerContract(t *testing.T) { + ctx := context.Background() + fixture := newUOWReadyClaimerFixture(t, ctx, "rc") + + for _, test := range []struct { + name string + run func(*testing.T, context.Context, conformance.ReadyClaimerFixture) + }{ + {name: "RejectsLimitOffsetAndEmptyActor", run: conformance.RunReadyClaimerRejectsLimitOffsetAndEmptyActor}, + {name: "EmptyFrontIsNormal", run: conformance.RunReadyClaimerEmptyFrontIsNormal}, + {name: "ClaimsTheFrontRowAndReturnsThePostClaimState", run: conformance.RunReadyClaimerClaimsTheFrontRowAndReturnsThePostClaimState}, + {name: "ClaimsAnEphemeralRowTheFilterAdmits", run: conformance.RunReadyClaimerClaimsAnEphemeralRowTheFilterAdmits}, + {name: "LeavesEphemeralRowsOutOfTheDefaultReadySet", run: conformance.RunReadyClaimerLeavesEphemeralRowsOutOfTheDefaultReadySet}, + {name: "LeasesADurableWinButNotAnEphemeralOne", run: conformance.RunReadyClaimerLeasesADurableWinButNotAnEphemeralOne}, + {name: "AnswersTheQuestionReaderReadyLists", run: conformance.RunReadyClaimerAnswersTheQuestionReaderReadyLists}, + {name: "SkipsIneligibleFrontRows", run: conformance.RunReadyClaimerSkipsIneligibleFrontRows}, + {name: "RecordsOneHistoryEntryForAWin", run: conformance.RunReadyClaimerRecordsOneHistoryEntryForAWin}, + {name: "DoesNotMutateTheCallerRequest", run: conformance.RunReadyClaimerDoesNotMutateTheCallerRequest}, + } { + t.Run(test.name, func(t *testing.T) { + test.run(t, ctx, fixture) + }) + } +} + +// newUOWReadyClaimerFixture composes the frozen role kit with this backend's +// two accessors over one provider. +func newUOWReadyClaimerFixture(t *testing.T, ctx context.Context, prefix string) conformance.ReadyClaimerFixture { + t.Helper() + provider := newUOWRoleFixtureProvider(t, ctx, prefix) + claimer, err := NewReadyClaimer(provider) + if err != nil { + t.Fatalf("NewReadyClaimer: %v", err) + } + reader, err := NewIssueReader(provider) + if err != nil { + t.Fatalf("NewIssueReader: %v", err) + } + kit := newUOWRoleFixtureKit(provider, prefix) + return conformance.ReadyClaimerFixture{ + IssuePrefix: kit.IssuePrefix, + Claimer: claimer, + Reader: reader, + CreateIssue: kit.CreateIssue, + CreateWisp: kit.CreateWisp, + AddDependency: kit.AddDependency, + QueryScalar: kit.QueryScalar, + CountHistory: kit.CountHistory, + } +} diff --git a/internal/storage/uow/relations.go b/internal/storage/uow/relations.go new file mode 100644 index 000000000..9db1a0815 --- /dev/null +++ b/internal/storage/uow/relations.go @@ -0,0 +1,76 @@ +package uow + +import ( + "context" + "fmt" + + "github.com/steveyegge/beads/internal/storage/domain" + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/internal/workapi" + publicops "github.com/steveyegge/beads/issueops" +) + +// RelationsSource is the capability accessor a unit-of-work provider offers +// for the neighbor-query role, the sibling of IssueReaderSource. +type RelationsSource interface { + IssueRelations() (publicops.Relations, error) +} + +// issueRelations answers neighbor queries through a unit of work. +type issueRelations struct { + provider UnitOfWorkProvider +} + +// IssueRelations returns the guarded neighbor-query surface for this provider. +func (p *doltSQLProvider) IssueRelations() (publicops.Relations, error) { + return NewIssueRelations(p) +} + +// NewIssueRelations constructs public neighbor queries backed by provider. +func NewIssueRelations(provider UnitOfWorkProvider) (publicops.Relations, error) { + if isNilUnitOfWorkProvider(provider) { + return nil, fmt.Errorf("new issue relations: unit-of-work provider must not be nil") + } + return &issueRelations{provider: provider}, nil +} + +var _ publicops.Relations = (*issueRelations)(nil) + +// Related answers one neighbor query inside one unit of work. +// +// The anchor probe is workapi.GetIssueOrWisp, the same issue-then-wisp +// fallback Reader.Get runs, so "no such issue" means the same thing on both +// roles. The type filter and the order are storageissueops.FinishRelatedPage — +// the one function the store-backed sibling also calls, for the reason +// workapi.FinishPage is shared: an ordering each implementation applies for +// itself is an ordering the two will eventually disagree about. +func (r *issueRelations) Related(ctx context.Context, request publicops.RelatedRequest) ([]*publicops.RelatedIssue, error) { + if err := storageissueops.ValidateRelatedRequest(request); err != nil { + return nil, err + } + direction := domain.DepDirectionOut + if request.Direction == publicops.RelationIn { + direction = domain.DepDirectionIn + } + return RunTxRead(ctx, r.provider, func(ctx context.Context, uw UnitOfWork) ([]*publicops.RelatedIssue, error) { + issue, isWisp, err := workapi.GetIssueOrWisp(ctx, workapi.NewUOWDetailSource(uw), request.ID) + if err != nil { + return nil, err + } + filter := domain.DepListFilter{Direction: direction} + var items []*publicops.RelatedIssue + if isWisp { + items, err = uw.DependencyUseCase().ListWispWithIssueMetadata(ctx, issue.ID, filter) + } else { + items, err = uw.DependencyUseCase().ListWithIssueMetadata(ctx, issue.ID, filter) + } + if err != nil { + return nil, err + } + // The filter runs HERE rather than in the use-case call above so both + // implementations narrow and order through one function; passing + // filter.Types down would put the narrowing in the query on one side + // and in Go on the other. + return storageissueops.FinishRelatedPage(items, request.Types), nil + }) +} diff --git a/internal/storage/uow/relations_contract_test.go b/internal/storage/uow/relations_contract_test.go new file mode 100644 index 000000000..eb7ecb34a --- /dev/null +++ b/internal/storage/uow/relations_contract_test.go @@ -0,0 +1,62 @@ +package uow + +import ( + "context" + "testing" + + "github.com/steveyegge/beads/backend/conformance" +) + +// TestRelationsContract runs the whole Relations contract against ONE +// unit-of-work provider. +// +// One provider, subtests, and NO t.Parallel. Every provider boots a real Dolt +// sql-server, so a case-per-provider suite pays that boot nine times; the +// contract fixtures were designed for sharing, and IssuePrefix namespaces what +// each case seeds. The no-parallel half matters because this backend has no +// per-test copy-on-write branch — the tables are database-global here. +func TestRelationsContract(t *testing.T) { + ctx := context.Background() + fixture := newUOWRelationsFixture(t, ctx, "rel") + + for _, test := range []struct { + name string + run func(*testing.T, context.Context, conformance.RelationsFixture) + }{ + {"AnswersInThePinnedOrder", conformance.RunRelationsAnswersInThePinnedOrder}, + {"OrdersNeighborsFromBothPlanesTogether", conformance.RunRelationsOrdersNeighborsFromBothPlanesTogether}, + {"AnswersAWispTargetInTheOutDirection", conformance.RunRelationsAnswersAWispTargetInTheOutDirection}, + {"RefusesTheZeroDirection", conformance.RunRelationsRefusesTheZeroDirection}, + {"SeparatesNoNeighborsFromNoSuchIssue", conformance.RunRelationsSeparatesNoNeighborsFromNoSuchIssue}, + {"ResolvesAWispAnchor", conformance.RunRelationsResolvesAWispAnchor}, + {"FiltersByAnOpenTypeVocabulary", conformance.RunRelationsFiltersByAnOpenTypeVocabulary}, + {"RefusesAnUnusableTypeFilter", conformance.RunRelationsRefusesAnUnusableTypeFilter}, + {"RefusesATypeFilterOverTheColumnLength", conformance.RunRelationsRefusesATypeFilterOverTheColumnLength}, + {"DirectionSelectsTheInverseGraph", conformance.RunRelationsDirectionSelectsTheInverseGraph}, + {"LeavesTheCallersRequestAlone", conformance.RunRelationsLeavesTheCallersRequestAlone}, + {"LeavesAnExternalTargetOutOfTheAnswer", conformance.RunRelationsLeavesAnExternalTargetOutOfTheAnswer}, + {"ResolvesTheAnchorIDExactly", conformance.RunRelationsResolvesTheAnchorIDExactly}, + } { + t.Run(test.name, func(t *testing.T) { + test.run(t, ctx, fixture) + }) + } +} + +func newUOWRelationsFixture(t *testing.T, ctx context.Context, prefix string) conformance.RelationsFixture { + t.Helper() + provider := newUOWRoleFixtureProvider(t, ctx, prefix) + relations, err := NewIssueRelations(provider) + if err != nil { + t.Fatalf("NewIssueRelations: %v", err) + } + kit := newUOWRoleFixtureKit(provider, prefix) + return conformance.RelationsFixture{ + IssuePrefix: kit.IssuePrefix, + Relations: relations, + CreateIssue: kit.CreateIssue, + CreateWisp: kit.CreateWisp, + AddDependency: kit.AddDependency, + QueryScalar: kit.QueryScalar, + } +} diff --git a/internal/storage/uow/role_fixture_kit_test.go b/internal/storage/uow/role_fixture_kit_test.go new file mode 100644 index 000000000..add38f60d --- /dev/null +++ b/internal/storage/uow/role_fixture_kit_test.go @@ -0,0 +1,417 @@ +package uow + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/steveyegge/beads/backend/conformance" + "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/types" +) + +// roleFixtureKit is the unit-of-work backend's answer to the hooks every +// issueops role fixture in package conformance needs. A role's wiring file +// composes one of these with the accessor under test and the IssuePrefix, so +// the seeding and scalar-query plumbing is written once per backend instead of +// once per role. +// +// The field names and signatures are IDENTICAL across the three backends' +// kits, and identical to the fields the conformance fixtures declare, so a kit +// closure is assignable to any role fixture with no adapter in between. That +// sameness is the point of the type; changing a signature here is a change to +// all three backends and to every role wiring at once. +// +// FROZEN SURFACE. This file is owned by the scaffolding slice (bd-kue5t) and +// no role slice edits it. A role that needs a hook this kit does not expose +// routes the addition through a follow-up commit against that bead, so the +// three kits never drift apart in a worktree. +// +// NAMING CONVENTION FOR EVERYTHING BUILT ON THIS KIT: every unexported helper a +// role slice adds — in package conformance and in the per-backend wiring files — +// is ROLE-PREFIXED (seedRelationsAnchor, assertCommenterEventCount), the way the +// existing contract already names seedDependencyEditorIssue and +// assertDependencyEdgeCount. Five slices add files to one package from separate +// worktrees; two of them each defining a bare seedIssue would compile alone and +// break combined. The scaffolding's own helpers are prefixed roleFixtureKit for +// the same reason. +type roleFixtureKit struct { + // IssuePrefix namespaces the ids each assertion seeds, so several + // assertions can share one database. + IssuePrefix string + // CreateIssue seeds a durable issue in the issues plane. + CreateIssue func(context.Context, *types.Issue, string) error + // CreateWisp seeds an ephemeral issue in the wisps plane. It is a separate + // field rather than a flag because the three backends reach the two planes + // through different verbs. + CreateWisp func(context.Context, *types.Issue, string) error + // AddDependency seeds ONE edge, routed to the plane the edge's SOURCE lives + // in, and RECORDS a dependency_added event. + // + // The event is not incidental. This backend has no event-free route to the + // dependency tables — both domain.DependencyUseCase.add and AddDependencies + // hard-code EmitEvent: true — while the two store backends default the + // other way (dolt/dependencies.go:20-26 "adds a dependency between two + // issues WITHOUT recording a dependency_added event"). Rather than let the + // same seed leave different rows behind on different backends, all three + // kits emit. A contract case that counts events must therefore take a DELTA + // around the operation under test; an absolute count taken after seeding + // edges counts the seeds too. + // + // SPEC-GAP bd-yby99.1: no issueops leaf doc says whether a structural + // dependency insert records an event, so the kits normalise rather than + // pick a winner. The owner adjudicates it with the rest of the batch. + AddDependency func(context.Context, *types.Dependency, string) error + // SetConfig writes one workspace config key, which is how a case installs + // the vocabulary (excluded types, default limits) a request is read against. + SetConfig func(context.Context, string, string) error + // QueryScalar runs a single-row query and scans it, and RETURNS the error + // rather than failing the test, so a case can assert on a query that is + // expected to fail. + QueryScalar func(context.Context, string, []any, ...any) error + // CountHistory reports how many history entries the fixture's branch has, + // for the "at most one entry per call, none when nothing landed" clause the + // role contracts state. Cases take it before and after rather than reading + // the top of the log, because two commits made inside one second tie on + // date and their relative order is not something to rely on. + // + // A nil CountHistory means "this backend cannot observe history here". A + // case that needs it must then skip LOUDLY with that reason rather than + // pass quietly. It is non-nil here: see + // TestUOWRoleFixtureKitCountHistoryMovesWithACommit for the evidence. + CountHistory func(context.Context) (int, error) +} + +// roleFixtureKitComposesConformanceFixtures is the compile-time half of the +// kit's promise: every hook is assignable to the fixture field of the same +// name with NO adapter in between. A signature drifting apart from the +// conformance fixtures breaks here, in the frozen file that owns the +// signatures, instead of in five role wirings at once. +var roleFixtureKitComposesConformanceFixtures = func(kit roleFixtureKit) (conformance.DependencyEditorFixture, conformance.IssueOperationsStagingFixture) { + return conformance.DependencyEditorFixture{ + IssuePrefix: kit.IssuePrefix, + CreateIssue: kit.CreateIssue, + CreateWisp: kit.CreateWisp, + QueryScalar: kit.QueryScalar, + }, conformance.IssueOperationsStagingFixture{ + IssuePrefix: kit.IssuePrefix, + CreateIssue: kit.CreateIssue, + AddDependency: kit.AddDependency, + SetConfig: kit.SetConfig, + QueryScalar: kit.QueryScalar, + } +} + +// newUOWRoleFixtureProvider boots one provider for a whole role suite and +// points its workspace prefix at the ids that suite will seed. +// +// ONE PROVIDER PER ROLE SUITE, not per case. Each call boots a real Dolt +// sql-server, so a role that builds a fresh provider per test function pays +// that boot for every case; the conformance fixtures were designed for sharing +// precisely so it does not have to (IssuePrefix namespaces the seeded ids). +// +// NO t.Parallel IN A SUITE THAT MEASURES COUNT DELTAS ON THIS BACKEND. The +// server-backed store gives each test its own copy-on-write branch; this one +// does not. dolt_log and the event tables are database-global here, so a +// parallel subtest sharing the provider corrupts another subtest's before/after +// arithmetic. +func newUOWRoleFixtureProvider(t *testing.T, ctx context.Context, prefix string) UnitOfWorkProvider { + t.Helper() + provider := newTestUOWProvider(t) + if err := RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + return "bd: set issue prefix", uw.ConfigUseCase().SetConfig(ctx, "issue_prefix", prefix) + }); err != nil { + t.Fatalf("set issue_prefix to %q: %v", prefix, err) + } + return provider +} + +// newUOWRoleFixtureKit builds the kit for a provider from +// newUOWRoleFixtureProvider. Every hook is one unit of work: this backend has +// no ambient connection a test can write through, so seeding is the same +// RunTx/RunTxRead shape the production code uses. +func newUOWRoleFixtureKit(provider UnitOfWorkProvider, prefix string) roleFixtureKit { + seed := func(wisp bool) func(context.Context, *types.Issue, string) error { + return func(ctx context.Context, issue *types.Issue, actor string) error { + return RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + params := domain.CreateIssueParams{ + Issue: issue, + ExplicitID: issue.ID, + Labels: append([]string(nil), issue.Labels...), + CreateOnly: true, + } + var err error + if wisp { + _, err = uw.IssueUseCase().CreateWisp(ctx, params, actor) + } else { + _, err = uw.IssueUseCase().CreateIssue(ctx, params, actor) + } + return "seed " + issue.ID, err + }) + } + } + queryScalar := func(ctx context.Context, query string, args []any, dest ...any) error { + row, err := RunTxRead(ctx, provider, func(ctx context.Context, uw UnitOfWork) ([]any, error) { + result, err := uw.RawSQLUseCase().Query(ctx, query, args...) + if err != nil { + return nil, err + } + if len(result.Rows) != 1 { + return nil, fmt.Errorf("query %q returned %d rows, want 1", query, len(result.Rows)) + } + return result.Rows[0], nil + }) + if err != nil { + return err + } + if len(row) != len(dest) { + return fmt.Errorf("query %q returned %d columns, want %d", query, len(row), len(dest)) + } + for i, target := range dest { + if err := scanRawSQLValue(target, row[i]); err != nil { + return fmt.Errorf("query %q column %d: %w", query, i, err) + } + } + return nil + } + return roleFixtureKit{ + IssuePrefix: prefix, + CreateIssue: seed(false), + CreateWisp: seed(true), + AddDependency: func(ctx context.Context, dep *types.Dependency, actor string) error { + return RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + // The source-routed bulk verb, not the plane-pinned single one: + // it is what makes this seed land the edge in the same plane the + // two store backends' AddDependency lands it in. + _, err := uw.DependencyUseCase().AddDependencies(ctx, []*types.Dependency{dep}, actor, domain.BulkAddDepsOpts{}) + return "seed dependency " + dep.IssueID + " -> " + dep.DependsOnID, err + }) + }, + SetConfig: func(ctx context.Context, key, value string) error { + return RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + return "set " + key, uw.ConfigUseCase().SetConfig(ctx, key, value) + }) + }, + QueryScalar: queryScalar, + CountHistory: func(ctx context.Context) (int, error) { + var entries int + err := queryScalar(ctx, "SELECT COUNT(*) FROM dolt_log", nil, &entries) + return entries, err + }, + } +} + +// skipKnownDivergence parks one conformance case on the backend that disagrees +// with the leaf contract's doc comment. +// +// The contract case asserts what the doc promises, so a genuine disagreement is +// a behaviour-unification decision for the owner rather than something a test +// slice may settle by weakening the assertion. Parking at the WIRING site (never +// inside the shared Run function) keeps the case running and passing on the +// backends that agree, so their behaviour is pinned the day the divergence is +// found. The "KNOWN DIVERGENCE" prefix is literal so `grep -r "KNOWN DIVERGENCE"` +// finds every parked case, and beadID names the child of bd-yby99 that records +// the three-way observed behaviour. +func skipKnownDivergence(t *testing.T, beadID, reason string) { + t.Helper() + t.Skipf("KNOWN DIVERGENCE %s: %s", beadID, reason) +} + +// TestScanRawSQLValueCoversTheContractDestinations pins the scan-destination +// set the role contracts depend on. It needs no database, so a wiring that +// scans into an unsupported type is caught here in milliseconds rather than +// after a Dolt server boot. +func TestScanRawSQLValueCoversTheContractDestinations(t *testing.T) { + stamp := time.Date(2026, 8, 2, 19, 49, 5, 123456000, time.UTC) + + var ( + gotInt int + gotInt64 int64 + gotBool bool + gotFloat float64 + gotString string + gotTime time.Time + gotTimeRaw time.Time + ) + for _, test := range []struct { + name string + value any + dest any + want any + got func() any + }{ + {"int from bytes", []byte("3"), &gotInt, 3, func() any { return gotInt }}, + {"int64 from string", "9007199254740993", &gotInt64, int64(9007199254740993), func() any { return gotInt64 }}, + {"bool from tinyint", int64(1), &gotBool, true, func() any { return gotBool }}, + {"bool from text", []byte("false"), &gotBool, false, func() any { return gotBool }}, + {"float64", "2.5", &gotFloat, 2.5, func() any { return gotFloat }}, + {"string from NULL", nil, &gotString, "", func() any { return gotString }}, + {"time from driver value", stamp, &gotTimeRaw, stamp, func() any { return gotTimeRaw }}, + {"time from text", "2026-08-02 19:49:05.123456", &gotTime, stamp, func() any { return gotTime }}, + } { + t.Run(test.name, func(t *testing.T) { + if err := scanRawSQLValue(test.dest, test.value); err != nil { + t.Fatalf("scanRawSQLValue(%T, %v): %v", test.dest, test.value, err) + } + if got := test.got(); got != test.want { + t.Fatalf("scanned %#v, want %#v", got, test.want) + } + }) + } + + // NULL must fail loudly for every destination that cannot represent it, + // rather than decay to a zero a count case would read as a real answer. + for _, dest := range []any{&gotInt, &gotInt64, &gotBool, &gotFloat, &gotTime} { + if err := scanRawSQLValue(dest, nil); err == nil { + t.Fatalf("scanRawSQLValue(%T, NULL) = nil error, want a refusal", dest) + } + } + if err := scanRawSQLValue(new(uint), 1); err == nil { + t.Fatal("scanRawSQLValue accepted an unsupported destination") + } +} + +// TestUOWRoleFixtureKitHooksAreUsable is the scaffolding's own tripwire: every +// hook the role fixtures compose is exercised once here, so a kit broken by a +// signature change fails in one obvious place instead of five role suites. +func TestUOWRoleFixtureKitHooksAreUsable(t *testing.T) { + ctx := context.Background() + provider := newUOWRoleFixtureProvider(t, ctx, "kit") + + assertRoleFixtureKitHooksAreUsable(t, ctx, newUOWRoleFixtureKit(provider, "kit")) +} + +// assertRoleFixtureKitHooksAreUsable drives every hook once and checks the rows +// landed where the field docs say they land. It pins the FIXTURE, not a role, +// and is deliberately a byte-for-byte sibling of the same helper in the other +// two backends' kit files so the three can be diffed. +func assertRoleFixtureKitHooksAreUsable(t *testing.T, ctx context.Context, kit roleFixtureKit) { + t.Helper() + issue := kit.IssuePrefix + "-kit-issue" + target := kit.IssuePrefix + "-kit-target" + wisp := kit.IssuePrefix + "-kit-wisp" + + for _, id := range []string{issue, target} { + if err := kit.CreateIssue(ctx, &types.Issue{ + ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, + }, "seed"); err != nil { + t.Fatalf("kit.CreateIssue(%s): %v", id, err) + } + } + if err := kit.CreateWisp(ctx, &types.Issue{ + ID: wisp, Title: wisp, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: true, + }, "seed"); err != nil { + t.Fatalf("kit.CreateWisp(%s): %v", wisp, err) + } + if err := kit.AddDependency(ctx, &types.Dependency{ + IssueID: issue, DependsOnID: target, Type: types.DepBlocks, + }, "seed"); err != nil { + t.Fatalf("kit.AddDependency: %v", err) + } + if err := kit.SetConfig(ctx, "role_fixture_kit_probe", "on"); err != nil { + t.Fatalf("kit.SetConfig: %v", err) + } + + var issues, wisps, edges int + if err := kit.QueryScalar(ctx, "SELECT COUNT(*) FROM issues WHERE id IN (?, ?)", []any{issue, target}, &issues); err != nil { + t.Fatalf("kit.QueryScalar issues: %v", err) + } + if issues != 2 { + t.Fatalf("seeded durable issues = %d, want 2", issues) + } + if err := kit.QueryScalar(ctx, "SELECT COUNT(*) FROM wisps WHERE id = ?", []any{wisp}, &wisps); err != nil { + t.Fatalf("kit.QueryScalar wisps: %v", err) + } + if wisps != 1 { + t.Fatalf("seeded wisps = %d, want 1 — CreateWisp did not reach the ephemeral plane", wisps) + } + if err := kit.QueryScalar(ctx, + // The target's own class decides which typed column holds it, so the + // contracts resolve it through this COALESCE rather than one column. + "SELECT COUNT(*) FROM dependencies WHERE issue_id = ? AND "+ + "COALESCE(depends_on_issue_id, depends_on_wisp_id, depends_on_external) = ?", + []any{issue, target}, &edges); err != nil { + t.Fatalf("kit.QueryScalar dependencies: %v", err) + } + if edges != 1 { + t.Fatalf("seeded edges = %d, want 1", edges) + } + var configured string + if err := kit.QueryScalar(ctx, "SELECT value FROM config WHERE `key` = ?", []any{"role_fixture_kit_probe"}, &configured); err != nil { + t.Fatalf("kit.QueryScalar config: %v", err) + } + if configured != "on" { + t.Fatalf("configured value = %q, want %q", configured, "on") + } + + if kit.CountHistory == nil { + t.Fatal("kit.CountHistory is nil — this backend cannot observe history, which the role contracts' entry-per-call clause needs") + } + entries, err := kit.CountHistory(ctx) + if err != nil { + t.Fatalf("kit.CountHistory: %v", err) + } + if entries < 1 { + t.Fatalf("history entries = %d, want at least the initializing commit", entries) + } +} + +// TestUOWRoleFixtureKitCountHistoryMovesWithACommit answers the one open +// research question the design left to the scaffolding slice: can this +// backend's fixture observe dolt_log at all? +// +// It can. RawSQLUseCase.Query is an unfiltered pass-through to the transaction's +// runner (domain/db/raw_sql.go — no table allow-list anywhere in the chain), the +// provider is a real Dolt sql-server, and every RunTx that returns a non-empty +// commit message ends in CALL DOLT_COMMIT (uow/doltserver_tx.go:23-31). So a +// versioned unit of work is visible as a dolt_log row from inside a later +// read-only unit of work, which is exactly what the role contracts' "at most one +// history entry per call, none when nothing landed" clause needs. +// +// The consequence of that answer is what matters: CountHistory is NON-NIL on all +// three fixtures, so the entry-per-call cases run on all three and the clause is +// pinned on the uow body as well as on the body dolt and embeddeddolt share. +// Had the answer been no, those cases would have skipped here and the clause +// would have been pinned only on two implementations that share ONE body — one +// vote, not two — on exactly the axis where the claim-message divergence lived +// (uow/ready_claimer.go:60-66). +func TestUOWRoleFixtureKitCountHistoryMovesWithACommit(t *testing.T) { + ctx := context.Background() + provider := newUOWRoleFixtureProvider(t, ctx, "kithist") + kit := newUOWRoleFixtureKit(provider, "kithist") + + before, err := kit.CountHistory(ctx) + if err != nil { + t.Fatalf("CountHistory before: %v", err) + } + if before < 1 { + t.Fatalf("history entries = %d before any test write, want at least the initializing commit", before) + } + if err := kit.SetConfig(ctx, "role_fixture_kit_history_probe", "on"); err != nil { + t.Fatalf("SetConfig: %v", err) + } + after, err := kit.CountHistory(ctx) + if err != nil { + t.Fatalf("CountHistory after: %v", err) + } + if after != before+1 { + t.Fatalf("history entries went %d -> %d across one committed unit of work, want exactly one more", before, after) + } + + // A unit of work that writes nothing must not move the log either — the + // "none when nothing landed" half of the same clause, proven on the fixture + // so a role case can rely on it. + if err := RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { + return "", nil + }); err != nil { + t.Fatalf("empty unit of work: %v", err) + } + idle, err := kit.CountHistory(ctx) + if err != nil { + t.Fatalf("CountHistory after an empty unit of work: %v", err) + } + if idle != after { + t.Fatalf("history entries went %d -> %d across a unit of work that committed nothing, want no change", after, idle) + } +} diff --git a/internal/telemetry/batch_closer.go b/internal/telemetry/batch_closer.go new file mode 100644 index 000000000..30901dcb4 --- /dev/null +++ b/internal/telemetry/batch_closer.go @@ -0,0 +1,39 @@ +package telemetry + +import ( + "context" + + "github.com/steveyegge/beads/issueops" +) + +// BatchCloser returns the inner store's batch-close surface wrapped in this +// layer's instrumentation. It recurses instead of delegating: a blind +// delegation would return the inner closer unspanned and untimed. +func (s *InstrumentedStorage) BatchCloser() (issueops.BatchCloser, error) { + inner, err := s.Unwrap().BatchCloser() + if err != nil { + return nil, err + } + return s.WrapBatchCloser(inner), nil +} + +// WrapBatchCloser instruments guarded batch closes with this storage layer's +// existing telemetry meter and tracer. +func (s *InstrumentedStorage) WrapBatchCloser(inner issueops.BatchCloser) issueops.BatchCloser { + return &instrumentedBatchCloser{storage: s, inner: inner} +} + +type instrumentedBatchCloser struct { + storage *InstrumentedStorage + inner issueops.BatchCloser +} + +// CloseBatch is ONE span over the whole request, because the request is the +// transaction: a span per item would time N things that cannot fail or commit +// independently and would hide the only duration anyone can act on. +func (o *instrumentedBatchCloser) CloseBatch(ctx context.Context, request issueops.CloseBatchRequest) (result issueops.CloseBatchResult, err error) { + ctx, span, started := o.storage.op(ctx, "BatchCloser.CloseBatch") + result, err = o.inner.CloseBatch(ctx, request) + o.storage.done(ctx, span, started, err) + return result, err +} diff --git a/internal/telemetry/commenter.go b/internal/telemetry/commenter.go new file mode 100644 index 000000000..aa912a0da --- /dev/null +++ b/internal/telemetry/commenter.go @@ -0,0 +1,36 @@ +package telemetry + +import ( + "context" + + "github.com/steveyegge/beads/issueops" +) + +// Commenter returns the inner store's add-comment surface wrapped in this +// layer's instrumentation. It recurses instead of delegating: a blind +// delegation would return the inner commenter unspanned and untimed. +func (s *InstrumentedStorage) Commenter() (issueops.Commenter, error) { + inner, err := s.Unwrap().Commenter() + if err != nil { + return nil, err + } + return s.WrapCommenter(inner), nil +} + +// WrapCommenter instruments guarded comment writes with this storage layer's +// existing telemetry meter and tracer. +func (s *InstrumentedStorage) WrapCommenter(inner issueops.Commenter) issueops.Commenter { + return &instrumentedCommenter{storage: s, inner: inner} +} + +type instrumentedCommenter struct { + storage *InstrumentedStorage + inner issueops.Commenter +} + +func (c *instrumentedCommenter) AddComment(ctx context.Context, request issueops.AddCommentRequest) (result issueops.AddCommentResult, err error) { + ctx, span, started := c.storage.op(ctx, "Commenter.AddComment") + result, err = c.inner.AddComment(ctx, request) + c.storage.done(ctx, span, started, err) + return result, err +} diff --git a/internal/telemetry/dependency_editor.go b/internal/telemetry/dependency_editor.go new file mode 100644 index 000000000..7a60dca64 --- /dev/null +++ b/internal/telemetry/dependency_editor.go @@ -0,0 +1,46 @@ +package telemetry + +import ( + "context" + + "github.com/steveyegge/beads/issueops" +) + +// DependencyEditor returns the inner store's dependency-edge surface wrapped +// in this layer's instrumentation. It recurses instead of delegating: a blind +// delegation would return the inner editor unspanned and untimed. +func (s *InstrumentedStorage) DependencyEditor() (issueops.DependencyEditor, error) { + inner, err := s.Unwrap().DependencyEditor() + if err != nil { + return nil, err + } + return s.WrapDependencyEditor(inner), nil +} + +// WrapDependencyEditor instruments guarded dependency edits with this storage +// layer's existing telemetry meter and tracer. +func (s *InstrumentedStorage) WrapDependencyEditor(inner issueops.DependencyEditor) issueops.DependencyEditor { + return &instrumentedDependencyEditor{storage: s, inner: inner} +} + +type instrumentedDependencyEditor struct { + storage *InstrumentedStorage + inner issueops.DependencyEditor +} + +// AddDependencies is ONE span over the whole request, because the request is +// the transaction: a span per edge would time N things that cannot fail or +// commit independently. +func (e *instrumentedDependencyEditor) AddDependencies(ctx context.Context, request issueops.AddDependenciesRequest) (result issueops.AddDependenciesResult, err error) { + ctx, span, started := e.storage.op(ctx, "DependencyEditor.AddDependencies") + result, err = e.inner.AddDependencies(ctx, request) + e.storage.done(ctx, span, started, err) + return result, err +} + +func (e *instrumentedDependencyEditor) RemoveDependency(ctx context.Context, request issueops.RemoveDependencyRequest) (result issueops.RemoveDependencyResult, err error) { + ctx, span, started := e.storage.op(ctx, "DependencyEditor.RemoveDependency") + result, err = e.inner.RemoveDependency(ctx, request) + e.storage.done(ctx, span, started, err) + return result, err +} diff --git a/internal/telemetry/ready_claimer.go b/internal/telemetry/ready_claimer.go new file mode 100644 index 000000000..c85f427f6 --- /dev/null +++ b/internal/telemetry/ready_claimer.go @@ -0,0 +1,36 @@ +package telemetry + +import ( + "context" + + "github.com/steveyegge/beads/issueops" +) + +// ReadyClaimer returns the inner store's claim surface wrapped in this layer's +// instrumentation. It recurses instead of delegating: a blind delegation would +// return the inner claimer unspanned and untimed. +func (s *InstrumentedStorage) ReadyClaimer() (issueops.ReadyClaimer, error) { + inner, err := s.Unwrap().ReadyClaimer() + if err != nil { + return nil, err + } + return s.WrapReadyClaimer(inner), nil +} + +// WrapReadyClaimer instruments guarded ready claims with this storage layer's +// existing telemetry meter and tracer. +func (s *InstrumentedStorage) WrapReadyClaimer(inner issueops.ReadyClaimer) issueops.ReadyClaimer { + return &instrumentedReadyClaimer{storage: s, inner: inner} +} + +type instrumentedReadyClaimer struct { + storage *InstrumentedStorage + inner issueops.ReadyClaimer +} + +func (c *instrumentedReadyClaimer) ClaimNext(ctx context.Context, request issueops.ClaimNextRequest) (result issueops.ClaimNextResult, err error) { + ctx, span, started := c.storage.op(ctx, "ReadyClaimer.ClaimNext") + result, err = c.inner.ClaimNext(ctx, request) + c.storage.done(ctx, span, started, err) + return result, err +} diff --git a/internal/telemetry/relations.go b/internal/telemetry/relations.go new file mode 100644 index 000000000..1d2f4f999 --- /dev/null +++ b/internal/telemetry/relations.go @@ -0,0 +1,36 @@ +package telemetry + +import ( + "context" + + "github.com/steveyegge/beads/issueops" +) + +// IssueRelations returns the inner store's neighbor-query surface wrapped in +// this layer's instrumentation. It recurses instead of delegating: a blind +// delegation would return the inner surface unspanned and untimed. +func (s *InstrumentedStorage) IssueRelations() (issueops.Relations, error) { + inner, err := s.Unwrap().IssueRelations() + if err != nil { + return nil, err + } + return s.WrapIssueRelations(inner), nil +} + +// WrapIssueRelations instruments guarded neighbor queries with this storage +// layer's existing telemetry meter and tracer. +func (s *InstrumentedStorage) WrapIssueRelations(inner issueops.Relations) issueops.Relations { + return &instrumentedIssueRelations{storage: s, inner: inner} +} + +type instrumentedIssueRelations struct { + storage *InstrumentedStorage + inner issueops.Relations +} + +func (r *instrumentedIssueRelations) Related(ctx context.Context, request issueops.RelatedRequest) (result []*issueops.RelatedIssue, err error) { + ctx, span, started := r.storage.op(ctx, "IssueRelations.Related") + result, err = r.inner.Related(ctx, request) + r.storage.done(ctx, span, started, err) + return result, err +} diff --git a/internal/telemetry/role_accessor_decorator_test.go b/internal/telemetry/role_accessor_decorator_test.go new file mode 100644 index 000000000..c76902634 --- /dev/null +++ b/internal/telemetry/role_accessor_decorator_test.go @@ -0,0 +1,193 @@ +package telemetry + +import ( + "context" + "errors" + "reflect" + "runtime" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/issueops" +) + +// roleAccessorNames is the seven-strong capability surface every storage +// decorator has to answer for. It is duplicated from the sibling test in +// internal/storage rather than shared because that package cannot import this +// one and this one's test helpers cannot be exported back. +var roleAccessorNames = []string{ + "IssueLifecycle", + "IssueReader", + "IssueRelations", + "Commenter", + "ReadyClaimer", + "BatchCloser", + "DependencyEditor", +} + +// TestInstrumentedStorageDeclaresEveryRoleAccessor is the structural half of +// this decorator's conformance story. +// +// InstrumentedStorage embeds storage.DoltStorage for capability pass-through, +// so DELETING an accessor still compiles: the embedded interface supplies a +// promoted method with the same signature and every call on that role goes +// unspanned and untimed. Reflection catches it because the compiler reports a +// promoted method's implementation as living in "". +func TestInstrumentedStorageDeclaresEveryRoleAccessor(t *testing.T) { + decorator := reflect.TypeOf(&InstrumentedStorage{}) + for _, name := range roleAccessorNames { + method, ok := decorator.MethodByName(name) + if !ok { + t.Errorf("%s has no %s accessor at all", decorator, name) + continue + } + file, _ := runtime.FuncForPC(method.Func.Pointer()).FileLine(method.Func.Pointer()) + if strings.Contains(file, "") { + t.Errorf("%s.%s is promoted from the embedded store, not declared on the decorator: "+ + "every call on that role goes unspanned", decorator, name) + } + } +} + +// roleAccessorStore is a DoltStorage whose only real methods are the seven role +// accessors, each answering with a distinguishable sentinel so a test can tell +// an instrumented surface from a passed-through one. +type roleAccessorStore struct { + storage.DoltStorage + surface *roleAccessorSentinel + err error +} + +func (s *roleAccessorStore) IssueLifecycle() (issueops.Lifecycle, error) { return s.surface, s.err } +func (s *roleAccessorStore) IssueReader() (issueops.Reader, error) { return s.surface, s.err } +func (s *roleAccessorStore) IssueRelations() (issueops.Relations, error) { return s.surface, s.err } +func (s *roleAccessorStore) Commenter() (issueops.Commenter, error) { return s.surface, s.err } +func (s *roleAccessorStore) ReadyClaimer() (issueops.ReadyClaimer, error) { + return s.surface, s.err +} +func (s *roleAccessorStore) BatchCloser() (issueops.BatchCloser, error) { return s.surface, s.err } +func (s *roleAccessorStore) DependencyEditor() (issueops.DependencyEditor, error) { + return s.surface, s.err +} + +// roleAccessorSentinel implements all seven roles at once. Nothing calls its +// methods; identity is the whole point. +type roleAccessorSentinel struct{} + +func (*roleAccessorSentinel) Create(context.Context, issueops.CreateRequest) (issueops.CreateResult, error) { + return issueops.CreateResult{}, nil +} +func (*roleAccessorSentinel) Update(context.Context, issueops.UpdateRequest) (issueops.UpdateResult, error) { + return issueops.UpdateResult{}, nil +} +func (*roleAccessorSentinel) Close(context.Context, issueops.CloseRequest) (issueops.CloseResult, error) { + return issueops.CloseResult{}, nil +} +func (*roleAccessorSentinel) Reopen(context.Context, issueops.ReopenRequest) (issueops.ReopenResult, error) { + return issueops.ReopenResult{}, nil +} +func (*roleAccessorSentinel) Ready(context.Context, issueops.ReadyRequest) (issueops.IssuePage, error) { + return issueops.IssuePage{}, nil +} +func (*roleAccessorSentinel) List(context.Context, issueops.ListRequest) (issueops.IssuePage, error) { + return issueops.IssuePage{}, nil +} +func (*roleAccessorSentinel) Get(context.Context, issueops.GetRequest) (*issueops.IssueDetails, error) { + return nil, nil +} +func (*roleAccessorSentinel) Related(context.Context, issueops.RelatedRequest) ([]*issueops.RelatedIssue, error) { + return nil, nil +} +func (*roleAccessorSentinel) AddComment(context.Context, issueops.AddCommentRequest) (issueops.AddCommentResult, error) { + return issueops.AddCommentResult{}, nil +} +func (*roleAccessorSentinel) ClaimNext(context.Context, issueops.ClaimNextRequest) (issueops.ClaimNextResult, error) { + return issueops.ClaimNextResult{}, nil +} +func (*roleAccessorSentinel) CloseBatch(context.Context, issueops.CloseBatchRequest) (issueops.CloseBatchResult, error) { + return issueops.CloseBatchResult{}, nil +} +func (*roleAccessorSentinel) AddDependencies(context.Context, issueops.AddDependenciesRequest) (issueops.AddDependenciesResult, error) { + return issueops.AddDependenciesResult{}, nil +} +func (*roleAccessorSentinel) RemoveDependency(context.Context, issueops.RemoveDependencyRequest) (issueops.RemoveDependencyResult, error) { + return issueops.RemoveDependencyResult{}, nil +} + +// TestInstrumentedStorageInstrumentsEveryRoleAccessor catches what reflection +// cannot: an accessor that IS declared but reads +// `return s.Unwrap().Commenter()`. That edit compiles, keeps satisfying +// DoltStorage, and silently drops every span and timing on that role. +// +// Unlike the hook decorator, this one has no read-role exemption: telemetry +// spans reads as well as writes, so ALL SEVEN must come back wrapped. Only +// IssueLifecycle and IssueReader had a recursion pin of their own before this +// test; the other five wrappers had no test at all. +func TestInstrumentedStorageInstrumentsEveryRoleAccessor(t *testing.T) { + t.Setenv("BD_OTEL_STDOUT", "true") + sentinel := &roleAccessorSentinel{} + inner := &roleAccessorStore{surface: sentinel} + wrapped, ok := WrapStorage(inner).(*InstrumentedStorage) + if !ok { + t.Fatal("WrapStorage did not instrument the store; telemetry is disabled in this environment") + } + + for _, test := range []struct { + name string + got func() (any, error) + }{ + {"IssueLifecycle", func() (any, error) { return wrapped.IssueLifecycle() }}, + {"IssueReader", func() (any, error) { return wrapped.IssueReader() }}, + {"IssueRelations", func() (any, error) { return wrapped.IssueRelations() }}, + {"Commenter", func() (any, error) { return wrapped.Commenter() }}, + {"ReadyClaimer", func() (any, error) { return wrapped.ReadyClaimer() }}, + {"BatchCloser", func() (any, error) { return wrapped.BatchCloser() }}, + {"DependencyEditor", func() (any, error) { return wrapped.DependencyEditor() }}, + } { + t.Run(test.name, func(t *testing.T) { + surface, err := test.got() + if err != nil { + t.Fatalf("%s() error = %v", test.name, err) + } + if surface == any(sentinel) { + t.Fatalf("%s() returned the inner surface uninstrumented, so every call on that role is unspanned and untimed", test.name) + } + }) + } +} + +// TestInstrumentedStorageRoleAccessorsPropagateInnerErrors pins the other half +// of the recursion: an accessor that recurses must not swallow the inner +// store's refusal, nor hand back a wrapper around nothing. +func TestInstrumentedStorageRoleAccessorsPropagateInnerErrors(t *testing.T) { + t.Setenv("BD_OTEL_STDOUT", "true") + want := errors.New("inner refused") + wrapped, ok := WrapStorage(&roleAccessorStore{err: want}).(*InstrumentedStorage) + if !ok { + t.Fatal("WrapStorage did not instrument the store; telemetry is disabled in this environment") + } + + for _, test := range []struct { + name string + got func() (any, error) + }{ + {"IssueLifecycle", func() (any, error) { return wrapped.IssueLifecycle() }}, + {"IssueReader", func() (any, error) { return wrapped.IssueReader() }}, + {"IssueRelations", func() (any, error) { return wrapped.IssueRelations() }}, + {"Commenter", func() (any, error) { return wrapped.Commenter() }}, + {"ReadyClaimer", func() (any, error) { return wrapped.ReadyClaimer() }}, + {"BatchCloser", func() (any, error) { return wrapped.BatchCloser() }}, + {"DependencyEditor", func() (any, error) { return wrapped.DependencyEditor() }}, + } { + t.Run(test.name, func(t *testing.T) { + surface, err := test.got() + if !errors.Is(err, want) { + t.Fatalf("%s() error = %v, want %v", test.name, err, want) + } + if surface != nil { + t.Fatalf("%s() = %#v alongside an error, want a nil surface", test.name, surface) + } + }) + } +} diff --git a/internal/types/types.go b/internal/types/types.go index e2be357b2..fc3db1855 100644 --- a/internal/types/types.go +++ b/internal/types/types.go @@ -1176,11 +1176,20 @@ var AllDependencyTypes = []DependencyType{ DepDelegatedFrom, } +// MaxDependencyTypeLen is the widest dependency type either dependency plane +// can store: dependencies.type and wisp_dependencies.type are both VARCHAR(32) +// (migrations 0002_create_dependencies and 0021_create_wisp_auxiliary), and no +// later migration widens either. Validators bound the type here rather than at +// some looser number of their own, so a type that passes validation is a type +// an edge can actually carry — a longer one is refused up front instead of +// becoming a filter that silently matches nothing. +const MaxDependencyTypeLen = 32 + // IsValid checks if the dependency type value is valid. -// Accepts any non-empty string up to 50 characters. +// Accepts any non-empty string that fits the type column (MaxDependencyTypeLen). // Use IsWellKnown() to check if it's a built-in type. func (d DependencyType) IsValid() bool { - return len(d) > 0 && len(d) <= 50 + return len(d) > 0 && len(d) <= MaxDependencyTypeLen } // WellKnownDependencyTypes returns the built-in dependency types accepted by diff --git a/internal/types/types_test.go b/internal/types/types_test.go index ced43ba8e..58c5b51c3 100644 --- a/internal/types/types_test.go +++ b/internal/types/types_test.go @@ -679,7 +679,11 @@ func TestIssueCompoundHelpers(t *testing.T) { } func TestDependencyTypeIsValid(t *testing.T) { - // IsValid now accepts any non-empty string up to 50 chars (Decision 004) + // IsValid accepts any non-empty string the type column can hold (Decision + // 004 for the open vocabulary; MaxDependencyTypeLen for the bound). The + // boundary cases below are the load-bearing ones: at the limit the type is + // storable and must be accepted, one past it no edge could carry it and a + // filter built from it would match nothing, so it is refused up front. tests := []struct { depType DependencyType valid bool @@ -698,6 +702,8 @@ func TestDependencyTypeIsValid(t *testing.T) { {DependencyType("custom-type"), true}, // Custom types are now valid {DependencyType("any-string"), true}, // Any non-empty string is valid {DependencyType(""), false}, // Empty is still invalid + {DependencyType(strings.Repeat("x", MaxDependencyTypeLen)), true}, // Exactly the column width + {DependencyType(strings.Repeat("x", MaxDependencyTypeLen+1)), false}, // One past it: unstorable {DependencyType("this-is-a-very-long-dependency-type-that-exceeds-fifty-characters"), false}, // Too long } diff --git a/internal/workapi/list.go b/internal/workapi/list.go index ca32f82a4..5c2661279 100644 --- a/internal/workapi/list.go +++ b/internal/workapi/list.go @@ -184,6 +184,17 @@ func LoadUOWListConfig(ctx context.Context, uw UnitOfWork) (ListConfig, error) { // exclusions, the pinned and template defaults, and the gate, infra-type, and // wisp suppression that make the default listing show durable work only. func BuildListFilter(in issueops.ListRequest, cfg ListConfig) (types.IssueFilter, error) { + // The --ready arm reaches its query through ReadyFilterFromIssueFilter, + // which carries only part of what this filter can express. A request that + // asks --ready to honor something the projection drops is refused here, + // at the one point every frontend and every implementation of + // issueops.Reader passes through, rather than answered with the wider set. + // The drop set and the refusal text live beside the promise they enforce, + // in issueops. + if err := issueops.ValidateReadyFlagScope(in); err != nil { + return types.IssueFilter{}, err + } + filter := types.IssueFilter{ Limit: SQLLimit(in), Offset: in.Offset, diff --git a/internal/workapi/ready.go b/internal/workapi/ready.go index 18390b8ba..102b0c30c 100644 --- a/internal/workapi/ready.go +++ b/internal/workapi/ready.go @@ -83,7 +83,15 @@ func BuildReadyFilter(in issueops.ReadyRequest) (types.WorkFilter, error) { } if !filter.SortPolicy.IsValid() { - return filter, fmt.Errorf("invalid sort policy '%s'. Valid values: hybrid, priority, oldest", in.Sort) + // A deterministic request-validation failure, so it matches + // ErrValidation: every role whose filter vocabulary this builds — + // Reader.Ready, ReadyClaimer.ClaimNext and BatchCloser's ClaimNext — + // promises a caller can classify one with errors.Is rather than by + // reading prose. The wrap is %.0w rather than a "%w: " prefix because + // this text is what `bd ready --sort bogus` prints verbatim behind + // "Error: "; prefixing it would change user-visible copy to say + // something the reader already knows. + return filter, fmt.Errorf("invalid sort policy '%s'. Valid values: hybrid, priority, oldest%.0w", in.Sort, issueops.ErrValidation) } return filter, nil } diff --git a/internal/workapi/storereader/reader.go b/internal/workapi/storereader/reader.go index 683c844cd..4551f644d 100644 --- a/internal/workapi/storereader/reader.go +++ b/internal/workapi/storereader/reader.go @@ -45,7 +45,7 @@ import ( // commands' JSON paths through the role would be worse. func New(store storage.DoltStorage) (issueops.Reader, error) { if store == nil { - return nil, &storage.ErrUnsupported{Op: "storereader.New", Backend: "nil"} + return nil, &issueops.ErrUnsupported{Op: "storereader.New", Backend: "nil"} } return &storeReader{store: store}, nil } @@ -54,7 +54,28 @@ type storeReader struct{ store storage.DoltStorage } var _ issueops.Reader = (*storeReader)(nil) +// offsetBackend names the backend an Offset refusal comes from. One name for +// both engines on purpose: the server-backed and embedded stores hand back +// THIS body, and it is the body — not the engine underneath it — that cannot +// page by offset. +const offsetBackend = "dolt-store" + +// refuseOffset is the shared refusal. The store seam renders LIMIT without +// OFFSET (internal/storage/issueops/ready_work.go, search_counts.go), so a +// request carrying one used to come back as the unpaged first page with no +// error on it — a caller paging with Offset saw the same rows forever. The +// field is not dead: `bd ready/list/query --offset` are real flags, and their +// direct routes already reject a non-zero offset before reaching any of this +// (cmd/bd/ready.go, list.go, query.go). This is the same refusal one layer +// down, for the callers that are not the CLI. +func refuseOffset(op string) error { + return &issueops.ErrUnsupported{Op: op, Backend: offsetBackend} +} + func (r *storeReader) Ready(ctx context.Context, req issueops.ReadyRequest) (issueops.IssuePage, error) { + if req.Offset != 0 { + return issueops.IssuePage{}, refuseOffset("Reader.Ready(Offset)") + } filter, err := workapi.BuildReadyFilter(req) if err != nil { return issueops.IssuePage{}, err @@ -78,6 +99,9 @@ func (r *storeReader) Ready(ctx context.Context, req issueops.ReadyRequest) (iss } func (r *storeReader) List(ctx context.Context, req issueops.ListRequest) (issueops.IssuePage, error) { + if req.Offset != 0 { + return issueops.IssuePage{}, refuseOffset("Reader.List(Offset)") + } cfg, err := workapi.LoadStoreListConfig(ctx, r.store) if err != nil { return issueops.IssuePage{}, err diff --git a/internal/workapi/storereader/reader_test.go b/internal/workapi/storereader/reader_test.go index 4d1d67a66..575e3f62a 100644 --- a/internal/workapi/storereader/reader_test.go +++ b/internal/workapi/storereader/reader_test.go @@ -195,6 +195,64 @@ func TestStoreReaderListOverFetchesForAPushdownSort(t *testing.T) { } } +// TestStoreReaderRefusesANonZeroOffset is the store-backed half of the offset +// split the role now promises (issueops/reader.go, ReadyRequest.Offset and +// ListRequest.Offset). This body renders LIMIT without OFFSET, so an offset it +// accepted would come back as the unpaged first page — which is what it used to +// do, silently. The refusal names the operation AND the backend, because that +// pair is all a caller holding only issueops.Reader gets to work with. +// +// The store must not be queried at all: a refusal that had already asked the +// database for the wrong page would be a wasted round trip on the way to the +// same error. +func TestStoreReaderRefusesANonZeroOffset(t *testing.T) { + for _, tc := range []struct { + name string + wantOp string + call func(issueops.Reader) (issueops.IssuePage, error) + }{ + {"Ready", "Reader.Ready(Offset)", func(rd issueops.Reader) (issueops.IssuePage, error) { + return rd.Ready(context.Background(), issueops.ReadyRequest{Sort: "priority", Offset: 1}) + }}, + {"List", "Reader.List(Offset)", func(rd issueops.Reader) (issueops.IssuePage, error) { + return rd.List(context.Background(), issueops.ListRequest{SortBy: "created", Offset: 1}) + }}, + } { + t.Run(tc.name, func(t *testing.T) { + rd, store := storeReaderFor(t, readerFixture(3)) + page, err := tc.call(rd) + var unsupported *storage.ErrUnsupported + if !errors.As(err, &unsupported) { + t.Fatalf("%s with Offset 1 = (%v, %v), want *storage.ErrUnsupported", tc.name, ids(page), err) + } + if unsupported.Op != tc.wantOp || unsupported.Backend != offsetBackend { + t.Errorf("refusal = Op %q Backend %q, want %q and %q", + unsupported.Op, unsupported.Backend, tc.wantOp, offsetBackend) + } + if queries := len(store.readyFilters) + len(store.searchFilters); queries != 0 { + t.Errorf("the refused request still ran %d queries", queries) + } + }) + } +} + +// TestStoreReaderServesOffsetZero: zero is the absence of a page request, not a +// request for page zero, so the refusal above must not catch the default. Every +// other test in this file would fail if it did, but none of them says why. +func TestStoreReaderServesOffsetZero(t *testing.T) { + rd, store := storeReaderFor(t, readerFixture(2)) + + if _, err := rd.Ready(context.Background(), issueops.ReadyRequest{Sort: "priority", Offset: 0}); err != nil { + t.Fatalf("Ready at Offset 0: %v", err) + } + if _, err := rd.List(context.Background(), issueops.ListRequest{SortBy: "created", Offset: 0}); err != nil { + t.Fatalf("List at Offset 0: %v", err) + } + if len(store.readyFilters) != 1 || len(store.searchFilters) != 1 { + t.Errorf("ran %d ready and %d search queries, want one each", len(store.readyFilters), len(store.searchFilters)) + } +} + // TestStoreReaderRefusesANilStore: the accessor is the only door, and a door // that hands back a reader over nothing would fail on the first query with a // nil dereference instead of at the seam that knows what is missing. diff --git a/issue_roles_external_test.go b/issue_roles_external_test.go new file mode 100644 index 000000000..33f2f501a --- /dev/null +++ b/issue_roles_external_test.go @@ -0,0 +1,167 @@ +package beads_test + +import ( + "errors" + "reflect" + "testing" + + "github.com/steveyegge/beads" + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/storage/dolt" + "github.com/steveyegge/beads/internal/telemetry" +) + +// TestReadyClaimerLayersHooksOutsideTelemetry pins the decorator order the +// claim accessor produces against the order cmd/bd assembles the chain in +// (storage_chain.go: telemetry first, hooks outermost), the same property +// TestIssueLifecycleLayersHooksOutsideTelemetry pins for the write role. A +// blind delegation at either decorator would still satisfy Storage and would +// still compile. +func TestReadyClaimerLayersHooksOutsideTelemetry(t *testing.T) { + t.Setenv("BD_OTEL_STDOUT", "true") + instrumented, ok := telemetry.WrapStorage(&dolt.DoltStore{}).(*telemetry.InstrumentedStorage) + if !ok { + t.Fatal("WrapStorage() did not create InstrumentedStorage") + } + + claimer, err := storage.NewHookFiringStore(instrumented, nil).ReadyClaimer() + if err != nil { + t.Fatalf("ReadyClaimer() error = %v", err) + } + if got := reflect.TypeOf(claimer).String(); got != "*storage.hookReadyClaimer" { + t.Fatalf("outer layer = %s, want the hook wrapper", got) + } +} + +// TestBatchCloserLayersHooksOutsideTelemetry is the same pin for the +// close-many role. +func TestBatchCloserLayersHooksOutsideTelemetry(t *testing.T) { + t.Setenv("BD_OTEL_STDOUT", "true") + instrumented, ok := telemetry.WrapStorage(&dolt.DoltStore{}).(*telemetry.InstrumentedStorage) + if !ok { + t.Fatal("WrapStorage() did not create InstrumentedStorage") + } + + closer, err := storage.NewHookFiringStore(instrumented, nil).BatchCloser() + if err != nil { + t.Fatalf("BatchCloser() error = %v", err) + } + if got := reflect.TypeOf(closer).String(); got != "*storage.hookBatchCloser" { + t.Fatalf("outer layer = %s, want the hook wrapper", got) + } +} + +// TestReadyClaimerExposesTypedUnsupportedError pins the typed error a backend +// returns when it cannot serve the role, reachable through the public alias +// without importing internal/storage. +func TestReadyClaimerExposesTypedUnsupportedError(t *testing.T) { + claimer, err := (*dolt.DoltStore)(nil).ReadyClaimer() + if claimer != nil { + t.Fatalf("ReadyClaimer() claimer = %T, want nil", claimer) + } + var unsupported *beads.ErrUnsupported + if !errors.As(err, &unsupported) { + t.Fatalf("ReadyClaimer() error = %v, want *beads.ErrUnsupported", err) + } +} + +func TestBatchCloserExposesTypedUnsupportedError(t *testing.T) { + closer, err := (*dolt.DoltStore)(nil).BatchCloser() + if closer != nil { + t.Fatalf("BatchCloser() closer = %T, want nil", closer) + } + var unsupported *beads.ErrUnsupported + if !errors.As(err, &unsupported) { + t.Fatalf("BatchCloser() error = %v, want *beads.ErrUnsupported", err) + } +} + +// TestDependencyEditorLayersHooksOutsideTelemetry is the same decorator-order +// pin for the edge-write role. +func TestDependencyEditorLayersHooksOutsideTelemetry(t *testing.T) { + t.Setenv("BD_OTEL_STDOUT", "true") + instrumented, ok := telemetry.WrapStorage(&dolt.DoltStore{}).(*telemetry.InstrumentedStorage) + if !ok { + t.Fatal("WrapStorage() did not create InstrumentedStorage") + } + + editor, err := storage.NewHookFiringStore(instrumented, nil).DependencyEditor() + if err != nil { + t.Fatalf("DependencyEditor() error = %v", err) + } + if got := reflect.TypeOf(editor).String(); got != "*storage.hookDependencyEditor" { + t.Fatalf("outer layer = %s, want the hook wrapper", got) + } +} + +// TestCommenterLayersHooksOutsideTelemetry is the same pin for the comment +// role. +func TestCommenterLayersHooksOutsideTelemetry(t *testing.T) { + t.Setenv("BD_OTEL_STDOUT", "true") + instrumented, ok := telemetry.WrapStorage(&dolt.DoltStore{}).(*telemetry.InstrumentedStorage) + if !ok { + t.Fatal("WrapStorage() did not create InstrumentedStorage") + } + + commenter, err := storage.NewHookFiringStore(instrumented, nil).Commenter() + if err != nil { + t.Fatalf("Commenter() error = %v", err) + } + if got := reflect.TypeOf(commenter).String(); got != "*storage.hookCommenter" { + t.Fatalf("outer layer = %s, want the hook wrapper", got) + } +} + +// TestIssueRelationsKeepsTelemetryOutermost is the READ role's version of the +// pin, and it is deliberately the other answer: the hook decorator adds no +// layer to a read, so the outermost thing a caller gets is the instrumented +// surface. A wrapper appearing here would mean a hook layer landed on a path +// with nothing to fire. +func TestIssueRelationsKeepsTelemetryOutermost(t *testing.T) { + t.Setenv("BD_OTEL_STDOUT", "true") + instrumented, ok := telemetry.WrapStorage(&dolt.DoltStore{}).(*telemetry.InstrumentedStorage) + if !ok { + t.Fatal("WrapStorage() did not create InstrumentedStorage") + } + + relations, err := storage.NewHookFiringStore(instrumented, nil).IssueRelations() + if err != nil { + t.Fatalf("IssueRelations() error = %v", err) + } + if got := reflect.TypeOf(relations).String(); got != "*telemetry.instrumentedIssueRelations" { + t.Fatalf("outer layer = %s, want the telemetry wrapper unwrapped by the hook decorator", got) + } +} + +func TestDependencyEditorExposesTypedUnsupportedError(t *testing.T) { + editor, err := (*dolt.DoltStore)(nil).DependencyEditor() + if editor != nil { + t.Fatalf("DependencyEditor() editor = %T, want nil", editor) + } + var unsupported *beads.ErrUnsupported + if !errors.As(err, &unsupported) { + t.Fatalf("DependencyEditor() error = %v, want *beads.ErrUnsupported", err) + } +} + +func TestCommenterExposesTypedUnsupportedError(t *testing.T) { + commenter, err := (*dolt.DoltStore)(nil).Commenter() + if commenter != nil { + t.Fatalf("Commenter() commenter = %T, want nil", commenter) + } + var unsupported *beads.ErrUnsupported + if !errors.As(err, &unsupported) { + t.Fatalf("Commenter() error = %v, want *beads.ErrUnsupported", err) + } +} + +func TestIssueRelationsExposesTypedUnsupportedError(t *testing.T) { + relations, err := (*dolt.DoltStore)(nil).IssueRelations() + if relations != nil { + t.Fatalf("IssueRelations() relations = %T, want nil", relations) + } + var unsupported *beads.ErrUnsupported + if !errors.As(err, &unsupported) { + t.Fatalf("IssueRelations() error = %v, want *beads.ErrUnsupported", err) + } +} diff --git a/issueops/batchcloser.go b/issueops/batchcloser.go new file mode 100644 index 000000000..16751aece --- /dev/null +++ b/issueops/batchcloser.go @@ -0,0 +1,147 @@ +package issueops + +import "context" + +// BatchCloseItem is one issue a batch close asks for, with the reason recorded +// against that issue alone. Reasons are per item rather than per request +// because `bd close a b c --reason x --reason y --reason z` has always mapped +// them positionally, and a single request-wide reason could not express it. +type BatchCloseItem struct { + IssueID string + Reason string +} + +// CloseBatchRequest describes one closure of many issues. +// +// THE REQUEST IS THE TRANSACTION BOUNDARY. That is the whole reason this is a +// request rather than a loop over Lifecycle.Close: closing N issues one call +// at a time is N transactions and N history entries, and the caller that wants +// them to land together has no way to say so. Nothing here exposes begin or +// commit and there is no handle to hold open, so the boundary cannot be got +// wrong — it is wherever the request ends. +type CloseBatchRequest struct { + // Actor is the closer and must not be empty. + Actor string + // Items are the issues to close, in the order the caller asked for them. + // It must not be empty. Every item appears in Outcomes at the same index. + // + // A DUPLICATED id is not a request error — `bd close a b a` is a plausible + // typo, not a failure. The items are closed in the order given, so the + // second occurrence finds what the first one did and reports an idempotent + // re-close at its OWN index: a per-item success with Changed false. The + // reason recorded on the row is the first occurrence's, because the second + // mutated nothing and so wrote nothing. + // + // A WISP ID IS AN ADMISSIBLE ITEM. An id is resolved across both planes, + // exactly as Lifecycle.Close resolves one, and closing a wisp is real work + // landing: it counts toward "at least one item closed" for ClaimNext below. + // What it does NOT do is reach the durable history entry — see the + // ephemeral paragraph on BatchCloser itself. + Items []BatchCloseItem + // Session records the closing session against every item. + Session string + // Force bypasses only blocker and open-child close policy, for every item. + // It never bypasses validation, and it never bypasses existence: an id that + // names nothing refuses whether or not force is set. It is request-wide + // because the flag that spells it is. + // + // It would not bypass a per-item LIFECYCLE PRECONDITION either, but no + // batch item carries one: there is no counterpart here to the + // ExpectedVersion a Lifecycle close takes, so the category is empty and + // nothing in a batch can exercise it today. The rule is stated for the day + // an item grows a precondition, which is the day force stops being a + // question with only two answers. + Force bool + // ClaimNext claims the next ready issue after the closes land, in the same + // transaction, and only when at least one item closed — a claim handed out + // by a request that closed nothing would be a claim the caller never + // earned. Nil skips it entirely. + // + // CHANGED IS THE TEST for "at least one item closed", not a nil per-item + // Err: a batch whose items were ALL already closed mutated nothing, so + // nothing landed. It earns no claim and records no history entry, for the + // same reason a batch of typos records none. A per-item success that + // changed nothing is not work the caller did. + // + // Its semantics are ReadyClaimer.ClaimNext's, by reference and not by + // restatement: the same filter vocabulary, the same unset-Limit-and-Offset + // rule, the same nil-means-nothing-eligible outcome. Restating them here + // is how the two would come apart. + ClaimNext *ReadyRequest +} + +// CloseOutcome is what happened to ONE requested item. +type CloseOutcome struct { + // IssueID is the id the caller asked for, echoed so an outcome can be read + // without indexing back into the request. + IssueID string + // Issue is the post-close snapshot with labels and dependency records, or + // nil when Err is set. Comments are omitted, as they are for CloseResult. + Issue *Issue + // Changed reports whether this item persisted a semantic mutation. It is + // false for an idempotent re-close. + Changed bool + // OpenChildren is the number of open children observed by a forced close + // of this item. It is reported even for an idempotent re-close. + OpenChildren int + // Err is this item's refusal, and NEVER aborts the rest of the batch. It + // carries the same typed close vocabulary Lifecycle.Close returns — + // ErrNotFound, ErrCloseBlocked, *CloseOpenChildrenError — so a caller + // classifies it with errors.Is and errors.As rather than by reading prose. + Err error +} + +// CloseBatchResult reports every requested item. +type CloseBatchResult struct { + // Outcomes has exactly one entry per requested item, in REQUEST ORDER, + // including for items that refused. A caller reporting per-id status walks + // it against its own argument list without matching ids back up. + Outcomes []CloseOutcome + // ClaimedNext is the row a requested ClaimNext won, hydrated with its + // cardinalities in the same transaction. Nil means the request asked for + // no claim, nothing closed, or nothing was eligible. + ClaimedNext *IssueWithCounts +} + +// BatchCloser describes closing many issues as one durable act: the write side +// of `bd close a b c`, and — like Lifecycle, Reader and ReadyClaimer — a role +// with its own accessor. A new capability gets a new role interface and its +// own accessor; never append a method here. +// +// IT IS NOT ALL-OR-NOTHING, and that is deliberate rather than a concession. +// An id the batch refuses is SKIPPED and the survivors commit together, which +// is what closing a list of issues has always done: an agent that finishes +// four of five steps and mistypes the fifth keeps the four. Making the batch +// atomic in the other sense — all or none — would turn a typo into a rollback +// of finished work, and the per-id refusal a caller prints is the report that +// tells it which one to fix. +// +// WHAT IS ATOMIC is everything that LANDS: one transaction, at most one +// history entry, and none at all when nothing landed. LANDED means CHANGED, in +// the CloseOutcome sense — an idempotent re-close is a per-item success that +// persisted nothing, so a batch of them lands nothing. The method's own error +// is reserved for request validation, cancellation and infrastructure — the +// failures that mean the batch never ran — so a non-nil error and a populated +// Outcomes are mutually exclusive. A per-item refusal is not an error of the +// batch; it is a result of the batch. +// +// A DURABLE HISTORY ENTRY NEVER NAMES A WISP ID. The entry a mixed batch +// records is composed from its DURABLE landings alone, so a batch of one issue +// and one wisp records an entry naming the issue only. The wisp tables are +// dolt-ignored precisely so ephemeral work never ships, so an entry naming a +// wisp would be the sync artifact ignoring those tables exists to prevent — the +// same rule Commenter states for an ephemeral comment. Only the durable trace +// is restricted: the close itself lands on the ephemeral row, reads back from +// it, and counts toward ClaimNext's coupling like any other landing. +// +// Implementations never mutate caller-owned request values, snapshot the +// request at method entry, and apply validation and normalization only to +// attempt-local clones. Deterministic request-validation failures match +// ErrValidation and leave persistent state unchanged. +type BatchCloser interface { + // CloseBatch closes every item it can and commits them together. Outcomes + // mirrors Items index for index. ClaimNext, when requested and when at + // least one item closed, runs after the closes inside the same + // transaction. + CloseBatch(ctx context.Context, req CloseBatchRequest) (CloseBatchResult, error) +} diff --git a/issueops/commenter.go b/issueops/commenter.go new file mode 100644 index 000000000..ffbc8e183 --- /dev/null +++ b/issueops/commenter.go @@ -0,0 +1,83 @@ +package issueops + +import ( + "context" + + "github.com/steveyegge/beads/internal/types" +) + +// Comment is one comment on an issue. +type Comment = types.Comment + +// AddCommentRequest describes one comment. +type AddCommentRequest struct { + // Author is the commenter and must not be empty. It is spelled Author + // rather than Actor because a comment is signed: the name lands in the row + // and is read back by everyone who sees the thread, where an Actor is the + // principal a mutation is attributed to. The other requests here mutate an + // issue on someone's behalf; this one publishes under their name. + Author string + // IssueID is the exact canonical id and must not be empty. The + // issue-to-wisp fallback happens INSIDE, exactly as it does for Reader.Get, + // so a caller never has to know which plane the thread lives on. There is + // no fuzzy or prefix resolution here, for the reason GetRequest.ID gives. + // + // Nor is there a plane ORDER to know, for the reason GetRequest.ID also + // gives: no local write path makes an id resident in both planes, so a + // comment can only land on the one thread that exists. GetRequest.ID owns + // that argument for every role that resolves an id; this one inherits it + // whole, INCLUDING ITS TWO CAVEATS — in particular that replication can + // produce a dual-resident id that no local guard closes, which is a corrupt + // store rather than a question this order would answer. + IssueID string + // Text is the comment body and must not be blank. It is stored verbatim: + // blankness is decided on a trimmed copy, and nothing trims the value that + // lands in the row. + Text string +} + +// AddCommentResult reports the stored comment. +type AddCommentResult struct { + // Comment is the stored comment, with the id and created_at the row + // actually got. CreatedAt is the STORED value at the column's precision, + // not the wall clock the call happened at, so it is safe to use directly + // as a comment-page cursor. + Comment *Comment +} + +// Commenter describes adding a comment to an issue: the write side of `bd +// comment`, and — like Lifecycle, Reader, ReadyClaimer, BatchCloser and +// DependencyEditor — a role with its own accessor. A new capability gets a new +// role interface and its own accessor; never append a method here. +// +// It is its own role rather than a Lifecycle verb because a comment is not a +// patch to an issue. It appends a row to a thread the issue owns and leaves +// every field of the issue untouched, so an IssuePatch has nothing to carry +// and an UpdateResult has nowhere to put the comment. +// +// READING the thread is deliberately not here. Reader.Get already returns +// comments when asked, and a comment-page walk is a paging question with a +// cursor of its own — a second question, so a second role when something needs +// it, not a second method here. +// +// Implementations never mutate caller-owned request values, snapshot the +// request at method entry, and apply validation and normalization only to +// attempt-local clones. Deterministic request-validation failures match +// ErrValidation and leave persistent state unchanged. +type Commenter interface { + // AddComment appends one comment as ONE atomic mutation, with at most one + // history entry. A blank Text is ErrValidation, and so is an empty + // IssueID; a NON-EMPTY id that names neither an issue nor a wisp is + // ErrNotFound. Refusals use the same typed vocabulary Lifecycle returns, + // so a caller classifies them with errors.Is rather than by reading prose. + // + // A comment on an EPHEMERAL row records NO durable history entry — none, + // not "at most one". Ephemeral rows are not versioned, and the wisp tables + // are dolt-ignored precisely so ephemeral work never ships, so a history + // entry naming a wisp thread would be the sync artifact ignoring those + // tables exists to prevent. The comment itself lands on the ephemeral + // thread and reads back from it; only the durable trace is absent, so a + // caller reconstructing threads from durable history alone will not see + // it. + AddComment(ctx context.Context, req AddCommentRequest) (AddCommentResult, error) +} diff --git a/issueops/dependencyeditor.go b/issueops/dependencyeditor.go new file mode 100644 index 000000000..724790021 --- /dev/null +++ b/issueops/dependencyeditor.go @@ -0,0 +1,183 @@ +package issueops + +import ( + "context" + + "github.com/steveyegge/beads/internal/types" +) + +// DependencyType names one kind of edge between two issues. +type DependencyType = types.DependencyType + +// Dependency types in COMMON USE. +// +// This is an OPEN SET, and these constants are a documented sample of it — not +// a closed enum, not exhaustive, and not a whitelist. A workspace configures +// its own vocabulary, so nothing in this package validates a DependencyType +// against this list, and an implementation that refused a type absent from it +// would break every workspace that spelled one of its own. Adding a value here +// documents a value; it never authorizes one. +// +// They exist at all because internal/types is unimportable outside this +// module. Every request and result below CARRIES a DependencyType, so without +// these an external embedder can hold one but has no spell-checked way to name +// one — the same reason the error sentinels are re-exported in errors.go. +const ( + DepBlocks = types.DepBlocks + DepParentChild = types.DepParentChild + DepRelated = types.DepRelated + DepDiscoveredFrom = types.DepDiscoveredFrom + DepRepliesTo = types.DepRepliesTo + DepWaitsFor = types.DepWaitsFor +) + +// DependencyEdge is one directed edge: IssueID depends on DependsOnID, with +// the given Type. Both endpoints are exact canonical ids — there is no fuzzy, +// prefix or cross-repo resolution on this contract, for the reason +// GetRequest.ID gives. +type DependencyEdge struct { + IssueID string + DependsOnID string + // Type is required and must be a usable value. It is checked for being a + // value at all — non-empty, within the column's length — and NEVER for + // membership of the constants above, which name an open set. + Type DependencyType +} + +// AddDependenciesRequest describes one set of edges asserted together. +// +// IT IS ALL-OR-NOTHING, and unlike the batch close that is not a policy choice +// but the shape of the question. A close acts on issues that are independent +// of one another, so skipping one and committing the rest loses nothing; edges +// asserted in one request describe a GRAPH, and half a graph is a graph nobody +// asked for — the cycle a caller was refused for is exactly the state a +// partial commit would leave behind. +type AddDependenciesRequest struct { + // Actor is the author of the edges and must not be empty. It is what the + // dependency_added entry each genuinely new edge records is attributed to, + // which is the only place a reader finds who wired an edge: the result + // does not carry it. + Actor string + // Edges are the edges to assert, in the caller's order. It must not be + // empty. Edges are applied parent-child first regardless of this order, so + // the complete planned hierarchy is visible before any blocking edge is + // validated against it. + Edges []DependencyEdge + // SkipPerEdgeCycleCheck drops the per-edge cycle probe for a caller wiring + // a large graph, trading validation cost for speed. It NEVER drops the + // whole-graph gate that runs once at the end, and it never drops the + // self-dependency refusal: an edge that points an issue at itself is + // refused with or without it. + SkipPerEdgeCycleCheck bool +} + +// AddDependenciesResult reports the edges that landed. +type AddDependenciesResult struct { + // Added is the edges this request wrote, in request order. All-or-nothing + // means it is either every requested edge or the call failed, so it echoes + // the request — deliberately, the way CloseOutcome echoes its IssueID: a + // caller reporting what landed reads the RESULT, and never has to know + // which of the two it is safe to read. + Added []DependencyEdge +} + +// RemoveDependencyRequest describes the removal of one edge. +type RemoveDependencyRequest struct { + // Actor is the remover and must not be empty. It is what the + // dependency_removed entry a successful removal records is attributed to, + // the mirror of AddDependenciesRequest.Actor. + Actor string + // IssueID and DependsOnID name the edge exactly. Neither may be empty. + IssueID string + DependsOnID string +} + +// RemoveDependencyResult reports what the removal found. +type RemoveDependencyResult struct { + // Removed is false when no such edge existed. That is a SUCCESS, not a + // refusal: removing an edge twice leaves the same graph as removing it + // once, and an agent replaying its own teardown should not have to + // classify an error to discover it already ran. Nothing is written for it + // and no history entry is recorded. + Removed bool +} + +// DependencyEditor describes guarded edits to the dependency graph: the write +// side of `bd dep add` and `bd dep remove`, and — like Lifecycle, Reader, +// ReadyClaimer and BatchCloser — a role with its own accessor. A new +// capability gets a new role interface and its own accessor; never append a +// method here. +// +// It is its own role rather than two more Lifecycle verbs because an edge is +// not a field of an issue. It has two endpoints, and every refusal it can +// raise — a cycle, a hierarchy deadlock, a type conflict — is a statement +// about the GRAPH the two endpoints sit in rather than about either row. A +// patch has nowhere to put that. +// +// An edge FOLLOWS ITS SOURCE. Both methods edit the durable graph `bd dep` +// shows and `bd dolt log` versions when the source is a durable issue, and the +// ephemeral graph when it is an ephemeral one — a wisp has no durable row for +// an edge to hang off, so there is no third answer. One request may mix the +// two; it is still one transaction, and still all-or-nothing across both. +// Only the durable half is versioned, so a request made entirely of ephemeral +// edges records no history entry. +// +// A TARGET's plane is independent of its source's: either class may depend on +// the other. +// +// EACH METHOD LEAVES A TRAIL IN THE SOURCE'S EVENT STREAM, attributed to the +// request's Actor: a genuinely new edge records a dependency_added entry, and +// a removal that found its edge a dependency_removed one. Work that wrote +// nothing records nothing — an idempotent same-type re-add and a removal that +// found no edge both leave the stream as they found it. The trail follows the +// source's plane exactly as the edge does, which is what makes it readable on +// an ephemeral edge at all: the wisp plane is not versioned, so for a +// wisp-sourced edge this is the only record the operation leaves. +// +// Implementations never mutate caller-owned request values, snapshot the +// request at method entry, and apply validation and normalization only to +// attempt-local clones. Deterministic request-validation failures match +// ErrValidation and leave persistent state unchanged. +type DependencyEditor interface { + // AddDependencies asserts every edge in the request as ONE durable act: + // one transaction, one history entry. Any refused edge refuses the whole + // request and writes nothing — a self-dependency (ErrSelfDependency), a + // scheduling cycle (ErrDependencyCycle), a conflicting type on a pair that + // already has an edge (*DependencyTypeConflictError), a blocking edge that + // would gate an issue on its own ancestor or descendant + // (*DependencyHierarchyConflictError), or a SOURCE that does not exist. + // + // A target's existence is checked only where the backend can see it. A + // target may legitimately be an "external:" reference or an issue in + // another repository, neither of which this database holds, so there is no + // blanket unknown-target refusal to promise. Where the backend CAN see the + // absence — an id in this database's own namespace, carrying no + // "external:" marker and matching no row — the edge is refused, and the + // request writes nothing like any other refusal. + // + // NEITHER EXISTENCE REFUSAL NAMES AN IDENTITY YET. The four refusals above + // hand a caller a sentinel or a typed value to branch on; a ghost source + // and a missing local target are only "an error", and not even the same + // error text on every implementation. So a caller cannot today tell a + // ghost endpoint from an infrastructure failure. That is a known gap + // (bd-yby99.9) rather than a promise the refusal will stay anonymous, and + // nothing should be written that string-matches it. + // + // An edge that already exists with the SAME type is idempotent and refuses + // nothing, and REPETITION WITHIN ONE REQUEST answers the same way: the + // second occurrence of a pair finds the first already written, so the pair + // is applied once, and the result still echoes every edge as requested. + // Two DIFFERENT types for one pair in one request is the same + // *DependencyTypeConflictError a pre-existing edge of the other type + // raises, and writes nothing. + // + // A request that wrote no durable edge — because every one of them already + // existed with the requested type — records NO history entry, the same way + // RemoveDependencyResult states it for a removal that found nothing. The + // one entry is recorded when at least one durable edge was genuinely + // written, and one is all that is recorded however many were. + AddDependencies(ctx context.Context, req AddDependenciesRequest) (AddDependenciesResult, error) + // RemoveDependency removes exactly the named edge. It is idempotent: a + // missing edge is Removed false with a nil error, not ErrNotFound. + RemoveDependency(ctx context.Context, req RemoveDependencyRequest) (RemoveDependencyResult, error) +} diff --git a/issueops/errors.go b/issueops/errors.go index 4112839aa..411839ae3 100644 --- a/issueops/errors.go +++ b/issueops/errors.go @@ -41,6 +41,28 @@ func (e *ClaimConflictError) Error() string { return e.Err.Error() } // Unwrap makes ClaimConflictError match the refusal it carries. func (e *ClaimConflictError) Unwrap() error { return e.Err } +// ErrUnsupported reports something the caller asked for that this backend +// cannot serve — a capability accessor it does not implement, or a request +// field it will not honor. It is a TYPE rather than a sentinel because the +// two facts a caller needs are which operation refused and which backend +// refused it, and neither survives a formatted string. +// +// A backend returns it instead of quietly doing something narrower. The case +// that made that rule explicit is Reader's Offset: the store-backed body +// rendered LIMIT without OFFSET, so a caller that paged with it received the +// first page over and over with no error to notice. +// +// It lives here so a caller holding only a role interface can classify the +// refusal with errors.As without importing internal/storage. +type ErrUnsupported struct { + Op string // method name, e.g. "AddLabel" or "Transaction.CreateIssues" + Backend string // e.g. "dolt-server" +} + +func (e *ErrUnsupported) Error() string { + return fmt.Sprintf("operation %q not supported by the %s backend", e.Op, e.Backend) +} + // ErrAssigneeMismatch is returned by UnclaimIssueIfAssignee when the issue's // current assignee does not match the expected assignee (including when the // issue is no longer assigned at all). The caller's view of the claim was @@ -108,10 +130,10 @@ var ErrSelfDependency = errors.New("cannot add self-dependency") // ErrDependencyCycle is returned when adding a dependency edge would introduce a // scheduling cycle. It is scoped to the dependency-add family — the single and -// bulk add paths (add/addBulk) and the dolt cross-tier check — so callers can -// errors.Is any dependency-add cycle rejection. The whole-graph construction -// paths (ApplyIssueGraph/ApplyWispGraph) are a separate family and deliberately -// do not carry this sentinel yet. +// bulk add paths (add/AddDependencies) and the dolt cross-tier check — so +// callers can errors.Is any dependency-add cycle rejection. The whole-graph +// construction paths (ApplyIssueGraph/ApplyWispGraph) are a separate family and +// deliberately do not carry this sentinel yet. var ErrDependencyCycle = errors.New("adding dependency would create a cycle") // DependencyTypeConflictError is returned when an edge already exists between diff --git a/issueops/issueops.go b/issueops/issueops.go index 99a00bd4e..8f0c22c70 100644 --- a/issueops/issueops.go +++ b/issueops/issueops.go @@ -56,6 +56,21 @@ type Field[T any] struct { // LabelPatch describes ordered label replacement and incremental edits. // Operations apply Replace, then Add, then Remove, so removal wins when the // same label appears in more than one edit. +// +// The VALUES an edit carries answer to the same field rules a create's labels +// do: a label longer than the column is refused with ErrFieldTooLong and the +// whole update writes nothing. Repetition is free in both directions — the +// same label named twice in one edit is applied once, and removing a label the +// issue does not carry is a no-op that reports Changed false. +// +// An EMPTY-STRING entry is DROPPED — not written, and not refused. A label +// row carrying "" renders as nothing and matches nothing, so writing one only +// stores junk; refusing the whole update would let one stray entry fail an +// otherwise-good multi-label edit. Dropping is a no-op rather than a partial +// write: an Add carrying only "" changes nothing and reports Changed false. +// An empty entry already stored is left alone by Add and Remove and cleared by +// a Replace that omits it, which is the ordinary set behavior and not a +// migration. type LabelPatch struct { // Add contains labels to add after any replacement. Add []string @@ -72,6 +87,18 @@ type LabelPatch struct { type MetadataPatch struct { // Replace replaces the complete metadata document when Set is true. A nil or // empty Value clears metadata; a nonempty Value must be valid JSON. + // + // CLEARING STORES THE EMPTY JSON DOCUMENT. An issue's metadata is never + // SQL NULL, and it is never NULL at creation either, so "created with no + // metadata" and "given metadata and then cleared" are the SAME stored + // value rather than two states for one user-visible fact. A consumer + // filtering on `metadata IS NULL` therefore matches neither, and one + // asking for an empty document matches both. + // + // Read back through a result or the Reader role, that same empty document + // arrives as an EMPTY json.RawMessage rather than the two bytes of an + // empty object — so a caller must treat nil, empty and {} as one value on + // the way out, exactly as this field treats them on the way in. Replace Field[json.RawMessage] // Merge merges a metadata document into the current value. A nil or empty // Value is invalid; a nonempty Value must be a JSON object. @@ -227,13 +254,46 @@ type UpdateRequest struct { // ExpectedStatus requires the current status to match. It must be nil when // Claim is true. ExpectedStatus *Status + // IssuePlaneOnly restricts the update to the issue plane: an ID that names + // a wisp is ErrNotFound rather than an ephemeral row to update. The zero + // value keeps the both-plane auto-resolve every caller gets today. + // + // Resolution happens INSIDE the transaction the update runs in, so a + // caller cannot be handed the plane an earlier read saw. It exists for the + // surface that serves durable issues only — refusing there rather than + // carrying a private copy of the resolve is what keeps the two front doors + // on one implementation. + IssuePlaneOnly bool + // Provenance labels the version-control history entry this mutation + // records, naming the surface the update came from. Empty selects the + // implementation's default label. + // + // It NEVER changes WHETHER history is recorded — only how the entry reads. + // An update that records none records none with it set, one that records + // one records one with it empty, and an implementation with no history to + // label ignores it. Persistence, not this, is what decides whether an issue + // is versioned at all. + Provenance string } // CloseRequest describes an issue closure. type CloseRequest struct { Actor string IssueID string - Reason string + // Reason records why the issue was closed. It is stored on the issue and + // read back on CloseResult.Issue.CloseReason, alongside the ClosedAt the + // same close stamps. + // + // THE FIRST CLOSE WINS. A second Close of an already-closed issue is the + // no-op CloseResult.Changed describes, so it writes neither this nor + // Session and the stored pair keeps the values the first close gave them + // — a replayed close cannot rewrite the record of why the work ended. A + // Reopen clears both, because they describe a closure that no longer + // holds. + Reason string + // Session names the working session that closed the issue. It is stored + // and read back on CloseResult.Issue.ClosedBySession, under the same + // first-close-wins rule as Reason. Session string // Force bypasses only blocker and open-child close policy. It never bypasses // validation, ExpectedVersion, or lifecycle rules. @@ -249,10 +309,27 @@ type ReopenRequest struct { IssueID string // Reason records why literal closed and configured done statuses move to // open. Non-done statuses are unchanged. + // + // WHERE it is recorded is the issue's EVENT HISTORY, carried on the + // reopened entry the move itself records. It is not stored on a field of + // the issue and ReopenResult does not surface it, so a caller that wants + // it back reads the issue's events — the same place the Actor attribution + // for the reopen lives. A reopen with no reason still records that entry; + // it simply carries none. Reason string // ExpectedVersion requires the current row version to match and is checked // before a non-done no-op. ExpectedVersion *int64 + // Provenance labels the version-control history entry this reopen records, + // naming the surface it came from. Empty selects the implementation's + // default label, and the implementations do not agree on what that is — the + // store-backed ones write "bd: reopen issue" and the unit-of-work one + // "reopen issue", neither naming the issue. A caller that wants one entry + // no matter which backend served it spells one, exactly as + // UpdateRequest.Provenance describes. + // + // It NEVER changes WHETHER history is recorded — only how the entry reads. + Provenance string } // CreateResult reports the created issue as a detached snapshot with labels, @@ -325,8 +402,9 @@ type Lifecycle interface { // category into it answers to close policy: an unforced crossing with open // children returns CloseOpenChildrenError and one with a live direct blocker // returns ErrCloseBlocked, both without mutation. ForceClosePolicy bypasses - // those two refusals and nothing else. A refusal or validation error leaves - // persistent state unchanged. + // those two refusals and nothing else. A Claim that loses its + // compare-and-set returns *ClaimConflictError carrying the state that beat + // it. A refusal or validation error leaves persistent state unchanged. Update(context.Context, UpdateRequest) (UpdateResult, error) // Close validates guards and commits the complete request as one atomic // mutation. It moves the issue to literal StatusClosed, including from a diff --git a/issueops/issueops_external_test.go b/issueops/issueops_external_test.go index 470447277..a81fd64ae 100644 --- a/issueops/issueops_external_test.go +++ b/issueops/issueops_external_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "fmt" "reflect" "strings" "testing" @@ -213,6 +214,35 @@ func TestPublicDependencyConflictTypesRemainCanonical(t *testing.T) { } } +// TestClaimConflictCarriesTheStateThatBeatIt pins the whole point of the typed +// conflict: a caller reports who won by reading FIELDS, and still classifies +// the refusal by sentinel. +func TestClaimConflictCarriesTheStateThatBeatIt(t *testing.T) { + conflict := &issueops.ClaimConflictError{ + IssueID: "bd-1", + Assignee: "bob", + Status: issueops.StatusInProgress, + Err: issueops.ErrAlreadyClaimed, + } + if !errors.Is(conflict, issueops.ErrAlreadyClaimed) { + t.Fatalf("ClaimConflictError does not match ErrAlreadyClaimed: %v", conflict) + } + var recovered *issueops.ClaimConflictError + if !errors.As(fmt.Errorf("claim bd-1: %w", conflict), &recovered) { + t.Fatal("ClaimConflictError is not recoverable through a wrap") + } + if recovered.Assignee != "bob" || recovered.Status != issueops.StatusInProgress { + t.Errorf("recovered = %+v, want the observed assignee and status", recovered) + } + + // The zero observation is a documented state, not a panic: the refusal + // stands, it just carries nothing. + bare := &issueops.ClaimConflictError{IssueID: "bd-1", Err: issueops.ErrNotClaimable} + if !errors.Is(bare, issueops.ErrNotClaimable) || bare.Error() != issueops.ErrNotClaimable.Error() { + t.Errorf("unobserved conflict = %q, want the bare sentinel", bare.Error()) + } +} + type operationsProbe struct{} func (operationsProbe) Create(context.Context, issueops.CreateRequest) (issueops.CreateResult, error) { diff --git a/issueops/reader.go b/issueops/reader.go index 2b1bf060f..0ea5a2ae4 100644 --- a/issueops/reader.go +++ b/issueops/reader.go @@ -87,18 +87,39 @@ type ReadyRequest struct { // stay distinguishable, which is what lets one constant serve both // surfaces. Limit *int - // Offset skips the first N matching rows, where the backend supports it. + // Offset skips the first N matching rows. It is honored by the + // unit-of-work implementation, which renders OFFSET; the store-backed one + // cannot, and REFUSES a non-zero Offset with a typed *ErrUnsupported + // naming the operation and the backend. What it never does is silently + // return an unpaged answer, so a caller that sets it either gets the page + // it asked for or an error it can classify with errors.As. + // + // A ready request carries no keyset position, so there is no portable way + // to page ready work. A caller that must page across backends pages a + // ListRequest instead — see ListRequest.Offset. Offset int } // ListRequest describes one issue-list query. // -// Like ReadyRequest it is high-level: the default status/template/gate/infra -// exclusions, type validation, status parsing and limit defaulting are all -// applied inside. +// Like ReadyRequest it is high-level: the default +// status/pinned/template/gate/infra exclusions, type validation, status +// parsing and limit defaulting are all applied inside. +// +// PINNED is TWO exclusions rather than one, because a row can be pinned two +// unrelated ways and each is hidden by its own predicate. The `pinned` STATUS +// is one of the statuses the default status exclusion covers, alongside +// `closed`; the separate Pinned FLAG — a marker on a row of any status — is +// hidden by a predicate of its own. A row carrying either is absent from a +// default listing, and the knob that takes each back off is a different one: +// see Status for the first and PinnedFlag for the second. type ListRequest struct { // Status selects statuses; one name, or a comma-separated OR set. Setting // it REPLACES the default exclusions rather than fighting them. + // + // It replaces the STATUS ones only. The pinned-flag predicate survives it, + // so `pinned` and `hooked` are the two spellings that also drop that + // predicate — every other status narrows to unflagged rows. Status string // IssueType is validated against the workspace vocabulary — unlike // ReadyRequest.IssueType, which matches nothing rather than failing. @@ -143,6 +164,21 @@ type ListRequest struct { PriorityMin *int PriorityMax *int + // PinnedFlag and NoPinnedFlag select on the Pinned FLAG, which is not the + // `pinned` status — see this type's own doc for why there are two of them. + // + // PinnedFlag answers with the FLAGGED rows and only them, at any status: it + // drops the default status exclusions on the way, so a closed pinned row — + // which a default listing hides twice over — is in that answer. + // + // NoPinnedFlag asks for the UNFLAGGED rows, which a default listing already + // answers with. Its work is holding that predicate in place where AllFlag + // or a pinned/hooked Status would otherwise have dropped it, so on a + // default listing it changes nothing and on those it narrows. + // + // On the ReadyFlag arm neither applies: that set decides pinned for itself, + // which is why PinnedFlag is refused there and NoPinnedFlag merely accepted + // (see AllFlag). PinnedFlag bool NoPinnedFlag bool IncludeTemplates bool @@ -165,8 +201,38 @@ type ListRequest struct { MetadataFields map[string]string HasMetadataKey string - // AllFlag drops the default status exclusions; ReadyFlag switches the - // query to blocker-aware ready work under the list vocabulary. + // AllFlag drops the default status exclusions. + // + // ReadyFlag switches the query to the blocker-aware ready set. It does NOT + // simply add a blocker predicate to this listing: that query reads a + // narrower filter vocabulary than this request can describe, and only part + // of the request reaches it. + // + // WHAT IT CARRIES: IssueType, all five label forms, Assignee, NoAssignee, + // the exact Priority, ParentID, MolType, WispType, MetadataFields, + // HasMetadataKey, the type exclusions (ExcludeTypes, and with them + // IncludeGates and IncludeInfra), Limit and Offset. SortBy and Reverse + // still apply, because the display order is applied to the page after the + // query rather than inside it. Status and AllFlag are resolved to "open" + // and have no further effect: ready work is open work. + // + // WHAT IT REFUSES: every other filter here is one the ready query cannot + // carry, so combining it with ReadyFlag returns ErrValidation naming the + // fields rather than answering a wider question than was asked. That is + // IDFilter, TitleSearch, SpecPrefix, the four *Contains fields, + // ExternalRef, every Created/Updated/Closed/Defer/Due bound, DeferredFlag, + // OverdueFlag, EmptyDesc, NoLabels, NoParent, PinnedFlag, PriorityMin, + // PriorityMax, and the keyset position. There is no fallback: no + // combination of the two silently widens the answer. + // + // TWO THINGS THE READY SET DECIDES FOR ITSELF, which no field here + // overrides. It never returns pinned issues, which is why NoPinnedFlag is + // accepted and PinnedFlag refused. And it applies no template predicate at + // all, so this request's default template exclusion does not reach it and + // IncludeTemplates changes nothing here: a template is left out of a + // ReadyFlag listing only when its issue type is one the ready query + // already excludes. SkipLabels is likewise not carried — labels are + // hydrated either way, which costs time and not correctness. AllFlag bool ReadyFlag bool @@ -182,7 +248,17 @@ type ListRequest struct { // is derived from it inside the implementation, together with the // over-fetch that detects truncation. Limit *int - // Offset skips the first N matching rows, where the backend supports it. + // Offset skips the first N matching rows. It is honored by the + // unit-of-work implementation, which renders OFFSET; the store-backed one + // cannot, and REFUSES a non-zero Offset with a typed *ErrUnsupported + // naming the operation and the backend. What it never does is silently + // return an unpaged answer, so a caller that sets it either gets the page + // it asked for or an error it can classify with errors.As. + // + // THE PORTABLE WAY TO PAGE IS THE KEYSET POSITION below, + // AfterCreatedAt/AfterID: every implementation honors it, and it does not + // skip or repeat rows when the result set changes underneath a walk. + // Offset is here for the surfaces that already published it. Offset int // AfterCreatedAt and AfterID carry a decoded keyset position in the @@ -198,6 +274,45 @@ type GetRequest struct { // resolution here: an interactive affordance that can resolve to a // different issue than the caller named has no place on a contract two // front doors share. The issue-to-wisp fallback DOES happen inside. + // + // THAT FALLBACK NEEDS NO PLANE ORDER, and this contract deliberately + // states none: no LOCAL WRITE PATH can make an id resident in both planes, + // so the state an order would arbitrate is not reachable by writing + // through this library. Every local write path closes it. A guarded create + // probes BOTH tables before inserting + // and answers ErrAlreadyExists for an id either one already holds. Every + // batch create — import, a graph apply, a cooked formula, a markdown + // import — refuses on top of that an id already resident in the SIBLING + // table, skipping the row rather than hard-failing only on the + // auto-import recovery path, which leaves the resident row alone. + // Promotion and demotion insert into the target plane and delete from the + // source inside ONE transaction, so their dual-presence window never + // commits. This is why the implementations are free to probe the planes in + // either order, and why they in fact differ — a documented non-issue + // rather than a latent divergence (bd-yby99.22). + // + // TWO CAVEATS ARE WORTH CARRYING, and the second is the load-bearing one. + // + // First: the graph-apply path served by a unit-of-work provider gets its + // refusal from a preflight ABOVE storage rather than from the create + // guard, so a future caller that reached the graph-apply use case directly + // would be the thing that made this reachable. + // + // Second, and NOT closed by anything here: REPLICATION. The durable plane + // merges from a remote on pull, the ephemeral tables are dolt-ignored and + // local-only, and no post-merge check reconciles the two — the collision + // guard is reachable only from the create path. So a clone holding a wisp + // whose id another clone promoted to durable receives that id into the + // issues plane while its own wisp row survives. That needs a deterministic + // id to collide at all, which explicit-id creates and the identically + // minted infra wisps supply. It is a REAL residual path, it is outside + // this library's reach, and the resulting state is worse than an + // unspecified plane order: the merge-based lookups behind ready and search + // hard-error for the whole store. A plane order here would not rescue it. + // + // So the honest statement is the scoped one — no local write path reaches + // dual residency, replication can, and a caller that hits it has a + // corrupt store rather than an ordering question (bd-yby99.22). ID string // IncludeDependents and IncludeComments populate the two expensive row // lists. Both default off: the detail view carries counts, and a caller diff --git a/issueops/reader_ready_scope.go b/issueops/reader_ready_scope.go new file mode 100644 index 000000000..982a22faa --- /dev/null +++ b/issueops/reader_ready_scope.go @@ -0,0 +1,116 @@ +package issueops + +import ( + "fmt" + "strings" +) + +// readyScopeField is one ListRequest field the ReadyFlag arm cannot carry, +// paired with the `bd list` flag that sets it. Naming both is the point of the +// refusal: a library caller looks for the struct field and a CLI caller for +// the flag, and neither should have to map one onto the other to learn which +// part of their request could not be honored. +type readyScopeField struct { + name string + flag string + set func(ListRequest) bool +} + +// readyScopeFields is the drop set: every field a list request can set that +// does not survive the trip to the blocker-aware ready query. +// +// It was read off the two functions between this request and that query — +// internal/workapi.BuildListFilter, which turns the request into a storage +// filter, and internal/workapi.ReadyFilterFromIssueFilter, which projects that +// filter onto the narrower ready-work filter — and it is exactly the +// intersection: fields the builder copies onto the filter and the projection +// then discards. +// +// Three groups are deliberately ABSENT, because listing them here would refuse +// requests that are answered correctly today: +// +// - What the projection carries: IssueType, all five label forms, Assignee, +// NoAssignee, the exact Priority, ParentID, MolType, WispType, +// MetadataFields, HasMetadataKey, ExcludeTypes (and with it IncludeGates +// and IncludeInfra's type suppression), Limit, Offset and MaxRows. +// +// - Status and AllFlag. The builder resolves both to "open" under ReadyFlag +// before the projection ever runs, so IssueFilter.Statuses is never +// populated on this path and there is nothing for the projection to drop. +// Ready work is open work; that override is pinned by the builder's golden +// file (internal/workapi/testdata/list_filter_golden.json, +// ready_flag_overrides_status). +// +// - NoPinnedFlag. Pinned is dropped by the projection, but the ready-work +// WHERE clause excludes pinned rows unconditionally +// (internal/storage/sqlbuild/ready.go), so a caller who asks for the +// pinned rows to be left out gets exactly that. The opposite request, +// PinnedFlag, asks for pinned rows only and would be answered with a set +// that can never contain one — it is in the list below. +var readyScopeFields = []readyScopeField{ + {"IDFilter", "--id", func(r ListRequest) bool { return r.IDFilter != "" }}, + {"TitleSearch", "--title", func(r ListRequest) bool { return r.TitleSearch != "" }}, + {"SpecPrefix", "--spec", func(r ListRequest) bool { return r.SpecPrefix != "" }}, + + {"TitleContains", "--title-contains", func(r ListRequest) bool { return r.TitleContains != "" }}, + {"DescContains", "--desc-contains", func(r ListRequest) bool { return r.DescContains != "" }}, + {"NotesContains", "--notes-contains", func(r ListRequest) bool { return r.NotesContains != "" }}, + {"ExternalContains", "--external-contains", func(r ListRequest) bool { return r.ExternalContains != "" }}, + {"ExternalRef", "--external-ref", func(r ListRequest) bool { return r.ExternalRef != "" }}, + + {"CreatedAfter", "--created-after", func(r ListRequest) bool { return r.CreatedAfter != nil }}, + {"CreatedBefore", "--created-before", func(r ListRequest) bool { return r.CreatedBefore != nil }}, + {"UpdatedAfter", "--updated-after", func(r ListRequest) bool { return r.UpdatedAfter != nil }}, + {"UpdatedBefore", "--updated-before", func(r ListRequest) bool { return r.UpdatedBefore != nil }}, + {"ClosedAfter", "--closed-after", func(r ListRequest) bool { return r.ClosedAfter != nil }}, + {"ClosedBefore", "--closed-before", func(r ListRequest) bool { return r.ClosedBefore != nil }}, + {"DeferAfter", "--defer-after", func(r ListRequest) bool { return r.DeferAfter != nil }}, + {"DeferBefore", "--defer-before", func(r ListRequest) bool { return r.DeferBefore != nil }}, + {"DueAfter", "--due-after", func(r ListRequest) bool { return r.DueAfter != nil }}, + {"DueBefore", "--due-before", func(r ListRequest) bool { return r.DueBefore != nil }}, + + {"DeferredFlag", "--deferred", func(r ListRequest) bool { return r.DeferredFlag }}, + {"OverdueFlag", "--overdue", func(r ListRequest) bool { return r.OverdueFlag }}, + {"EmptyDesc", "--empty-description", func(r ListRequest) bool { return r.EmptyDesc }}, + {"NoLabels", "--no-labels", func(r ListRequest) bool { return r.NoLabels }}, + {"NoParent", "--no-parent", func(r ListRequest) bool { return r.NoParent }}, + {"PinnedFlag", "--pinned", func(r ListRequest) bool { return r.PinnedFlag }}, + + {"PriorityMin", "--priority-min", func(r ListRequest) bool { return r.PriorityMin != nil }}, + {"PriorityMax", "--priority-max", func(r ListRequest) bool { return r.PriorityMax != nil }}, + + // The keyset position is a pair and only the timestamp half decides + // whether one was supplied; AfterID alone is not a position. + {"AfterCreatedAt/AfterID", "cursor", func(r ListRequest) bool { return r.AfterCreatedAt != nil }}, +} + +// ValidateReadyFlagScope refuses a list request that combines ReadyFlag with a +// filter the blocker-aware ready query cannot carry, naming every field it +// could not honor. A generic refusal would leave the caller to bisect their +// own request. +// +// This is the enforcement half of ListRequest.ReadyFlag's promise; the other +// half is the doc comment there. It lives beside that promise rather than in +// any implementation, and it is called from the single builder every +// implementation of Reader runs (internal/workapi.BuildListFilter), so no +// backend can be missing it — a per-backend copy is the drift this role exists +// to remove. +// +// A request without ReadyFlag is never refused here: every field below is +// honored by the ordinary listing. +func ValidateReadyFlagScope(req ListRequest) error { + if !req.ReadyFlag { + return nil + } + var named []string + for _, f := range readyScopeFields { + if f.set(req) { + named = append(named, f.name+" ("+f.flag+")") + } + } + if len(named) == 0 { + return nil + } + return fmt.Errorf("%w: --ready cannot filter on %s; the blocker-aware ready query carries only part of the list vocabulary, so answering would return every ready issue rather than the ones asked for — drop --ready, or drop what it cannot carry", + ErrValidation, strings.Join(named, ", ")) +} diff --git a/issueops/readyclaimer.go b/issueops/readyclaimer.go new file mode 100644 index 000000000..3ce2f4f78 --- /dev/null +++ b/issueops/readyclaimer.go @@ -0,0 +1,92 @@ +package issueops + +import "context" + +// ClaimNextRequest describes one atomic take of ready work. +type ClaimNextRequest struct { + // Actor is the claimant and must not be empty. + Actor string + // Filter selects the candidate set in Reader.Ready's EXACT vocabulary — + // the same type, not a parallel one shaped like it. 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. + // + // Limit and Offset must be unset (ErrValidation). A claim delivers exactly + // the one row it wins no matter how large the pool it scanned, and the + // scan itself must stay unbounded: the implementation walks the ready + // order and continues past rows a racing agent already took, so a bounded + // window would report "nothing to claim" whenever that window happened to + // be unclaimable while plenty of other ready work remained. Rejecting the + // two fields says that out loud rather than accepting them and quietly + // dropping them. + Filter ReadyRequest +} + +// ClaimNextResult reports the claim. +type ClaimNextResult struct { + // Claimed is the claimed row with its relationship cardinalities, hydrated + // inside the transaction that committed the claim, so the counts describe + // the state the claim actually produced rather than a later one. + // + // It is nil when nothing was eligible. That is a NORMAL outcome, not an + // error: 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. Nothing is written and no history entry is + // recorded for it. + Claimed *IssueWithCounts +} + +// ReadyClaimer describes the atomic take of ready work: the operation `bd +// ready --claim` performs, and — like Lifecycle and Reader — a role with its +// own accessor. A new capability gets a new role interface and its own +// accessor; never append a method here. +// +// It is a role of its own rather than a fifth Lifecycle verb because it is not +// a mutation of an issue the caller names. The caller names a QUESTION and the +// implementation picks the answer, which makes selection part of the +// operation's contract: the ready predicate, the compare-and-set that wins the +// row, and the hydration of the row that was won all belong to the same +// transaction, and none of them is expressible as a patch. +// +// Implementations never mutate caller-owned request values, snapshot the +// request at method entry, and apply validation and normalization only to +// attempt-local clones. Deterministic request-validation failures match +// ErrValidation. Result values are unspecified when error is non-nil; a +// validation failure leaves persistent state unchanged. +type ReadyClaimer interface { + // ClaimNext claims the first ready issue matching the request's filter and + // returns it hydrated. Selection, the compare-and-set and the hydration + // share ONE transaction, so the row cannot move between being chosen and + // being reported. + // + // The ready set is whatever the request's filter admits — the same set + // Reader.Ready lists for that filter, which is the whole point of the two + // surfaces sharing a request type. Ephemeral rows are outside it by + // default, and a filter that sets IncludeEphemeral pulls them in for the + // claim exactly as it does for the listing: such a row IS claimable, and + // claiming it moves the ephemeral row itself rather than promoting it to + // a durable one or refusing it. + // + // At most one durable history entry is recorded, and none at all when + // nothing was eligible. A claim that wins an EPHEMERAL row records none + // either: ephemeral rows are not versioned, so the row moves to + // in-progress under the actor while the durable history stands still. A + // caller reconstructing who took what from history alone will not see + // those claims — read the row. + // + // A DURABLE win grants EXACTLY ONE LEASE on the row it won. The lease is + // what makes the claim recoverable — it is the handle heartbeats extend, + // and the row lease-expiry recovery walks once nothing extends it — so a + // win that wrote no lease would hand out work nothing could ever take + // back. + // + // An ephemeral win carries NO LEASE, which is the sharper of the two + // consequences because it has no expiry to wait out. Heartbeats refuse an + // ephemeral row and lease-expiry recovery only walks leased durable ones, + // so nothing reclaims the row if its claimant dies: it stays in-progress + // under a gone actor until something releases or finishes it. A caller + // that hands ephemeral work to agents it does not supervise owns that + // recovery itself. + ClaimNext(ctx context.Context, req ClaimNextRequest) (ClaimNextResult, error) +} diff --git a/issueops/relations.go b/issueops/relations.go new file mode 100644 index 000000000..71381133f --- /dev/null +++ b/issueops/relations.go @@ -0,0 +1,99 @@ +package issueops + +import ( + "context" + + "github.com/steveyegge/beads/internal/types" +) + +// RelatedIssue is one issue on the far end of an edge, carrying the edge's +// type alongside the issue's own fields. +// +// It is an ISSUE and can be nothing else, which settles what an edge whose +// target is neither issue nor wisp answers with. A dependency target may be an +// "external:" reference or an issue belonging to ANOTHER repository — see +// DependencyEditor, which accepts both — and this database holds no row for +// either. Such an edge has no far end to describe here, so it is not a neighbor: +// Related leaves it out, with no placeholder row and no error. +// +// The consequence is worth stating because it is not visible in the answer: the +// length of a result is the anchor's neighbor count and NOT its edge count, and +// the two differ by however many of its edges point outside this database. A +// caller that needs the edges themselves needs a role that answers with edges. +type RelatedIssue = types.IssueWithDependencyMetadata + +// RelationDirection selects which way the anchor's edges are walked. +// +// Its ZERO VALUE is invalid, and that is the point. A silent default direction +// is how a caller asks for "what blocks this" and is handed "what this blocks" +// — the exact inverse of the graph it wanted, with the same shape, the same +// field names and no error to notice. +type RelationDirection string + +const ( + // RelationOut walks OUTGOING edges: the issues the anchor depends on. + RelationOut RelationDirection = "out" + // RelationIn walks INCOMING edges: the issues that depend on the anchor. + RelationIn RelationDirection = "in" +) + +// RelatedRequest describes one neighbor query. +type RelatedRequest struct { + // ID is the anchor's exact canonical id, and EXACT is a promise the role + // keeps rather than an obligation it puts on the caller: a spelling that is + // not the stored one resolves to nothing. A case variant, an id carrying + // surrounding whitespace, a prefix of a real id and a real id with a suffix + // are all misses, for the same reason GetRequest.ID has no fuzzy resolution + // — an affordance that can answer ABOUT A DIFFERENT ISSUE than the caller + // named has no place on a contract an unattended client calls. + // + // Both planes are searched, and a miss on both is ErrNotFound rather than an + // empty answer: "this issue has no dependencies" and "there is no such + // issue" are different facts, and a caller that cannot tell them apart + // reports a typo as a clean graph. + ID string + // Direction is required. The zero value is ErrValidation; there is no + // implicit "both", and no direction is the default. + Direction RelationDirection + // Types restricts the answer to these edge types. Empty means every type. + // + // An entry is checked for being a value at all — non-empty, within the + // column's length — and NEVER for membership of a known-types list: the + // vocabulary is OPEN (see the Dep* constants), so a workspace's own type + // has to be able to filter. An unusable entry is ErrValidation rather than + // a filter that quietly matches nothing. + Types []DependencyType +} + +// Relations describes reading an issue's neighbors: the read side of `bd dep +// list`, and — like Reader — a role with its own accessor. A new capability +// gets a new role interface and its own accessor; never append a method here. +// +// It is its own role rather than a fourth Reader method because it answers a +// question about EDGES. Reader's three methods all answer with pages of +// issues, selected by the issues' own fields; this one is anchored on a +// specific issue and its answer is shaped by the edges reaching it, which is +// why its result carries the edge type and its request carries a direction. +// +// The dependency TREE is deliberately not here. A recursive walk has a depth, +// a cycle policy and a node shape of its own, and it answers with a forest +// rather than a list — a different question, so a different role when +// something needs it. +// +// Implementations never mutate caller-owned request values, snapshot the +// request at method entry, and apply validation and normalization only to +// attempt-local clones. RelatedRequest travels by value, so Types is the one +// member a body could write through to the caller at all: reading it into a +// set is fine, sorting or de-duplicating it in place is not. +type Relations interface { + // Related returns the anchor's neighbors in the requested direction. + // + // THE ORDER IS PINNED: ascending by the neighbor's id, with the edge type + // breaking a tie. It is pinned rather than left to the query because the + // rows come from two dependency tables read in sequence, so the natural + // order is an artifact of which plane a neighbor happens to live on — + // stable enough to look deliberate and not stable enough to rely on. + // + // The result is never nil for a successful call. + Related(ctx context.Context, req RelatedRequest) ([]*RelatedIssue, error) +} diff --git a/tests/oracle-a/harness/scenarios/enumerated.json b/tests/oracle-a/harness/scenarios/enumerated.json index 59475727e..ba5e880ab 100644 --- a/tests/oracle-a/harness/scenarios/enumerated.json +++ b/tests/oracle-a/harness/scenarios/enumerated.json @@ -2479,7 +2479,7 @@ "--json" ] ], - "pins": "{\"error\":\"invalid dependency type \\\"\\\" (must be non-empty, max 50 chars); valid types: ...\"} on STDOUT; exit 1.", + "pins": "{\"error\":\"invalid dependency type \\\"\\\" (must be non-empty, max 32 chars); valid types: ...\"} on STDOUT; exit 1.", "deterministic": true }, { @@ -5381,7 +5381,7 @@ "--json" ] ], - "pins": "Error 'invalid dependency type \"\": must be non-empty and at most 50 characters'; exit 1; JSON error envelope on stdout.", + "pins": "Error 'invalid dependency type \"\": must be non-empty and at most 32 characters'; exit 1; JSON error envelope on stdout.", "deterministic": true }, {