feat(issueops): put every issue capability behind one library surface
Beads had two implementations of most issue verbs: one for the direct route
(the CLI talking to a store it opened itself) and one for the proxied-server
route (the CLI talking through a unit of work over a running Dolt server).
They drifted — different commit messages, different transaction boundaries,
different refusals, occasionally different answers.
Seven role interfaces now live in the leaf package issueops: Lifecycle,
Reader, ReadyClaimer, BatchCloser, DependencyEditor, Commenter and Relations.
Each is reached only through a store accessor, never a constructor, because
the accessor is where the hook and telemetry decorators add their layers.
Three implementations back every role — dolt, embeddeddolt, and the
unit-of-work provider the proxied route uses. Both routes call the same role
for close, dep add/remove/list, comment, ready --claim and update.
A depguard rule (httpapi-domain-boundary) denies internal/storage/domain from
internal/httpapi, so a handler cannot reach uw.IssueUseCase() past the roles
and open a second front door one lint-clean commit at a time.
Behaviour users will notice, all in the CHANGELOG:
- bd close a b c is one Dolt commit, not three, and --claim-next moved
inside that transaction so it fires only when something landed
- the open-children guard moved into the transaction and its hand-rolled
cmd/bd copy is gone, removing a read-then-write window that made
bd close <child> <parent> depend on argument order
- bd dep add --file honours deferred version commit
- embedded bd comment writes the role's message and author
- dep verb commit messages are the role's on the direct route
Wisp-sourced dependency edges are restored. Moving bd dep add onto the role
had pinned an edge's SOURCE to the issues plane, and the two routes did not
even fail alike: direct refused with "issue <id> not found", proxied threw an
fk_dep_issue violation. The comment justifying the pin claimed the issues
plane was "the only one its unit-of-work sibling can reach" — that was false;
domain.DependencyUseCase declared a full set of wisp twins with no production
caller. All three implementations now route per edge by the edge's own
source. A mixed request stays one transaction: parent-child-first ordering
and the whole-graph cycle gate span both planes, and a refusal rolls back
both. Behind the role, three bulk add verbs collapsed into one source-routed
AddDependencies, so no plane-pinned variant is left to reach for by mistake.
Six Provenance fields with no production caller were deleted rather than
wired — CloseRequest, CloseBatchRequest, ClaimNextRequest, AddCommentRequest,
AddDependenciesRequest, RemoveDependencyRequest. Each role already composes an
id-bearing message, so a caller could only restate the default and make it
unreachable from production. Two are not caller-settable even in principle:
CloseBatchCommitMessage names what LANDED and ClaimNextCommitMessage names the
id the claim WON. UpdateRequest and ReopenRequest keep theirs; commit messages
users see are unchanged.
Verified: build, vet and gofmt clean; golangci-lint 0 issues; protocol corpus
byte-identical under BEADS_PROTOCOL_REQUIRE_DOLT=1; all twelve
DependencyEditor conformance wirings green (four contract functions against
each implementation); TestEmbeddedDepAddWispSource runs bd dep add <wisp-id>
at the front door and was demonstrated RED against the pinned routing first.
Three internal/storage/dolt failures reproduce on pristine origin/main.
Known gaps are enumerated in the PR description rather than left to be found:
comment listing is on no role, bd dep tree and bd dep cycles have no role,
bd create and bd reopen are on Lifecycle only on the direct route, per-edge
line attribution is lost in bd dep add --file, multi-store bd close
--claim-next rides only the first store's batch, and the is_blocked staging gap
(bd-2y9ke, predates this change). Seven of the eight role interfaces now have a
shared conformance contract in backend/conformance, run at all three
implementations; main's Claimer, added in parallel by #5334, is the eighth and
has none yet.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
0621dd6cef
commit
d801ec43dc
152 changed files with 20222 additions and 1110 deletions
|
|
@ -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
|
||||
|
|
|
|||
443
CHANGELOG.md
443
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 <bead>` 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 <bead>` 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 <id> --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 <done-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 <a> <b>` 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 <a> <b>` and
|
||||
`bd: dep remove <a> <b>` — where the direct path used to write
|
||||
`dependency: add <type> <a> -> <b>` / `dependency: remove <a> -> <b>` in
|
||||
server mode and a generic `bd: dep add (auto-commit) by <actor> [...]` 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 <id>`
|
||||
authored by `beads`, where the CLI auto-commit wrote
|
||||
`bd: comment (auto-commit) by <actor> [<id>]` 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 <id>`) 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 <wisp-id> <target>` 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 <wisp-id>
|
||||
<target>` 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 <id>`, the
|
||||
spelling the other two backends already wrote (it was
|
||||
`bd: ready --claim <id>`); 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 <child> <parent>` 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
|
||||
|
|
|
|||
1322
backend/conformance/batch_closer_contract.go
Normal file
1322
backend/conformance/batch_closer_contract.go
Normal file
File diff suppressed because it is too large
Load diff
561
backend/conformance/commenter_contract.go
Normal file
561
backend/conformance/commenter_contract.go
Normal file
|
|
@ -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 <id>"), 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
|
||||
}
|
||||
1272
backend/conformance/dependency_editor_contract.go
Normal file
1272
backend/conformance/dependency_editor_contract.go
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
768
backend/conformance/lifecycle_close_reopen_contract.go
Normal file
768
backend/conformance/lifecycle_close_reopen_contract.go
Normal file
|
|
@ -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
|
||||
}
|
||||
1472
backend/conformance/reader_contract.go
Normal file
1472
backend/conformance/reader_contract.go
Normal file
File diff suppressed because it is too large
Load diff
765
backend/conformance/ready_claimer_contract.go
Normal file
765
backend/conformance/ready_claimer_contract.go
Normal file
|
|
@ -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
|
||||
}
|
||||
714
backend/conformance/relations_contract.go
Normal file
714
backend/conformance/relations_contract.go
Normal file
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
18
claim.go
18
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 <assignee>"), and on ErrNotClaimable it embeds the
|
||||
// current status ("issue not claimable: status <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
|
||||
// <assignee>"), on ErrNotClaimable the current status ("issue not claimable:
|
||||
// status <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.
|
||||
|
|
|
|||
200
cmd/bd/close.go
200
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
|
||||
}
|
||||
|
|
|
|||
221
cmd/bd/close_direct.go
Normal file
221
cmd/bd/close_direct.go
Normal file
|
|
@ -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 <child> <parent>` 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)
|
||||
}
|
||||
}
|
||||
|
|
@ -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)
|
||||
}
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
198
cmd/bd/dep.go
198
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,
|
||||
|
|
|
|||
186
cmd/bd/dep_bulk_role_test.go
Normal file
186
cmd/bd/dep_bulk_role_test.go
Normal file
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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 <wisp-id> <target>` 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 <id> 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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")
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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{
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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).
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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 <ids>".
|
||||
Provenance: "bd: reopen " + fullID,
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error reopening %s: %v\n", fullID, err)
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
205
cmd/bd/update_claim_proxied_test.go
Normal file
205
cmd/bd/update_claim_proxied_test.go
Normal file
|
|
@ -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")
|
||||
}
|
||||
}
|
||||
|
|
@ -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)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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{
|
||||
|
|
|
|||
153
go.sum
153
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=
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
70
internal/storage/dolt/batch_closer.go
Normal file
70
internal/storage/dolt/batch_closer.go
Normal file
|
|
@ -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)
|
||||
156
internal/storage/dolt/batch_closer_contract_test.go
Normal file
156
internal/storage/dolt/batch_closer_contract_test.go
Normal file
|
|
@ -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()
|
||||
}
|
||||
}
|
||||
|
|
@ -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 {
|
||||
|
|
|
|||
49
internal/storage/dolt/commenter.go
Normal file
49
internal/storage/dolt/commenter.go
Normal file
|
|
@ -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)
|
||||
80
internal/storage/dolt/commenter_contract_test.go
Normal file
80
internal/storage/dolt/commenter_contract_test.go
Normal file
|
|
@ -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()
|
||||
}
|
||||
}
|
||||
104
internal/storage/dolt/commenter_persistence_test.go
Normal file
104
internal/storage/dolt/commenter_persistence_test.go
Normal file
|
|
@ -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 <id>", 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")
|
||||
}
|
||||
}
|
||||
71
internal/storage/dolt/dependency_editor.go
Normal file
71
internal/storage/dolt/dependency_editor.go
Normal file
|
|
@ -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)
|
||||
198
internal/storage/dolt/dependency_editor_contract_test.go
Normal file
198
internal/storage/dolt/dependency_editor_contract_test.go
Normal file
|
|
@ -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()
|
||||
}
|
||||
}
|
||||
159
internal/storage/dolt/dependency_editor_test.go
Normal file
159
internal/storage/dolt/dependency_editor_test.go
Normal file
|
|
@ -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")
|
||||
}
|
||||
}
|
||||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
}
|
||||
}
|
||||
178
internal/storage/dolt/reader_contract_test.go
Normal file
178
internal/storage/dolt/reader_contract_test.go
Normal file
|
|
@ -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()
|
||||
}
|
||||
}
|
||||
74
internal/storage/dolt/ready_claimer.go
Normal file
74
internal/storage/dolt/ready_claimer.go
Normal file
|
|
@ -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)
|
||||
103
internal/storage/dolt/ready_claimer_contract_test.go
Normal file
103
internal/storage/dolt/ready_claimer_contract_test.go
Normal file
|
|
@ -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
|
||||
}
|
||||
47
internal/storage/dolt/relations.go
Normal file
47
internal/storage/dolt/relations.go
Normal file
|
|
@ -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)
|
||||
111
internal/storage/dolt/relations_contract_test.go
Normal file
111
internal/storage/dolt/relations_contract_test.go
Normal file
|
|
@ -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()
|
||||
}
|
||||
}
|
||||
243
internal/storage/dolt/role_fixture_kit_test.go
Normal file
243
internal/storage/dolt/role_fixture_kit_test.go
Normal file
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
42
internal/storage/dolt/role_test_helpers_test.go
Normal file
42
internal/storage/dolt/role_test_helpers_test.go
Normal file
|
|
@ -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)
|
||||
}
|
||||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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")
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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 <assignee>" 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) {
|
||||
|
|
|
|||
72
internal/storage/embeddeddolt/batch_closer.go
Normal file
72
internal/storage/embeddeddolt/batch_closer.go
Normal file
|
|
@ -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)
|
||||
151
internal/storage/embeddeddolt/batch_closer_contract_test.go
Normal file
151
internal/storage/embeddeddolt/batch_closer_contract_test.go
Normal file
|
|
@ -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,
|
||||
}
|
||||
}
|
||||
51
internal/storage/embeddeddolt/commenter.go
Normal file
51
internal/storage/embeddeddolt/commenter.go
Normal file
|
|
@ -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)
|
||||
75
internal/storage/embeddeddolt/commenter_contract_test.go
Normal file
75
internal/storage/embeddeddolt/commenter_contract_test.go
Normal file
|
|
@ -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,
|
||||
}
|
||||
}
|
||||
73
internal/storage/embeddeddolt/dependency_editor.go
Normal file
73
internal/storage/embeddeddolt/dependency_editor.go
Normal file
|
|
@ -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)
|
||||
193
internal/storage/embeddeddolt/dependency_editor_contract_test.go
Normal file
193
internal/storage/embeddeddolt/dependency_editor_contract_test.go
Normal file
|
|
@ -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,
|
||||
}
|
||||
}
|
||||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
}
|
||||
}
|
||||
168
internal/storage/embeddeddolt/reader_contract_test.go
Normal file
168
internal/storage/embeddeddolt/reader_contract_test.go
Normal file
|
|
@ -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
|
||||
},
|
||||
}
|
||||
}
|
||||
63
internal/storage/embeddeddolt/ready_claimer.go
Normal file
63
internal/storage/embeddeddolt/ready_claimer.go
Normal file
|
|
@ -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)
|
||||
98
internal/storage/embeddeddolt/ready_claimer_contract_test.go
Normal file
98
internal/storage/embeddeddolt/ready_claimer_contract_test.go
Normal file
|
|
@ -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,
|
||||
}
|
||||
}
|
||||
49
internal/storage/embeddeddolt/relations.go
Normal file
49
internal/storage/embeddeddolt/relations.go
Normal file
|
|
@ -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)
|
||||
105
internal/storage/embeddeddolt/relations_contract_test.go
Normal file
105
internal/storage/embeddeddolt/relations_contract_test.go
Normal file
|
|
@ -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,
|
||||
}
|
||||
}
|
||||
252
internal/storage/embeddeddolt/role_fixture_kit_test.go
Normal file
252
internal/storage/embeddeddolt/role_fixture_kit_test.go
Normal file
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
44
internal/storage/embeddeddolt/role_test_helpers_test.go
Normal file
44
internal/storage/embeddeddolt/role_test_helpers_test.go
Normal file
|
|
@ -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)
|
||||
}
|
||||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
49
internal/storage/hook_batch_closer.go
Normal file
49
internal/storage/hook_batch_closer.go
Normal file
|
|
@ -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
|
||||
}
|
||||
116
internal/storage/hook_batch_closer_test.go
Normal file
116
internal/storage/hook_batch_closer_test.go
Normal file
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
37
internal/storage/hook_commenter.go
Normal file
37
internal/storage/hook_commenter.go
Normal file
|
|
@ -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
|
||||
}
|
||||
104
internal/storage/hook_commenter_test.go
Normal file
104
internal/storage/hook_commenter_test.go
Normal file
|
|
@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -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
|
||||
|
|
|
|||
60
internal/storage/hook_dependency_editor.go
Normal file
60
internal/storage/hook_dependency_editor.go
Normal file
|
|
@ -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
|
||||
}
|
||||
162
internal/storage/hook_dependency_editor_test.go
Normal file
162
internal/storage/hook_dependency_editor_test.go
Normal file
|
|
@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
38
internal/storage/hook_ready_claimer.go
Normal file
38
internal/storage/hook_ready_claimer.go
Normal file
|
|
@ -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
|
||||
}
|
||||
107
internal/storage/hook_ready_claimer_test.go
Normal file
107
internal/storage/hook_ready_claimer_test.go
Normal file
|
|
@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
17
internal/storage/hook_relations.go
Normal file
17
internal/storage/hook_relations.go
Normal file
|
|
@ -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()
|
||||
}
|
||||
50
internal/storage/hook_relations_test.go
Normal file
50
internal/storage/hook_relations_test.go
Normal file
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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 <assignee>"
|
||||
// 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
|
||||
|
|
|
|||
112
internal/storage/issueops/claim_next.go
Normal file
112
internal/storage/issueops/claim_next.go
Normal file
|
|
@ -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
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue