fix(mol): molecule reads, auto-close and close --continue over http through issueops entries (S16) (#7513)
* fix(create): let a remote backend mint the --parent child id
`bd create --parent` always called the raw GetNextChildID first, which the
http backend does not serve, so every child create on a remote workspace
refused before writing anything. The Lifecycle role already mints
<parent>.<n> for a create that carries a ParentID and no id of its own, on
every backend and inside the create's own transaction; conformance
RunIssueOperationsCreateUnderAParentMintsTheNextChildID pins it on every leg,
the served one included (and the bd-enterprise postgres leg the MC server
runs). So the create route needs no new capability token: on a registered
Remote backend the client skips the raw reservation and lets the server mint.
The local route keeps its reservation so its Dolt commit staging is
unchanged, and an explicit --id beside --parent is still refused up front.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(mol): molecule reads, auto-close and close --continue over issueops roles
Over the http backend three molecule paths failed, and two of them
silently:
- `bd mol current` / `bd mol progress` without an id answered "no molecules"
because the in_progress listing (a raw SearchIssues shape) and the parent
walk (raw GetDependencyRecordsForIssues) were refused and the refusal was
swallowed; with an id they refused on raw GetMoleculeProgress.
- The molecule auto-close after `bd close` never ran: findParentMolecules
swallowed the same refused edge read into "not part of a molecule".
- `bd close --continue` claimed the next step in a raw RunInTransaction.
The direct route now reads molecules through roleMolStore, which answers
through roles every backend serves: EdgeReader (batched at the wire's 100
anchors) for the parent walk, BatchGetter for the roots (Get per id where a
server does not publish issues.batchGet), Relations for the step rows (full
rows; the raw dependents read over http is getIssue's shallow projection,
which zeroed step assignees) and the progress counts, and Reader.List for the
in_progress/hooked listings. The auto-close closes the root through
Lifecycle.Close, and the --continue claim is one Lifecycle.Update guarded by
ExpectedStatus=open.
No refusal is swallowed any more: findParentMolecules, the molecule finders
and the hooked scan return their errors; `mol current/progress` report them;
the auto-close stays best effort but warns on stderr; AdvanceToNextStep only
moves on to the next ready step when the claim LOST a race (status mismatch,
not claimable, already claimed) and returns anything else. The one heuristic
still skipped is the id-pattern heal in loadDescendants, and only for an
ErrUnsupported backend that cannot express an id-prefix search; other
failures now surface. `mol current`/`mol progress` leave the
types.IssueFilter forbidigo hole, since they no longer build a filter.
gc does not depend on bd's molecule auto-close: it runs its own
(cmd/gc/molecule_autoclose.go, from the bd on_close hook and the
controller's bead-close events). Its worker prompts do run `bd mol current`.
Served e2e (TestE2E_MoleculesOverHTTP): create --parent mints <root>.1/.2,
mol current <id> is non-empty with the full in-progress step, mol progress
counts, close --continue auto-advances, closing the last step auto-closes
the root. `mol current` without an id now refuses out loud on this stack
(asserted: never an empty list); its non-empty assertion is skipped until
S6c (externaldeps reader passthrough) is underneath.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(mol): list molecule candidates with the four wire knobs, drop the S6c skip
On top of S6c the in_progress listing behind 'bd mol current' (no id)
reaches the v0 wire encoder, which refuses ListRequest.IncludeAllTypes.
Ask for templates, gates, infra and ephemeral rows explicitly, which the
wire publishes, and run the 'mol current without an id' served case.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* feat(issueops): one library entry each for molecule auto-close, advance and reads
The molecule rules lived only in cmd/bd, in copies that disagreed: two
auto-close implementations that closed the root through different
library entries outside the step close's transaction, a `close
--continue` claim that set no assignee and could take a step another
agent held on the direct and http routes, and three progress counts.
Every molecule rule now has one implementation in the public issueops
package, composed over three roles every backend serves (BatchGetter,
Relations, EdgeReader): MoleculeRoots, LoadMolecule, AnalyzeMolecule,
ViewMolecule, ReadMoleculeProgress, ActiveMoleculeIDs,
CompletedMolecule. Membership is the parent-child edge.
Auto-close: CloseRequest.AutoCloseMolecule and
CloseBatchRequest.AutoCloseMolecule (opt-in, so gc's own auto-close is
not doubled) close the molecule root a close completed IN THE SAME
TRANSACTION, unforced and guarded on the root revision read there:
storageissueops.CloseCompletedMoleculeInTx on the store backends (the
role bodies bound to the caller's tx, TxMoleculeReader) and
uow.CloseCompletedMoleculeInUOW on the unit of work. It replays on an
idempotent re-close, reports the root on CloseResult/CloseOutcome
.AutoClosedMolecule, and a root its own close policy refuses stays open
and is reported (MoleculeAutoCloseRefusal) without failing the step.
Advance: a new MoleculeStepper role (storage.DoltStorage accessor,
uow.MoleculeStepperSource) whose one implementation,
issueops.NewMoleculeStepper, claims the next ready step through the
Claimer (Lifecycle.Update's Claim for a wisp step): assignee set, a step
another actor holds skipped, never taken.
HTTP: closeIssue/batchCloseIssues carry auto_close_molecule behind the
issues.close.autoCloseMolecule behavior token, and POST
/v0/beads/issues/{id}:advanceMolecule (issues.advanceMolecule) serves
the stepper. Handlers only decode, call the role and encode. The client
sends the member and dials the operation only where advertised; against
an older server it DEGRADES rather than refuses — it runs the same
library rule over its own roles (issueops.CloseCompletedMolecule after
the close, NewMoleculeStepper for the advance), so the outcome is the
same in more round trips. The capability fallbacks that lived in
cmd/bd move into the client: BatchGetter answers one getIssue per id
without issues.batchGet, and EdgeReader splits past the operation's 100
anchors.
Conformance: RunMolecule* on dolt, embedded, uow and http (the http leg
twice: served, and against a server with the tokens struck out).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor(cmd/bd): molecule commands and create --parent through the library entries
`bd close`, `bd close --continue`, `bd mol current`, `bd mol progress`,
`bd ready --mol` and `bd create --parent` now call the one library entry
for each rule on every route (direct, proxied server, remote):
- close (batch, --if-revision, proxied) sets CloseRequest/
CloseBatchRequest.AutoCloseMolecule and only reports what the library
closed in the step close's transaction. autoCloseCompletedMolecule,
autoCloseProxiedCompletedMolecule and closeCompletedMoleculeRoot are
gone, and so is the separate post-close write.
- --continue is the route's MoleculeStepper role: a real claim (the
assignee is set) that skips a step another actor holds. Before, the
direct and http routes flipped the status only and could take it.
AdvanceToNextStep, ClaimStepIfOpen and its two implementations are
gone.
- mol current / mol progress / ready --mol read through
issueops.ViewMolecule, ReadMoleculeProgress, ActiveMoleculeIDs and
LoadMolecule/AnalyzeMolecule over the route's roles. Over http this
fixes the missing step assignee on `ready --mol` (corpus mark
mc-ready-mol). The proxied route's SearchIssues fallback, the role
store, the third progress count and the cmd/bd copy of the readiness
analysis are deleted; only presentation stays here.
- create --parent asks the create role to mint the child id on every
route (the local CLI reservation is gone) and to inherit the parent's
labels (InheritLabelsFromParent) inside the create. The dry-run
preview still shows the labels, and a failed label read there is
reported, not swallowed.
TestProxiedServerMoleculeLifecycleAgreesOnEveryRoute runs one molecule
lifecycle through the real binary on the direct, proxied and remote
(`bd connect` to `bd serve`) routes and requires the same rows and the
same JSON on all three. The served e2e now also pins the held-step skip,
the claimed step's assignee and the full rows of `ready --mol`.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(httpclient): refuse molecule auto-close and advance before dialing an older server
The client used to DEGRADE against a server without
issues.close.autoCloseMolecule / issues.advanceMolecule: it closed the step
without the member and ran a second, client-side copy of the auto-close
(issueops.CloseCompletedMolecule) in its own transactions, and composed the
stepper over its own roles. That kept two executions of each rule alive.
Now the rule runs in ONE place, the server's library: a close or batch close
that sets AutoCloseMolecule, and an Advance, refuse before anything is dialed
with the typed capability error (storage.ErrUnsupported, Capability naming the
token). The composed single-item batch leg now carries the member too.
- issueops.CloseCompletedMolecule (the role-composed form) is gone.
MoleculeRootClose is the one root close request (unforced, the auto-close
reason, the session, guarded on the root revision read), and both
in-transaction bodies (storage issueops CloseCompletedMoleculeInTx, uow
CloseCompletedMoleculeInUOW) build from it.
- MoleculeView.Ready is `bd ready --mol`'s list (every analysis-ready node,
hydrated), so ready --mol and mol current derive from ViewMolecule alone.
Tests: unit pre-dial refusal and member pins (httpclient molecule_test.go),
TestServedMoleculeRefusesAgainstAnOlderServer (step stays open, nothing
claimed) replacing the degraded contract arm.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(cmd/bd): ask for the molecule auto-close only where the route serves it
The refuse-before-dialing client made every `bd close` over http fail
against a server that does not advertise issues.close.autoCloseMolecule
(an older bd serve, or the MC server shape, whose orchestrator owns the
molecule lifecycle): the CLI always set AutoCloseMolecule.
storage.ServesMoleculeAutoClose answers, through every decorator, whether a
store's closes may carry the flag (MoleculeAutoCloseProber, implemented by
httpclient.Store from its handshake; every local backend serves it). The
direct batch close and the --if-revision close set the flag from it; the
proxied route always serves it. Against a silent server the close goes out
without the member and the server's side owns the auto-close.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(backend/http): scope the advertised-policy check to reads before the close
The close policy check is the client-side policy's last chance: it runs
before the close request, so only the reads up to that request count. A
read after the close (the old-server molecule notice reads the closed
step's edges) is not the external-dependency policy.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(backend/http/corpus): drop the six marks S16 and S19 retire
With the molecule library entries underneath, mol current (with and
without an id, json and text), mol progress and ready --mol read through
issueops.LoadMolecule over the roles, and create --parent lets the server
mint the child id. Those six shapes pass on the reference profile.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(cmd/bd): never silent against a server without the molecule tokens
Against a server that advertises neither issues.close.autoCloseMolecule
nor issues.advanceMolecule (an older bd serve, or one whose orchestrator
owns the molecule lifecycle):
- `bd close --continue` closed the step and only then found the advance
refused, leaving the step closed and the next step unclaimed. It now
asks storage.ServesMoleculeAdvance (a MoleculeAdvanceProber the http
store answers from its handshake; local backends always serve it)
BEFORE the close and refuses up front, saying nothing was closed.
- `bd close` went out without auto_close_molecule and said nothing. When
the closed step belongs to a molecule (issueops.MoleculeRoot), a notice
on stderr now names the molecule and the missing token: its auto-close
is the server's to run. The batch and --if-revision closes both say it.
The served e2e masks both tokens out of the handshake and checks the
up-front refusal (the step stays open) and the notice; the httpclient
unit test pins ServesMoleculeAdvance to the handshake.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor(cmd/bd): mol show through issueops.LoadMolecule on every route
`bd mol show` still loaded the molecule through cmd/bd's
loadTemplateSubgraph (raw GetIssue, GetDependentsWithMetadata and
GetDependencyRecords, plus an id-pattern child probe), while mol current,
mol progress and ready --mol read through the library. It now loads
through issueops.LoadMolecule over the route's molecule roles (the direct
store's, or the proxied provider's), so membership is the parent-child
edge everywhere and the http route reads through roles the server serves.
The served e2e checks mol show's root and step count.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs: the molecule auto-close fails the step's close on a non-policy error; stale comments
CloseRequest.AutoCloseMolecule and CloseCompletedMoleculeInTx now say what
changed when the auto-close moved into the close's transaction: a root
close the close policy refuses still leaves the root open and is reported,
but any other failure (a storage error, a lost race on the root's revision)
fails the step's close with it, where the CLI used to close the root
afterwards and only warn.
Stale: the advanceMolecule vocabulary entry said the client composes the
stepper over its own roles when unserved (it refuses before dialing), and
the graph-create collision probe called itself best-effort by transport
(the http GetIssue miss is storage.ErrNotFound like every other store's).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(changelog): the molecule tokens and the S16/S19 behaviours
Entries for issues.close.autoCloseMolecule and issues.advanceMolecule, the
issueops molecule entries, the auto-close inside the step's close (and a
non-policy failure of it failing the close), the real claim behind
close --continue, the molecule reads on every route, the notice and the
up-front --continue refusal against a server without the tokens, and
create --parent / mol reads over http.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(httpclient): regenerate unsupported_gen.go for MoleculeStepper
The PR adds MoleculeStepper() to storage.DoltStorage (200 -> 201
methods). httpclient implements it by hand, but the generated shell's
trailer still counted 200, so
//internal/storage/unsupportedgen:unsupportedgen_test
(TestGeneratedShellIsFresh) failed in Bazel / test and
Bazel / integration, turning CI Gate / Required red.
Regenerated with `go generate ./internal/httpclient`; the only change
is the trailer count (143 of 201 methods generated; 58 left).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(molecule): auto-close refusals, write skew, close --json, docs
Review fixes for #7513, numbered as in each iteration's review
synthesis.
Iteration 1:
F1: a close guard's refusal of the root (TemplateReadOnlyError,
PinnedError, CloseNotAssigneeError) is an auto-close refusal, like the
close policy's: the root stays open and is reported, and the step's
close stands. Pinned by the new conformance case
RunMoleculeGuardedRootKeepsTheStepClose on dolt, embedded, uow and the
served http client.
F2: two closes that finish a molecule's last two steps in concurrent
transactions each read the other's step as open, so neither closed the
root and both committed. Every auto-close now rewrites the root's
coordination cell before it decides the root (local_metadata
molecule-coordination/v1/<shard>, the dependency coordination idiom and
sharding with a FreshRowLock value), in both twins
(CloseCompletedMoleculesInTx and CloseCompletedMoleculesInUOW). Two
deciders of one root now conflict at commit (1213), and the retry reads
the winner's close and closes the root. This is the synthesis's option
(c), applied through a coordination cell instead of the root row; it
needs no post-commit second transaction and no engine lock. The
deterministic two-transaction regression fails without the touch and
passes with it on dolt and uow; the concurrent-close tests end with the
root closed in every round, reported by exactly one close.
F3: the auto-close checks the root's eligibility before walking any
step, MoleculeStepsClosed stops at the first open step, and a batch
decides each root once and reports it on the first item under it.
F4: ErrVersionMismatch on the root is not a refusal; it fails the
step's close with it. The classifier unit test pins this. A conformance
case cannot stage that race deterministically through the public roles.
F5: storage.ServesMoleculeAdvance answers (bool, error), and bd close
--continue refuses before closing anything when the handshake cannot be
read.
F6: the CHANGELOG and the stepper and batch-closer doc comments say
what the code does.
F7: the unserved-auto-close notice fires only when the close left an
auto-closing molecule with every step closed and its root open
(issueops.CompletedMolecule): again on a re-close, once per root in a
batch, never for a step under an ordinary epic or an unfinished
molecule. Proxied mol show, mol current and mol progress again report a
read unit of work that cannot be opened as itself, not as a molecule
that was not found.
F8: the write-ledger comment says the close is refused before dialing.
The dead FirstClosed/LastClosed guards in mol progress pre-exist on main
and are left as they are.
Iteration 2:
F1: on the proxied route, bd ready --mol reported a read unit
of work it could not open twice: once as itself, then as "molecule
'<id>' not found", which under --json is a second error document on
stdout. It now returns moleculeNotResolved, as mol show, mol current and
mol progress do. TestProxiedReadyMolReportsAnUnopenableReadOnce drives
runMoleculeReady with a provider whose NewUOW fails and wants one Error:
line, or one JSON document; both subtests fail with the old return.
F2: the coordination cell serializes every concurrent close of a step
under an open auto-closing root, not only the closes that finish the
molecule. That is the price of deciding the root in the step's
transaction, so it is documented (TouchMoleculeCoordinationInTx, the
UOW twin, CloseRequest.AutoCloseMolecule, the CHANGELOG) and pinned on
dolt and uow: two sibling closes with a third step still open conflict
(both commit when the touch is removed, on either twin), and a six-step
fan-out closes every step through the store's retry, with the root
closed and reported by exactly one close. The synthesis's alternative,
a post-commit recheck by any close that read a step open, is not taken:
it is a second, best-effort transaction after the step's commit, the
shape this PR exists to remove.
F3: MoleculeRootClose's doc no longer promises that a step reopened
between the completion read and the root close fails the step's close.
The guard is the root's RowVersion, which a step reopen never writes;
the doc now says what the guard covers and that this race goes
undetected (it is inherited from the CLI's old post-commit auto-close).
F4: the user docs describe the auto-close. docs/workflows/molecules.md
replaces "Closing the last child does not close the molecule root"
with which roots close and which stay open, the refusal warning, the
unserved-server note and the --json members, and documents the claiming
--continue and parent-child step membership;
docs/reference/json-schema.md gains a bd close --json section. These
are main-only behaviors on pages pinned to v1.2.2 (docs/cli-docs.pin):
a maintainer call against §1 of
engdocs/decisions/2026-07-17-docs-release-pin.md, as in #6508, #5855,
#5997 and #5092. The auto-close itself shipped in v1.2.2
(cmd/bd/close.go autoCloseCompletedMolecule), so the old sentence was
already wrong at the pin. docs/cli-reference/ is generated from the
pinned release and is not hand-edited; the bd close and bd mol show
help texts carry the same facts and reach it at the next pin bump.
F5: bd close --json reports the auto-close. The entry of a close that
completed a molecule gains auto_closed_molecule (the root it closed) or
molecule_auto_close_refusal (why the root stayed open), the HTTP API's
names, on the direct, proxied and --if-revision routes. The members sit
beside the issue's own rather than wrapping the output in an object the
way --suggest-next does: an object would change the output's shape
exactly when a close completes a molecule and break every consumer that
reads an array, while members leave each entry decoding as the closed
issue, compose with `closed` under the flag objects, and leave a plain
close's bytes unchanged. Pinned on the embedded and proxied tiers
(TestEmbeddedCloseJSONReportsMoleculeAutoClose, TestProxiedServerClose2B
json_reports_*, and both --if-revision replay tests), all red without
the change.
F6: cmd/bd's BeadsTemplateLabel is issueops.MoleculeTemplateLabel, so
the template commands and molecule membership cannot drift apart.
F7: the UOW twin's revision probe says that it writes nothing,
and the BatchCloseRequest.auto_close_molecule spec description has its
verb back (apigen regenerated, no drift).
Iteration 3:
F1: on the unit-of-work route (bd serve, the proxied CLI), a refused
root's molecule_auto_close_refusal and warning carried the use case's
and repository's wrapping ("close <id>: db:
IssueSQLRepository.CloseChecked <id>: ...") around the refusal, where
the tx twin and the docs give the refusal alone. Both twins now report
it through RefusedMoleculeAutoClose, which answers the refusing guard's
or policy's own sentence. RunMoleculeRefusedRootKeepsTheStepClose,
RunMoleculeGuardedRootKeepsTheStepClose and the embedded and proxied
close --json tests want that exact sentence; the uow conformance leg
and the proxied test fail without the unwrap.
F2: the docs no longer promise ErrVersionMismatch for a write to the
root that races its auto-close. The root's read and its revision check
share one transaction snapshot, so that write conflicts with the root
close at commit and the retry decides the root again; the close fails
only if it still conflicts when its retry budget runs out
(MoleculeRootClose, IsMoleculeAutoCloseRefusal,
CloseRequest.AutoCloseMolecule, the tx twin's comment, the CHANGELOG
and the OpenAPI description, apigen regenerated).
F3: TestEmbeddedCloseJSONReportsMoleculeAutoClose moves above
TestEmbeddedCloseConcurrent's doc comment, which documents its own test
again.
F4: bd mol progress counting direct steps while the auto-close counts
every descendant predates this PR; it is left for a follow-up.
F5: cmd/bd's molReader drops GetMoleculeProgress, which nothing called
once mol progress read through issueops.ReadMoleculeProgress.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
559b5de1e2
commit
a2d43e6792
101 changed files with 6863 additions and 1599 deletions
1
.github/scripts/embedded-cmd-test-shards.txt
vendored
1
.github/scripts/embedded-cmd-test-shards.txt
vendored
|
|
@ -214,6 +214,7 @@
|
|||
100 70 TestEmbeddedPurgeConcurrent
|
||||
100 70 TestEmbeddedRoutedMutatingSiblingAssignTagDepTag
|
||||
|
||||
100 71 TestEmbeddedCloseJSONReportsMoleculeAutoClose
|
||||
100 71 TestEmbeddedInitRoleRoutingExplicitDefault
|
||||
100 71 TestEmbeddedPrimeChangeDirRedirectNoticeFollowsTarget
|
||||
|
||||
|
|
|
|||
|
|
@ -282,6 +282,7 @@
|
|||
40 15 TestEmbeddedRelationsFiltersByAnOpenTypeVocabulary
|
||||
40 15 TestGetIssue
|
||||
40 15 TestLegacyTrackedIgnoredCursorHealsOnOpen
|
||||
40 15 TestMoleculeContract
|
||||
40 15 TestReadyWorkPageTotalFilterMatrix
|
||||
|
||||
40 16 TestDescendantWalkReachesEveryTargetKindAndStopsOnCycles
|
||||
|
|
|
|||
1
.github/scripts/proxied-cmd-test-shards.txt
vendored
1
.github/scripts/proxied-cmd-test-shards.txt
vendored
|
|
@ -78,6 +78,7 @@
|
|||
34 7 TestProxiedServerIfRevisionGuardDelete
|
||||
34 7 TestProxiedServerIfRevisionTargetGoneIsPreconditionFailed
|
||||
34 7 TestProxiedServerLabelC
|
||||
34 7 TestProxiedServerMoleculeLifecycleAgreesOnEveryRoute
|
||||
34 7 TestProxiedServerTypesAgreeWithCreate
|
||||
|
||||
34 8 TestProxiedServerClose2
|
||||
|
|
|
|||
|
|
@ -472,7 +472,13 @@ linters:
|
|||
linters:
|
||||
- forbidigo
|
||||
# Molecule reporting: each selects the members of one molecule.
|
||||
- path: '^cmd/bd/mol_(current|port|progress|ready_gated|stale)\.go$'
|
||||
#
|
||||
# `mol current` and `mol progress` LEFT this list when their in_progress
|
||||
# and hooked listings moved onto issueops.Reader.List (cmd/bd/mol_roles.go)
|
||||
# so a remote backend answers them. The proxied route's in-transaction
|
||||
# port still searches through the unit of work, and that filter lives in
|
||||
# mol_port.go beside the port.
|
||||
- path: '^cmd/bd/mol_(port|ready_gated|stale)\.go$'
|
||||
text: 'do not write a filter here'
|
||||
linters:
|
||||
- forbidigo
|
||||
|
|
|
|||
74
CHANGELOG.md
74
CHANGELOG.md
|
|
@ -206,6 +206,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
malformed `BEADS_MAX_ROWS`, which is ignored with a warning, a malformed
|
||||
cap value fails every unlimited ready or query read rather than falling
|
||||
back to the default.
|
||||
- Two molecule capability tokens on `bd serve`. `issues.close.autoCloseMolecule`
|
||||
announces that `POST /v0/beads/issues/{id}:close` and `POST
|
||||
/v0/beads/issues:batchClose` accept `auto_close_molecule` and answer
|
||||
`auto_closed_molecule` and `molecule_auto_close_refusal`;
|
||||
`issues.advanceMolecule` is the new `POST
|
||||
/v0/beads/issues/{id}:advanceMolecule`, `bd close --continue`'s advance.
|
||||
Both run the one library entry (`issueops.CloseRequest.AutoCloseMolecule`,
|
||||
`issueops.MoleculeStepper`) on the server. The public `issueops` package
|
||||
gains the molecule rules as one implementation over the BatchGetter,
|
||||
Relations and EdgeReader roles (`MoleculeRoots`, `LoadMolecule`,
|
||||
`AnalyzeMolecule`, `ViewMolecule`, `ReadMoleculeProgress`,
|
||||
`ActiveMoleculeIDs`, `CompletedMolecule`, `MoleculeRootClose`); a
|
||||
molecule's membership is the parent-child edge. Against a server that
|
||||
does not advertise a token the HTTP client refuses a library close that
|
||||
sets `AutoCloseMolecule`, or an advance, before dialing, with a typed
|
||||
capability error; it never runs a client-side copy of either rule.
|
||||
- `bd close --json` reports the molecule auto-close. The entry of a close
|
||||
that completed a molecule carries the root it closed as
|
||||
`auto_closed_molecule`, or why the root stayed open as
|
||||
`molecule_auto_close_refusal`, on every route; before, that refusal
|
||||
reached only stderr. Both members are absent from every other entry, so
|
||||
each entry still decodes as the closed issue, and the output stays an
|
||||
array (under `closed` with `--suggest-next`, `--continue` or
|
||||
`--claim-next`).
|
||||
|
||||
### Changed
|
||||
|
||||
|
|
@ -243,6 +267,43 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
migrate-personal` and the missing-id lookup fallback all read the same
|
||||
local-only answer, and none pays a settings round trip for it. Local
|
||||
backends still fall back to the database values.
|
||||
- **The molecule auto-close runs inside the step's close, and an error in
|
||||
it fails the close.** `bd close` of a molecule's last step closes the
|
||||
root in the same transaction (opt-in `AutoCloseMolecule`, so an
|
||||
orchestrator that runs its own molecule lifecycle is not doubled), and it
|
||||
replays on an idempotent re-close. The root close is unforced, so a root
|
||||
a direct close would refuse stays open and is reported while the step's
|
||||
close stands: one its close policy refuses (such as a live blocker), and
|
||||
now also one a close guard refuses (a template, a pinned root, a root
|
||||
another actor holds). Any other failure of the root close (such as a
|
||||
storage error) now fails the step's close with it, where the CLI used to
|
||||
close the root afterwards and only warn.
|
||||
Two closes that finish a molecule's last steps at the same time no
|
||||
longer leave its root open: one of them retries and closes it. The cost
|
||||
is that concurrent closes of steps under one open auto-closing root now
|
||||
serialize, whether or not either finishes the molecule: each conflict is
|
||||
retried, and a close still conflicting when its retry budget runs out
|
||||
fails with the serialization error. A batch close reports each root once,
|
||||
on the first item under it that closed.
|
||||
- **`bd close --continue` claims the next step for real.** The advance is
|
||||
the `MoleculeStepper` role on every route: the assignee is set and a step
|
||||
another agent holds is skipped, never taken (the direct and http routes
|
||||
used to flip the status only).
|
||||
- **`bd mol current`, `bd mol progress`, `bd ready --mol` and `bd mol show`
|
||||
read through the library's molecule entries on every route**, so
|
||||
membership is the parent-child edge everywhere (`bd mol show` no longer
|
||||
adds children found only by an id pattern).
|
||||
- **Against a server without the molecule tokens, `bd close` says what it
|
||||
did not do.** If the server does not advertise
|
||||
`issues.close.autoCloseMolecule` (an older `bd serve`, or one whose
|
||||
orchestrator owns the molecule lifecycle), the close goes out without the
|
||||
auto-close request. When that leaves a molecule with every step closed and
|
||||
its root open, a notice on stderr names the root, once per root in a batch
|
||||
and again on a re-close; a step under an ordinary epic or an unfinished
|
||||
molecule prints nothing. If it does not advertise
|
||||
`issues.advanceMolecule`, or the handshake that would say so fails, `bd
|
||||
close --continue` refuses before closing anything, so the step is never
|
||||
left closed with the next step unclaimed.
|
||||
- Every `bd` invocation used to start two git subprocesses before doing any
|
||||
work: `git rev-parse` to locate the repository and `git config user.name`
|
||||
to resolve the actor. On Linux the repository is now located in-process
|
||||
|
|
@ -333,9 +394,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
rebuilds the same typed errors. `bd close` prints the same lines and exits
|
||||
as before, and `bd close --if-revision`, which skipped the guards, now
|
||||
applies them too. Two paths stay outside the guards. The raw storage
|
||||
`CloseIssue`, which the molecule auto-close, a `close` line of `bd batch`
|
||||
and the other closes `cmd/bd` makes outside `bd close` use, runs neither the
|
||||
guards nor close policy on dolt, embedded or proxied; over HTTP it now sends
|
||||
`CloseIssue`, which a `close` line of `bd batch` and the other closes
|
||||
`cmd/bd` makes outside `bd close` use, runs neither the guards nor close
|
||||
policy on dolt, embedded or proxied; over HTTP it now sends
|
||||
`force`, so there it also stops applying close policy, and only a template
|
||||
refuses. A status update into the done category (`bd update -s closed`, a
|
||||
`PATCH` whose `status` is done, an `update` item of `issues:batchApply`)
|
||||
|
|
@ -457,6 +518,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
negative duration and fails, even though `--age 0s`'s own contract is
|
||||
that every wisp qualifies. `ageThreshold <= 0` now bypasses the clock
|
||||
comparison entirely (#7236).
|
||||
- `bd create --parent` works on the HTTP backend: the create role mints the
|
||||
`<parent>.<n>` child id (and inherits the parent's labels) inside the
|
||||
create on every route, instead of the CLI reserving it through a raw
|
||||
`GetNextChildID` the HTTP backend does not serve. `bd mol current` (with
|
||||
or without an id) and `bd mol progress` no longer answer empty or refuse
|
||||
over http, and `bd ready --mol` step rows carry their assignee and
|
||||
timestamps.
|
||||
- **PRs based on `hotfix/**` branches now run full CI, not just
|
||||
cross-version historical smokes and triage labeling.** `pr.yml`,
|
||||
`pr-risk.yml`, `conformance.yml`, `cross-version-smoke.yml` and
|
||||
|
|
|
|||
|
|
@ -41,6 +41,7 @@ go_library(
|
|||
"lifecycle_update_contract.go",
|
||||
"memories_contract.go",
|
||||
"metadata_cas_contract.go",
|
||||
"molecule_contract.go",
|
||||
"portable.go",
|
||||
"querier_contract.go",
|
||||
"reader_contract.go",
|
||||
|
|
|
|||
480
backend/conformance/molecule_contract.go
Normal file
480
backend/conformance/molecule_contract.go
Normal file
|
|
@ -0,0 +1,480 @@
|
|||
package conformance
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
publicops "github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// This file holds the contract for the molecule operations every backend
|
||||
// serves through one library entry each:
|
||||
//
|
||||
// - CloseRequest.AutoCloseMolecule / CloseBatchRequest.AutoCloseMolecule —
|
||||
// the close closes the molecule root it completed IN ITS OWN TRANSACTION
|
||||
// (internal/storage/issueops.CloseCompletedMoleculeInTx on the store
|
||||
// backends, uow.CloseCompletedMoleculeInUOW on the unit of work, the
|
||||
// server's own on http). Opt-in; unforced; guarded on the root revision.
|
||||
// - issueops.MoleculeStepper — the advance behind `bd close --continue`,
|
||||
// whose claim is a real claim (assignee = Actor) that never takes a step
|
||||
// another actor holds.
|
||||
//
|
||||
// THE LEAF DOC COMMENTS ARE THE SPEC (issueops/issueops.go CloseRequest,
|
||||
// issueops/batchcloser.go, issueops/moleculestepper.go, issueops/molecule.go).
|
||||
|
||||
// MoleculeFixture supplies adapter-specific storage access for the molecule
|
||||
// assertions.
|
||||
type MoleculeFixture struct {
|
||||
// IssuePrefix namespaces the ids each assertion seeds.
|
||||
IssuePrefix string
|
||||
Lifecycle publicops.Lifecycle
|
||||
BatchCloser publicops.BatchCloser
|
||||
Stepper publicops.MoleculeStepper
|
||||
// CreateIssue and CreateWisp seed one row in the issues and wisps plane.
|
||||
CreateIssue func(context.Context, *types.Issue, string) error
|
||||
CreateWisp func(context.Context, *types.Issue, string) error
|
||||
// AddDependency seeds one edge.
|
||||
AddDependency func(context.Context, *types.Dependency, string) error
|
||||
// QueryScalar runs a single-row query and scans it.
|
||||
QueryScalar func(context.Context, string, []any, ...any) error
|
||||
}
|
||||
|
||||
const moleculeActor = "molecule-contract"
|
||||
|
||||
type moleculeSeed struct {
|
||||
t *testing.T
|
||||
ctx context.Context
|
||||
fixture MoleculeFixture
|
||||
}
|
||||
|
||||
func (s moleculeSeed) issue(id string, typ types.IssueType, status types.Status, ephemeral bool, labels ...string) {
|
||||
s.t.Helper()
|
||||
issue := &types.Issue{ID: id, Title: "molecule " + id, IssueType: typ, Status: status, Priority: 2, Labels: labels, Ephemeral: ephemeral}
|
||||
if status == types.StatusClosed {
|
||||
issue.CloseReason = "seeded closed"
|
||||
}
|
||||
create := s.fixture.CreateIssue
|
||||
if ephemeral {
|
||||
create = s.fixture.CreateWisp
|
||||
}
|
||||
if err := create(s.ctx, issue, moleculeActor); err != nil {
|
||||
s.t.Fatalf("seed %s: %v", id, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s moleculeSeed) edge(from, to string, typ types.DependencyType) {
|
||||
s.t.Helper()
|
||||
if err := s.fixture.AddDependency(s.ctx, &types.Dependency{IssueID: from, DependsOnID: to, Type: typ}, moleculeActor); err != nil {
|
||||
s.t.Fatalf("seed edge %s -> %s: %v", from, to, err)
|
||||
}
|
||||
}
|
||||
|
||||
// row reads id's status and assignee from whichever plane holds it.
|
||||
func (s moleculeSeed) row(id string) (status, assignee string) {
|
||||
s.t.Helper()
|
||||
err := s.fixture.QueryScalar(s.ctx,
|
||||
`SELECT status, COALESCE(assignee, '') FROM issues WHERE id = ?
|
||||
UNION ALL SELECT status, COALESCE(assignee, '') FROM wisps WHERE id = ?`,
|
||||
[]any{id, id}, &status, &assignee)
|
||||
if err != nil {
|
||||
s.t.Fatalf("read %s: %v", id, err)
|
||||
}
|
||||
return status, assignee
|
||||
}
|
||||
|
||||
// molecule seeds root <- step1 (closed), step2 (open) and answers the ids.
|
||||
func (s moleculeSeed) molecule(name string, rootType types.IssueType, ephemeral bool, labels ...string) (root, done, last string) {
|
||||
s.t.Helper()
|
||||
root = s.fixture.IssuePrefix + "-" + name
|
||||
done, last = root+".1", root+".2"
|
||||
s.issue(root, rootType, types.StatusOpen, ephemeral, labels...)
|
||||
s.issue(done, types.TypeTask, types.StatusClosed, ephemeral)
|
||||
s.issue(last, types.TypeTask, types.StatusOpen, ephemeral)
|
||||
s.edge(done, root, types.DepParentChild)
|
||||
s.edge(last, root, types.DepParentChild)
|
||||
return root, done, last
|
||||
}
|
||||
|
||||
func (s moleculeSeed) closeStep(id string, autoClose bool) publicops.CloseResult {
|
||||
s.t.Helper()
|
||||
res, err := s.fixture.Lifecycle.Close(s.ctx, publicops.CloseRequest{
|
||||
Actor: moleculeActor, IssueID: id, Reason: "step done", Session: "molecule-session", AutoCloseMolecule: autoClose,
|
||||
})
|
||||
if err != nil {
|
||||
s.t.Fatalf("close %s: %v", id, err)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// RunMoleculeCloseAutoClosesTheCompletedRoot pins CloseRequest.AutoCloseMolecule:
|
||||
// closing the last open step closes an auto-closing root in the same call,
|
||||
// reports it, and records the auto-close reason.
|
||||
func RunMoleculeCloseAutoClosesTheCompletedRoot(t *testing.T, ctx context.Context, fixture MoleculeFixture) {
|
||||
t.Helper()
|
||||
s := moleculeSeed{t, ctx, fixture}
|
||||
for _, shape := range []struct {
|
||||
name string
|
||||
rootType types.IssueType
|
||||
labels []string
|
||||
}{
|
||||
{"poured", types.TypeMolecule, nil},
|
||||
{"template", types.TypeEpic, []string{publicops.MoleculeTemplateLabel}},
|
||||
} {
|
||||
root, _, last := s.molecule("auto-"+shape.name, shape.rootType, false, shape.labels...)
|
||||
res := s.closeStep(last, true)
|
||||
if !res.Changed || res.Issue == nil || res.Issue.Status != types.StatusClosed {
|
||||
t.Fatalf("%s: close %s = %+v, want the step closed", shape.name, last, res)
|
||||
}
|
||||
if res.AutoClosedMolecule == nil || res.AutoClosedMolecule.ID != root {
|
||||
t.Fatalf("%s: AutoClosedMolecule = %+v, want %s", shape.name, res.AutoClosedMolecule, root)
|
||||
}
|
||||
if res.MoleculeAutoCloseRefusal != "" {
|
||||
t.Errorf("%s: MoleculeAutoCloseRefusal = %q, want none", shape.name, res.MoleculeAutoCloseRefusal)
|
||||
}
|
||||
if status, _ := s.row(root); status != string(types.StatusClosed) {
|
||||
t.Errorf("%s: root %s status = %s, want closed", shape.name, root, status)
|
||||
}
|
||||
var reason string
|
||||
if err := fixture.QueryScalar(ctx, `SELECT close_reason FROM issues WHERE id = ?`, []any{root}, &reason); err != nil {
|
||||
t.Fatalf("read %s close_reason: %v", root, err)
|
||||
}
|
||||
if reason != publicops.MoleculeAutoCloseReason {
|
||||
t.Errorf("%s: root close_reason = %q, want %q", shape.name, reason, publicops.MoleculeAutoCloseReason)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// RunMoleculeAutoCloseIsOptInAndRuleBound pins the opt-in default and the
|
||||
// three roots the auto-close must leave open: one a request did not ask for,
|
||||
// an incomplete one, and an ordinary epic (explicit close-eligible work).
|
||||
func RunMoleculeAutoCloseIsOptInAndRuleBound(t *testing.T, ctx context.Context, fixture MoleculeFixture) {
|
||||
t.Helper()
|
||||
s := moleculeSeed{t, ctx, fixture}
|
||||
|
||||
root, _, last := s.molecule("optin", types.TypeMolecule, false)
|
||||
if res := s.closeStep(last, false); res.AutoClosedMolecule != nil {
|
||||
t.Errorf("close without AutoCloseMolecule reported %s auto-closed", res.AutoClosedMolecule.ID)
|
||||
}
|
||||
if status, _ := s.row(root); status != string(types.StatusOpen) {
|
||||
t.Errorf("root %s status after an un-flagged close = %s, want open", root, status)
|
||||
}
|
||||
|
||||
root, _, last = s.molecule("plain", types.TypeEpic, false)
|
||||
if res := s.closeStep(last, true); res.AutoClosedMolecule != nil {
|
||||
t.Errorf("an ordinary epic auto-closed: %s", res.AutoClosedMolecule.ID)
|
||||
}
|
||||
if status, _ := s.row(root); status != string(types.StatusOpen) {
|
||||
t.Errorf("ordinary epic %s status = %s, want open", root, status)
|
||||
}
|
||||
|
||||
root, done, last := s.molecule("incomplete", types.TypeMolecule, false)
|
||||
if res := s.closeStep(done, true); res.AutoClosedMolecule != nil {
|
||||
t.Errorf("an incomplete molecule auto-closed: %s", res.AutoClosedMolecule.ID)
|
||||
}
|
||||
if status, _ := s.row(root); status != string(types.StatusOpen) {
|
||||
t.Errorf("incomplete molecule %s status = %s, want open (%s still open)", root, status, last)
|
||||
}
|
||||
}
|
||||
|
||||
// RunMoleculeRecloseHealsAStrandedRoot pins the replay clause: an idempotent
|
||||
// re-close of the last step still closes a root left open.
|
||||
func RunMoleculeRecloseHealsAStrandedRoot(t *testing.T, ctx context.Context, fixture MoleculeFixture) {
|
||||
t.Helper()
|
||||
s := moleculeSeed{t, ctx, fixture}
|
||||
root := fixture.IssuePrefix + "-stranded"
|
||||
step := root + ".1"
|
||||
s.issue(root, types.TypeMolecule, types.StatusOpen, false)
|
||||
s.issue(step, types.TypeTask, types.StatusClosed, false)
|
||||
s.edge(step, root, types.DepParentChild)
|
||||
|
||||
res := s.closeStep(step, true)
|
||||
if res.Changed {
|
||||
t.Errorf("re-close of %s reported Changed", step)
|
||||
}
|
||||
if res.AutoClosedMolecule == nil || res.AutoClosedMolecule.ID != root {
|
||||
t.Fatalf("re-close AutoClosedMolecule = %+v, want %s healed", res.AutoClosedMolecule, root)
|
||||
}
|
||||
if status, _ := s.row(root); status != string(types.StatusClosed) {
|
||||
t.Errorf("stranded root %s status = %s, want closed", root, status)
|
||||
}
|
||||
}
|
||||
|
||||
// RunMoleculeBatchCloseAutoClosesTheRootOnce pins the batch clause: a batch
|
||||
// that closes the remaining steps closes the root once, on one outcome.
|
||||
func RunMoleculeBatchCloseAutoClosesTheRootOnce(t *testing.T, ctx context.Context, fixture MoleculeFixture) {
|
||||
t.Helper()
|
||||
s := moleculeSeed{t, ctx, fixture}
|
||||
root, _, last := s.molecule("batch", types.TypeMolecule, false)
|
||||
other := root + ".3"
|
||||
s.issue(other, types.TypeTask, types.StatusOpen, false)
|
||||
s.edge(other, root, types.DepParentChild)
|
||||
|
||||
res, err := fixture.BatchCloser.CloseBatch(ctx, publicops.CloseBatchRequest{
|
||||
Actor: moleculeActor,
|
||||
Items: []publicops.BatchCloseItem{{IssueID: last, Reason: "done"}, {IssueID: other, Reason: "done"}},
|
||||
AutoCloseMolecule: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CloseBatch: %v", err)
|
||||
}
|
||||
reported := 0
|
||||
for _, outcome := range res.Outcomes {
|
||||
if outcome.Err != nil {
|
||||
t.Fatalf("outcome %s: %v", outcome.IssueID, outcome.Err)
|
||||
}
|
||||
if outcome.AutoClosedMolecule != nil {
|
||||
reported++
|
||||
if outcome.AutoClosedMolecule.ID != root {
|
||||
t.Errorf("outcome %s auto-closed %s, want %s", outcome.IssueID, outcome.AutoClosedMolecule.ID, root)
|
||||
}
|
||||
}
|
||||
}
|
||||
if reported != 1 {
|
||||
t.Errorf("the root was reported on %d outcomes, want exactly one", reported)
|
||||
}
|
||||
if status, _ := s.row(root); status != string(types.StatusClosed) {
|
||||
t.Errorf("root %s status = %s, want closed", root, status)
|
||||
}
|
||||
}
|
||||
|
||||
// RunMoleculeRefusedRootKeepsTheStepClose pins the refusal clause: a root its
|
||||
// own close policy refuses (a live blocker) stays open and is reported in the
|
||||
// policy's own sentence, and the step close it followed stands.
|
||||
func RunMoleculeRefusedRootKeepsTheStepClose(t *testing.T, ctx context.Context, fixture MoleculeFixture) {
|
||||
t.Helper()
|
||||
s := moleculeSeed{t, ctx, fixture}
|
||||
root, _, last := s.molecule("blocked", types.TypeMolecule, false)
|
||||
blocker := root + "-blocker"
|
||||
s.issue(blocker, types.TypeTask, types.StatusOpen, false)
|
||||
s.edge(root, blocker, types.DepBlocks)
|
||||
|
||||
res := s.closeStep(last, true)
|
||||
if res.AutoClosedMolecule != nil {
|
||||
t.Errorf("a blocked root auto-closed: %s", res.AutoClosedMolecule.ID)
|
||||
}
|
||||
if want := publicops.NewCloseBlockedError(root, []string{blocker}).Error(); res.MoleculeAutoCloseRefusal != want {
|
||||
t.Errorf("MoleculeAutoCloseRefusal = %q, want the policy's own sentence %q", res.MoleculeAutoCloseRefusal, want)
|
||||
}
|
||||
if status, _ := s.row(last); status != string(types.StatusClosed) {
|
||||
t.Errorf("step %s status = %s, want closed (the refusal must not undo it)", last, status)
|
||||
}
|
||||
if status, _ := s.row(root); status != string(types.StatusOpen) {
|
||||
t.Errorf("blocked root %s status = %s, want open", root, status)
|
||||
}
|
||||
}
|
||||
|
||||
// RunMoleculeGuardedRootKeepsTheStepClose pins the guard clause: the root close
|
||||
// is unforced, so a root a direct close would refuse — assigned to someone
|
||||
// other than Actor, pinned, or a template — stays open and is reported in the
|
||||
// guard's own sentence, on a single close and on a batch, and the step's close
|
||||
// (and a batch's other items) stand.
|
||||
func RunMoleculeGuardedRootKeepsTheStepClose(t *testing.T, ctx context.Context, fixture MoleculeFixture) {
|
||||
t.Helper()
|
||||
s := moleculeSeed{t, ctx, fixture}
|
||||
for _, guard := range []struct {
|
||||
name string
|
||||
apply func(*types.Issue)
|
||||
// refusal is the guard's own error for root, whose sentence
|
||||
// MoleculeAutoCloseRefusal reports.
|
||||
refusal func(root string) error
|
||||
}{
|
||||
{"assigned", func(root *types.Issue) { root.Assignee = "someone-else" }, func(root string) error {
|
||||
return &publicops.CloseNotAssigneeError{IssueID: root, Assignee: "someone-else", Actor: moleculeActor}
|
||||
}},
|
||||
{"pinned", func(root *types.Issue) { root.Pinned = true }, func(root string) error {
|
||||
return &publicops.PinnedError{IssueID: root}
|
||||
}},
|
||||
{"template", func(root *types.Issue) { root.IsTemplate = true }, func(root string) error {
|
||||
return &publicops.TemplateReadOnlyError{IssueID: root}
|
||||
}},
|
||||
} {
|
||||
for _, batch := range []bool{false, true} {
|
||||
name := guard.name
|
||||
if batch {
|
||||
name += "-batch"
|
||||
}
|
||||
root := fixture.IssuePrefix + "-guarded-" + name
|
||||
last := root + ".2"
|
||||
rootIssue := &types.Issue{ID: root, Title: "molecule " + root, IssueType: types.TypeMolecule, Status: types.StatusOpen, Priority: 2}
|
||||
guard.apply(rootIssue)
|
||||
if err := fixture.CreateIssue(ctx, rootIssue, moleculeActor); err != nil {
|
||||
t.Fatalf("%s: seed %s: %v", name, root, err)
|
||||
}
|
||||
s.issue(root+".1", types.TypeTask, types.StatusClosed, false)
|
||||
s.issue(last, types.TypeTask, types.StatusOpen, false)
|
||||
s.edge(root+".1", root, types.DepParentChild)
|
||||
s.edge(last, root, types.DepParentChild)
|
||||
|
||||
var (
|
||||
autoClosed *publicops.Issue
|
||||
refusal string
|
||||
closed = []string{last}
|
||||
)
|
||||
if batch {
|
||||
other := root + "-other"
|
||||
s.issue(other, types.TypeTask, types.StatusOpen, false)
|
||||
closed = append(closed, other)
|
||||
res, err := fixture.BatchCloser.CloseBatch(ctx, publicops.CloseBatchRequest{
|
||||
Actor: moleculeActor,
|
||||
Items: []publicops.BatchCloseItem{{IssueID: last, Reason: "done"}, {IssueID: other, Reason: "done"}},
|
||||
AutoCloseMolecule: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("%s: CloseBatch: %v", name, err)
|
||||
}
|
||||
for _, outcome := range res.Outcomes {
|
||||
if outcome.Err != nil {
|
||||
t.Fatalf("%s: outcome %s: %v", name, outcome.IssueID, outcome.Err)
|
||||
}
|
||||
if outcome.IssueID == last {
|
||||
autoClosed, refusal = outcome.AutoClosedMolecule, outcome.MoleculeAutoCloseRefusal
|
||||
}
|
||||
}
|
||||
} else {
|
||||
res := s.closeStep(last, true)
|
||||
autoClosed, refusal = res.AutoClosedMolecule, res.MoleculeAutoCloseRefusal
|
||||
}
|
||||
|
||||
if autoClosed != nil {
|
||||
t.Errorf("%s: a guarded root auto-closed: %s", name, autoClosed.ID)
|
||||
}
|
||||
if want := guard.refusal(root).Error(); refusal != want {
|
||||
t.Errorf("%s: MoleculeAutoCloseRefusal = %q, want the guard's own sentence %q", name, refusal, want)
|
||||
}
|
||||
for _, id := range closed {
|
||||
if status, _ := s.row(id); status != string(types.StatusClosed) {
|
||||
t.Errorf("%s: %s status = %s, want closed (the refusal must not undo it)", name, id, status)
|
||||
}
|
||||
}
|
||||
if status, _ := s.row(root); status != string(types.StatusOpen) {
|
||||
t.Errorf("%s: guarded root %s status = %s, want open", name, root, status)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// RunMoleculeStepperClaimsTheNextReadyStepForTheActor pins the advance and its
|
||||
// claim: the next ready step becomes in progress AND assigned to Actor; without
|
||||
// AutoClaim nothing is written.
|
||||
func RunMoleculeStepperClaimsTheNextReadyStepForTheActor(t *testing.T, ctx context.Context, fixture MoleculeFixture) {
|
||||
t.Helper()
|
||||
s := moleculeSeed{t, ctx, fixture}
|
||||
root := fixture.IssuePrefix + "-advance"
|
||||
a, b, c := root+".1", root+".2", root+".3"
|
||||
s.issue(root, types.TypeMolecule, types.StatusOpen, false)
|
||||
s.issue(a, types.TypeTask, types.StatusClosed, false)
|
||||
s.issue(b, types.TypeTask, types.StatusOpen, false)
|
||||
s.issue(c, types.TypeTask, types.StatusOpen, false)
|
||||
for _, id := range []string{a, b, c} {
|
||||
s.edge(id, root, types.DepParentChild)
|
||||
}
|
||||
s.edge(c, b, types.DepBlocks)
|
||||
|
||||
res, err := fixture.Stepper.Advance(ctx, publicops.AdvanceRequest{Actor: moleculeActor, ClosedStepID: a})
|
||||
if err != nil {
|
||||
t.Fatalf("Advance: %v", err)
|
||||
}
|
||||
if res.MoleculeID != root || res.Claimed || res.NextStep == nil || res.NextStep.ID != b {
|
||||
t.Fatalf("Advance without a claim = %+v, want next %s in %s, unclaimed", res, b, root)
|
||||
}
|
||||
if status, assignee := s.row(b); status != string(types.StatusOpen) || assignee != "" {
|
||||
t.Errorf("%s after an unclaimed advance = %s/%q, want open and unassigned", b, status, assignee)
|
||||
}
|
||||
|
||||
res, err = fixture.Stepper.Advance(ctx, publicops.AdvanceRequest{Actor: moleculeActor, ClosedStepID: a, AutoClaim: true})
|
||||
if err != nil {
|
||||
t.Fatalf("Advance with a claim: %v", err)
|
||||
}
|
||||
if !res.Claimed || res.NextStep == nil || res.NextStep.ID != b || res.NextStep.Assignee != moleculeActor {
|
||||
t.Fatalf("Advance with a claim = %+v, want %s claimed for %s", res, b, moleculeActor)
|
||||
}
|
||||
if status, assignee := s.row(b); status != string(types.StatusInProgress) || assignee != moleculeActor {
|
||||
t.Errorf("%s after the claim = %s/%q, want in_progress assigned to %s", b, status, assignee, moleculeActor)
|
||||
}
|
||||
if status, _ := s.row(c); status != string(types.StatusOpen) {
|
||||
t.Errorf("%s (blocked) status = %s, want open", c, status)
|
||||
}
|
||||
}
|
||||
|
||||
// RunMoleculeStepperNeverTakesAStepAnotherActorHolds pins the refusal the claim
|
||||
// carries: a ready step assigned to someone else is skipped for the next one,
|
||||
// and left exactly as it was.
|
||||
func RunMoleculeStepperNeverTakesAStepAnotherActorHolds(t *testing.T, ctx context.Context, fixture MoleculeFixture) {
|
||||
t.Helper()
|
||||
s := moleculeSeed{t, ctx, fixture}
|
||||
root := fixture.IssuePrefix + "-held"
|
||||
a, held, free := root+".1", root+".2", root+".3"
|
||||
s.issue(root, types.TypeMolecule, types.StatusOpen, false)
|
||||
s.issue(a, types.TypeTask, types.StatusClosed, false)
|
||||
heldIssue := &types.Issue{ID: held, Title: "held", IssueType: types.TypeTask, Status: types.StatusOpen, Priority: 2, Assignee: "someone-else"}
|
||||
if err := fixture.CreateIssue(ctx, heldIssue, moleculeActor); err != nil {
|
||||
t.Fatalf("seed %s: %v", held, err)
|
||||
}
|
||||
s.issue(free, types.TypeTask, types.StatusOpen, false)
|
||||
for _, id := range []string{a, held, free} {
|
||||
s.edge(id, root, types.DepParentChild)
|
||||
}
|
||||
|
||||
res, err := fixture.Stepper.Advance(ctx, publicops.AdvanceRequest{Actor: moleculeActor, ClosedStepID: a, AutoClaim: true})
|
||||
if err != nil {
|
||||
t.Fatalf("Advance: %v", err)
|
||||
}
|
||||
if !res.Claimed || res.NextStep == nil || res.NextStep.ID != free {
|
||||
t.Fatalf("Advance = %+v, want %s skipped (held) and %s claimed", res, held, free)
|
||||
}
|
||||
if status, assignee := s.row(held); status != string(types.StatusOpen) || assignee != "someone-else" {
|
||||
t.Errorf("held step %s = %s/%q, want untouched (open, someone-else)", held, status, assignee)
|
||||
}
|
||||
}
|
||||
|
||||
// RunMoleculeStepperAnswersCompleteAndOutsideAMolecule pins the two answers
|
||||
// that claim nothing.
|
||||
func RunMoleculeStepperAnswersCompleteAndOutsideAMolecule(t *testing.T, ctx context.Context, fixture MoleculeFixture) {
|
||||
t.Helper()
|
||||
s := moleculeSeed{t, ctx, fixture}
|
||||
orphan := fixture.IssuePrefix + "-orphan"
|
||||
s.issue(orphan, types.TypeTask, types.StatusClosed, false)
|
||||
res, err := fixture.Stepper.Advance(ctx, publicops.AdvanceRequest{Actor: moleculeActor, ClosedStepID: orphan, AutoClaim: true})
|
||||
if err != nil {
|
||||
t.Fatalf("Advance(orphan): %v", err)
|
||||
}
|
||||
if res.MoleculeID != "" || res.NextStep != nil || res.Claimed || res.ClosedStep == nil || res.ClosedStep.ID != orphan {
|
||||
t.Errorf("Advance(orphan) = %+v, want the step and no molecule", res)
|
||||
}
|
||||
|
||||
root := fixture.IssuePrefix + "-complete"
|
||||
s.issue(root, types.TypeEpic, types.StatusOpen, false)
|
||||
s.issue(root+".1", types.TypeTask, types.StatusClosed, false)
|
||||
s.edge(root+".1", root, types.DepParentChild)
|
||||
res, err = fixture.Stepper.Advance(ctx, publicops.AdvanceRequest{Actor: moleculeActor, ClosedStepID: root + ".1", AutoClaim: true})
|
||||
if err != nil {
|
||||
t.Fatalf("Advance(complete): %v", err)
|
||||
}
|
||||
if res.MoleculeID != root || !res.Complete || res.NextStep != nil || res.Claimed {
|
||||
t.Errorf("Advance(complete) = %+v, want %s complete", res, root)
|
||||
}
|
||||
|
||||
if _, err := fixture.Stepper.Advance(ctx, publicops.AdvanceRequest{Actor: moleculeActor, ClosedStepID: fixture.IssuePrefix + "-absent"}); !errors.Is(err, publicops.ErrNotFound) {
|
||||
t.Errorf("Advance(absent) = %v, want ErrNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
// RunMoleculeStepperClaimsAWispStep pins the wisp plane: a wisp molecule's next
|
||||
// step is claimed for the actor too.
|
||||
func RunMoleculeStepperClaimsAWispStep(t *testing.T, ctx context.Context, fixture MoleculeFixture) {
|
||||
t.Helper()
|
||||
s := moleculeSeed{t, ctx, fixture}
|
||||
root, done, last := s.molecule("wisp", types.TypeMolecule, true)
|
||||
res, err := fixture.Stepper.Advance(ctx, publicops.AdvanceRequest{Actor: moleculeActor, ClosedStepID: done, AutoClaim: true})
|
||||
if err != nil {
|
||||
t.Fatalf("Advance: %v", err)
|
||||
}
|
||||
if res.MoleculeID != root || !res.Claimed || res.NextStep == nil || res.NextStep.ID != last {
|
||||
t.Fatalf("Advance over a wisp molecule = %+v, want %s claimed", res, last)
|
||||
}
|
||||
if status, assignee := s.row(last); status != string(types.StatusInProgress) || assignee != moleculeActor {
|
||||
t.Errorf("wisp step %s = %s/%q, want in_progress assigned to %s", last, status, assignee, moleculeActor)
|
||||
}
|
||||
}
|
||||
|
|
@ -32,6 +32,7 @@ go_test(
|
|||
srcs = [
|
||||
"attach_test.go",
|
||||
"e2e_cli_test.go",
|
||||
"e2e_mol_test.go",
|
||||
"e2e_remote_roles_test.go",
|
||||
"open_test.go",
|
||||
"per_open_credential_test.go",
|
||||
|
|
|
|||
6
backend/http/corpus/testdata/corpus.yaml
vendored
6
backend/http/corpus/testdata/corpus.yaml
vendored
|
|
@ -214,7 +214,6 @@ shapes:
|
|||
- id: mc-ready-mol
|
||||
source: mc skills/pr-review (bd ready --mol <root>)
|
||||
args: [ready, --mol, e2e-mol, --json]
|
||||
pending: {slice: "S16", reason: "ready --mol loads molecule steps off a raw path: step rows lose assignee and timestamps (molecule reads over roles)"}
|
||||
- id: mc-ready-parent
|
||||
source: mc skills/pr-review (bd ready --parent <root>)
|
||||
args: [ready, --parent, e2e-ep, --json]
|
||||
|
|
@ -354,20 +353,16 @@ shapes:
|
|||
- id: mc-mol-current
|
||||
source: mc worker prompts (bd mol current, ~38; inferred from in_progress work)
|
||||
args: [mol, current, --json]
|
||||
pending: {slice: "S16", reason: "mol current without an id is silently empty over http (B3 #4)"}
|
||||
- id: mc-mol-current-text
|
||||
source: mc gc-role-worker template (bd mol current, text)
|
||||
args: [mol, current]
|
||||
compare: text
|
||||
pending: {slice: "S16", reason: "mol current without an id is silently empty over http (B3 #4)"}
|
||||
- id: mc-mol-current-id
|
||||
source: mc prompts (bd mol current <id>)
|
||||
args: [mol, current, e2e-mol, --json]
|
||||
pending: {slice: "S16", reason: "mol current <id> refuses (B3 #4)"}
|
||||
- id: mc-mol-progress
|
||||
source: mc prompts (bd mol progress <id>)
|
||||
args: [mol, progress, e2e-mol, --json]
|
||||
pending: {slice: "S16", reason: "mol progress <id> refuses (B3 #4)"}
|
||||
|
||||
# ---------------------------------------------------------------- config / probes / local
|
||||
- id: gc-config-get-types
|
||||
|
|
@ -445,7 +440,6 @@ shapes:
|
|||
args: [create, --json, "gc child", -t, task, --parent, e2e-ep]
|
||||
compare: exit
|
||||
verify: [[show, --json, e2e-ep.3]]
|
||||
pending: {slice: "S19", reason: "create --parent calls GetNextChildID (B3 #8)"}
|
||||
- id: gc-create-ephemeral
|
||||
source: gc bdstore.go CreateWithStorage (--ephemeral)
|
||||
args: [create, --json, "gc wisp", -t, task, --id, e2e-wisp-n2, --ephemeral, --metadata, '{"gc.routed_to":"pool-a"}']
|
||||
|
|
|
|||
305
backend/http/e2e_mol_test.go
Normal file
305
backend/http/e2e_mol_test.go
Normal file
|
|
@ -0,0 +1,305 @@
|
|||
//go:build cgo
|
||||
|
||||
package bdhttp_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestE2E_MoleculesOverHTTP drives the molecule workflow a gc worker runs —
|
||||
// `bd create --parent`, `bd mol current`, `bd mol progress`, `bd ready --mol`,
|
||||
// `bd close --continue` and the molecule auto-close after the last step —
|
||||
// through the real `bd` binary against an in-process `bd serve` (slices S16
|
||||
// and S19).
|
||||
//
|
||||
// Every one of these used to fail or, worse, answer silently over http. Each
|
||||
// now has one library entry the server runs: the create role mints the child
|
||||
// id, the molecule view (issueops.ViewMolecule) answers the reads, the
|
||||
// close runs the auto-close in its own transaction (auto_close_molecule), and
|
||||
// `close --continue` is the advanceMolecule operation, whose claim sets the
|
||||
// assignee and never takes a step someone else holds.
|
||||
func TestE2E_MoleculesOverHTTP(t *testing.T) {
|
||||
skipUnlessEmbeddedDolt(t)
|
||||
bin := buildBD(t)
|
||||
addr := startE2EServer(t)
|
||||
workspace := t.TempDir()
|
||||
|
||||
bd := func(args ...string) bdResult {
|
||||
t.Helper()
|
||||
return runBD(t, bin, workspace, nil, append([]string{"--actor", "alice"}, args...)...)
|
||||
}
|
||||
mustBD := func(args ...string) bdResult {
|
||||
t.Helper()
|
||||
r := bd(args...)
|
||||
if r.code != 0 {
|
||||
t.Fatalf("bd %s failed (exit %d): stdout=%s stderr=%s", strings.Join(args, " "), r.code, r.stdout, r.stderr)
|
||||
}
|
||||
return r
|
||||
}
|
||||
status := func(id string) string {
|
||||
t.Helper()
|
||||
return firstJSONField(t, mustBD("show", id, "--json").stdout, "status")
|
||||
}
|
||||
|
||||
mustBD("connect", "http://"+addr, "--expect-project-id", e2eProjectID, "--json")
|
||||
|
||||
root := firstJSONField(t, mustBD("create", "Patrol molecule", "-t", "molecule", "--json").stdout, "id")
|
||||
if root == "" {
|
||||
t.Fatal("bd create (molecule root) produced no id")
|
||||
}
|
||||
|
||||
// S19: the server mints <parent>.<n>; the client no longer asks a raw
|
||||
// GetNextChildID the http backend does not serve.
|
||||
step1 := firstJSONField(t, mustBD("create", "Step one", "--parent", root, "--json").stdout, "id")
|
||||
step2 := firstJSONField(t, mustBD("create", "Step two", "--parent", root, "--json").stdout, "id")
|
||||
step3 := firstJSONField(t, mustBD("create", "Step three", "--parent", root, "--json").stdout, "id")
|
||||
if step1 != root+".1" || step2 != root+".2" || step3 != root+".3" {
|
||||
t.Fatalf("create --parent minted %q, %q and %q, want %q, %q and %q", step1, step2, step3, root+".1", root+".2", root+".3")
|
||||
}
|
||||
// An explicit --id beside --parent is still refused locally, before any mint.
|
||||
if r := bd("create", "Both", "--parent", root, "--id", root+".9", "--json"); r.code == 0 {
|
||||
t.Errorf("create --parent --id succeeded; want the existing refusal: %s", r.stdout)
|
||||
}
|
||||
|
||||
mustBD("dep", "add", step2, step1, "--json")
|
||||
mustBD("dep", "add", step3, step1, "--json")
|
||||
mustBD("update", step1, "-s", "in_progress", "-a", "alice", "--json")
|
||||
// Someone else holds step two: the advance must skip it, not take it.
|
||||
mustBD("update", step2, "-a", "bob", "--json")
|
||||
|
||||
// S16: mol current with an id is a non-empty answer whose current step is
|
||||
// the in-progress one.
|
||||
current := decodeMolecules(t, mustBD("mol", "current", root, "--json").stdout)
|
||||
if len(current) != 1 || current[0].MoleculeID != root {
|
||||
t.Fatalf("mol current %s = %+v, want the one molecule %s", root, current, root)
|
||||
}
|
||||
if current[0].CurrentStep == nil || current[0].CurrentStep.ID != step1 || current[0].Total != 3 {
|
||||
t.Fatalf("mol current %s current=%v total=%d, want current %s of 3", root, current[0].CurrentStep, current[0].Total, step1)
|
||||
}
|
||||
// The step is the FULL row: the raw dependents read over http is getIssue's
|
||||
// shallow projection, which zeroes the assignee a worker prompt reads.
|
||||
if got := current[0].CurrentStep.Assignee; got != "alice" {
|
||||
t.Errorf("mol current %s current step assignee = %q, want alice (full step row)", root, got)
|
||||
}
|
||||
|
||||
progress := mustBD("mol", "progress", root, "--json").stdout
|
||||
if n := jsonIntField(t, progress, "total"); n != 3 {
|
||||
t.Errorf("mol progress total = %d, want 3: %s", n, progress)
|
||||
}
|
||||
if id := firstJSONField(t, progress, "current_step_id"); id != step1 {
|
||||
t.Errorf("mol progress current_step_id = %q, want %q: %s", id, step1, progress)
|
||||
}
|
||||
|
||||
// mol show reads through the same library entry (issueops.LoadMolecule).
|
||||
var shown struct {
|
||||
Root struct{ ID string } `json:"root"`
|
||||
Issues []struct {
|
||||
ID string `json:"id"`
|
||||
Assignee string `json:"assignee"`
|
||||
} `json:"issues"`
|
||||
}
|
||||
showOut := mustBD("mol", "show", root, "--json").stdout
|
||||
if err := json.Unmarshal([]byte(strings.TrimSpace(showOut)), &shown); err != nil {
|
||||
t.Fatalf("parse mol show: %v\n%s", err, showOut)
|
||||
}
|
||||
if shown.Root.ID != root || len(shown.Issues) != 4 {
|
||||
t.Errorf("mol show %s = root %q with %d issues, want %s and 4 (root + 3 steps): %s", root, shown.Root.ID, len(shown.Issues), root, showOut)
|
||||
}
|
||||
|
||||
t.Run("mol current without an id", func(t *testing.T) {
|
||||
r := bd("mol", "current", "--json")
|
||||
// Whatever the backend can do, it must not answer an EMPTY list for an
|
||||
// agent with a molecule in progress: that was the swallowed refusal.
|
||||
if r.code == 0 && len(decodeMolecules(t, r.stdout)) == 0 {
|
||||
t.Fatalf("mol current (no id) answered an empty list while %s is in progress: stderr=%s", step1, r.stderr)
|
||||
}
|
||||
if r.code != 0 {
|
||||
t.Fatalf("mol current (no id) failed (exit %d): %s stdout=%s", r.code, r.stderr, r.stdout)
|
||||
}
|
||||
got := decodeMolecules(t, r.stdout)
|
||||
if len(got) != 1 || got[0].MoleculeID != root {
|
||||
t.Errorf("mol current (no id) = %+v, want molecule %s", got, root)
|
||||
}
|
||||
})
|
||||
|
||||
// ready --mol: the step rows are the full rows (the corpus mark
|
||||
// mc-ready-mol was the shallow projection dropping the assignee).
|
||||
var ready struct {
|
||||
Steps []struct {
|
||||
Issue struct {
|
||||
ID string `json:"id"`
|
||||
Assignee string `json:"assignee"`
|
||||
} `json:"issue"`
|
||||
} `json:"steps"`
|
||||
}
|
||||
readyOut := mustBD("ready", "--mol", root, "--json").stdout
|
||||
if err := json.Unmarshal([]byte(strings.TrimSpace(readyOut)), &ready); err != nil {
|
||||
t.Fatalf("parse ready --mol: %v\n%s", err, readyOut)
|
||||
}
|
||||
sawStep1 := false
|
||||
for _, step := range ready.Steps {
|
||||
if step.Issue.ID == step1 {
|
||||
sawStep1 = true
|
||||
if step.Issue.Assignee != "alice" {
|
||||
t.Errorf("ready --mol %s step %s assignee = %q, want alice (full step row)", root, step1, step.Issue.Assignee)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !sawStep1 {
|
||||
t.Errorf("ready --mol %s did not list the in-progress step %s: %s", root, step1, readyOut)
|
||||
}
|
||||
|
||||
// close --continue: step two is first in line but bob holds it, so the
|
||||
// advance claims step three for alice — a real claim, assignee set.
|
||||
cont := mustBD("close", step1, "--continue", "--json")
|
||||
var contBody struct {
|
||||
Continue struct {
|
||||
NextStep *struct{ ID string } `json:"next_step"`
|
||||
AutoAdvanced bool `json:"auto_advanced"`
|
||||
MoleculeID string `json:"molecule_id"`
|
||||
} `json:"continue"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(strings.TrimSpace(cont.stdout)), &contBody); err != nil {
|
||||
t.Fatalf("parse close --continue output: %v\n%s", err, cont.stdout)
|
||||
}
|
||||
if !contBody.Continue.AutoAdvanced || contBody.Continue.NextStep == nil || contBody.Continue.NextStep.ID != step3 ||
|
||||
contBody.Continue.MoleculeID != root {
|
||||
t.Errorf("close --continue = %s, want auto-advance to %s in %s (skipping %s, held by bob)", cont.stdout, step3, root, step2)
|
||||
}
|
||||
if got := status(step3); got != "in_progress" {
|
||||
t.Errorf("%s status after close --continue = %q, want in_progress", step3, got)
|
||||
}
|
||||
if got := firstJSONField(t, mustBD("show", step3, "--json").stdout, "assignee"); got != "alice" {
|
||||
t.Errorf("%s assignee after close --continue = %q, want alice (a claim, not a status flip)", step3, got)
|
||||
}
|
||||
if got := firstJSONField(t, mustBD("show", step2, "--json").stdout, "assignee"); got != "bob" || status(step2) != "open" {
|
||||
t.Errorf("%s after close --continue = %s/%q, want open and still bob's", step2, status(step2), got)
|
||||
}
|
||||
if got := status(root); got == "closed" {
|
||||
t.Fatalf("molecule %s closed with %s still open", root, step2)
|
||||
}
|
||||
|
||||
// Closing the last steps auto-closes the molecule root.
|
||||
mustBD("close", step3)
|
||||
if got := status(root); got == "closed" {
|
||||
t.Fatalf("molecule %s closed with %s still open", root, step2)
|
||||
}
|
||||
last := mustBD("close", step2, "--force")
|
||||
if strings.Contains(last.stderr, "could not") {
|
||||
t.Errorf("close %s warned: %s", step2, last.stderr)
|
||||
}
|
||||
if got := status(root); got != "closed" {
|
||||
t.Errorf("molecule %s status after its last step closed = %q, want closed (auto-close): stdout=%s stderr=%s",
|
||||
root, got, last.stdout, last.stderr)
|
||||
}
|
||||
}
|
||||
|
||||
type e2eMolecule struct {
|
||||
MoleculeID string `json:"molecule_id"`
|
||||
Total int `json:"total"`
|
||||
CurrentStep *struct {
|
||||
ID string `json:"id"`
|
||||
Assignee string `json:"assignee"`
|
||||
} `json:"current_step"`
|
||||
}
|
||||
|
||||
func decodeMolecules(t *testing.T, out string) []e2eMolecule {
|
||||
t.Helper()
|
||||
var got []e2eMolecule
|
||||
if err := json.Unmarshal([]byte(strings.TrimSpace(out)), &got); err != nil {
|
||||
t.Fatalf("parse mol current output: %v\n%s", err, out)
|
||||
}
|
||||
return got
|
||||
}
|
||||
|
||||
// TestE2E_MoleculeCloseAgainstAnOlderServer is `bd close` on a molecule step
|
||||
// against a server that advertises neither issues.close.autoCloseMolecule nor
|
||||
// issues.advanceMolecule (an older bd serve, or one whose orchestrator owns
|
||||
// the molecule lifecycle). Neither gap may be silent:
|
||||
//
|
||||
// - close --continue refuses BEFORE closing, so the step is not left closed
|
||||
// with the next step unclaimed;
|
||||
// - a plain close goes out without the auto-close request and names the
|
||||
// molecule it did not auto-close on stderr.
|
||||
func TestE2E_MoleculeCloseAgainstAnOlderServer(t *testing.T) {
|
||||
skipUnlessEmbeddedDolt(t)
|
||||
bin := buildBD(t)
|
||||
addr, _ := startMaskingProxy(t, startE2EServer(t), func(body map[string]any) {
|
||||
caps, _ := body["capabilities"].([]any)
|
||||
kept := caps[:0]
|
||||
for _, c := range caps {
|
||||
if c != "issues.close.autoCloseMolecule" && c != "issues.advanceMolecule" {
|
||||
kept = append(kept, c)
|
||||
}
|
||||
}
|
||||
body["capabilities"] = kept
|
||||
})
|
||||
workspace := t.TempDir()
|
||||
bd := func(args ...string) bdResult {
|
||||
t.Helper()
|
||||
return runBD(t, bin, workspace, nil, append([]string{"--actor", "alice"}, args...)...)
|
||||
}
|
||||
mustBD := func(args ...string) bdResult {
|
||||
t.Helper()
|
||||
r := bd(args...)
|
||||
if r.code != 0 {
|
||||
t.Fatalf("bd %s failed (exit %d): stdout=%s stderr=%s", strings.Join(args, " "), r.code, r.stdout, r.stderr)
|
||||
}
|
||||
return r
|
||||
}
|
||||
status := func(id string) string {
|
||||
t.Helper()
|
||||
return firstJSONField(t, mustBD("show", id, "--json").stdout, "status")
|
||||
}
|
||||
|
||||
mustBD("connect", "http://"+addr, "--expect-project-id", e2eProjectID, "--json")
|
||||
root := firstJSONField(t, mustBD("create", "Old-server molecule", "-t", "molecule", "--json").stdout, "id")
|
||||
step := firstJSONField(t, mustBD("create", "First step", "--parent", root, "--json").stdout, "id")
|
||||
last := firstJSONField(t, mustBD("create", "Last step", "--parent", root, "--json").stdout, "id")
|
||||
epic := firstJSONField(t, mustBD("create", "Ordinary epic", "-t", "epic", "--json").stdout, "id")
|
||||
child := firstJSONField(t, mustBD("create", "Only epic child", "--parent", epic, "--json").stdout, "id")
|
||||
|
||||
cont := bd("close", step, "--continue", "--json")
|
||||
if cont.code == 0 {
|
||||
t.Fatalf("close --continue succeeded against a server without issues.advanceMolecule: %s", cont.stdout)
|
||||
}
|
||||
if !strings.Contains(cont.stderr+cont.stdout, "issues.advanceMolecule") || !strings.Contains(cont.stderr+cont.stdout, "nothing was closed") {
|
||||
t.Errorf("close --continue refusal does not name the missing operation: stdout=%s stderr=%s", cont.stdout, cont.stderr)
|
||||
}
|
||||
if got := status(step); got == "closed" {
|
||||
t.Fatalf("close --continue refused but %s is closed: the refusal came after the close", step)
|
||||
}
|
||||
|
||||
// The notice is owed only where the close left an auto-closing molecule
|
||||
// complete with its root open: not for a step whose molecule still has an
|
||||
// open step, and not under an ordinary epic, which never auto-closes.
|
||||
for _, id := range []string{step, child} {
|
||||
if r := mustBD("close", id, "--json"); strings.Contains(r.stderr, "issues.close.autoCloseMolecule") {
|
||||
t.Errorf("close of %s completed no auto-closing molecule but printed the unserved auto-close notice: stderr=%s", id, r.stderr)
|
||||
}
|
||||
}
|
||||
// The close that completes the molecule names its root, and so does an
|
||||
// idempotent re-close while the root stays open.
|
||||
for _, attempt := range []string{"close", "re-close"} {
|
||||
r := mustBD("close", last, "--json")
|
||||
if !strings.Contains(r.stderr, "completed molecule "+root) || !strings.Contains(r.stderr, "issues.close.autoCloseMolecule") {
|
||||
t.Errorf("%s of %s against a server without the auto-close gave no notice naming %s: stderr=%s", attempt, last, root, r.stderr)
|
||||
}
|
||||
}
|
||||
for _, id := range []string{step, last, child} {
|
||||
if got := status(id); got != "closed" {
|
||||
t.Errorf("%s status = %q, want closed", id, got)
|
||||
}
|
||||
}
|
||||
if got := status(root); got == "closed" {
|
||||
t.Errorf("molecule %s closed although the server was not asked to auto-close it", root)
|
||||
}
|
||||
|
||||
// The root the notice names closes by hand; then nothing is owed.
|
||||
mustBD("close", root, "--json")
|
||||
if r := mustBD("close", last, "--json"); strings.Contains(r.stderr, "issues.close.autoCloseMolecule") {
|
||||
t.Errorf("re-close of %s under the closed %s printed the unserved auto-close notice: stderr=%s", last, root, r.stderr)
|
||||
}
|
||||
}
|
||||
|
|
@ -691,9 +691,18 @@ func TestE2E_AdvertisedExternalPolicyIsPassedThrough(t *testing.T) {
|
|||
t.Errorf("claimNext requests = %d, by-id claims = %d; want one atomic claim-next and no by-id claim: %v", claimNexts, byID, counter.snapshot())
|
||||
}
|
||||
f.mustRun(nil, "close", other, "--json")
|
||||
for _, p := range counter.snapshot() {
|
||||
// The close policy check is the client-side policy's last chance: it runs
|
||||
// before the close request, so only the reads up to that request count
|
||||
// here. The molecule auto-close is not a client read any more; it rides on
|
||||
// the close request itself (auto_close_molecule) and the server performs
|
||||
// it inside the close.
|
||||
paths := counter.snapshot()
|
||||
for _, p := range paths {
|
||||
if strings.HasPrefix(p, "POST /v0/beads/issues:batchClose") {
|
||||
break
|
||||
}
|
||||
if strings.HasPrefix(p, "GET /v0/beads/dependencies") {
|
||||
t.Errorf("client-side policy ran against a server advertising policy.external_dependencies: %s in %v", p, counter.snapshot())
|
||||
t.Errorf("client-side policy ran against a server advertising policy.external_dependencies: %s in %v", p, paths)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -249,6 +249,7 @@ go_library(
|
|||
"mol_progress.go",
|
||||
"mol_proxied_server.go",
|
||||
"mol_ready_gated.go",
|
||||
"mol_roles.go",
|
||||
"mol_seed.go",
|
||||
"mol_show.go",
|
||||
"mol_squash.go",
|
||||
|
|
@ -997,6 +998,7 @@ go_test(
|
|||
"mol_ready_gated_hint_test.go",
|
||||
"mol_ready_gated_proxied_integration_test.go",
|
||||
"mol_ready_gated_test.go",
|
||||
"mol_route_parity_integration_test.go",
|
||||
"mol_show_proxied_integration_test.go",
|
||||
"mol_squash_embedded_test.go",
|
||||
"mol_squash_proxied_integration_test.go",
|
||||
|
|
|
|||
192
cmd/bd/close.go
192
cmd/bd/close.go
|
|
@ -37,7 +37,16 @@ the fallback anywhere, or =0 to disable it entirely.
|
|||
When closing multiple issues, provide one --reason for all IDs or repeat
|
||||
--reason once per ID. Reasons map positionally: the first --reason applies
|
||||
to the first ID, the second --reason to the second ID, regardless of where
|
||||
the flags appear in the command line.`,
|
||||
the flags appear in the command line.
|
||||
|
||||
Closing a molecule's last open step also closes the molecule's root, with
|
||||
the reason "all steps complete", when the root is a poured molecule, a wisp,
|
||||
or an epic labeled "template"; any other epic stays open as close-eligible
|
||||
work. A root that would refuse its own close (an open blocker, a pin, another
|
||||
assignee) stays open with a warning, and the step's close stands. Under
|
||||
--json, the step's entry names the closed root (auto_closed_molecule) or the
|
||||
refusal (molecule_auto_close_refusal). --continue claims the next ready step
|
||||
in the molecule for you; add --no-auto to only show it.`,
|
||||
// Refuse a missing ID in argument validation, before root's
|
||||
// PersistentPreRunE can open the store, migrate, or auto-import
|
||||
// (bd-m00pb); see updateCmd for the full rationale.
|
||||
|
|
@ -153,6 +162,21 @@ the flags appear in the command line.`,
|
|||
postCloseStore = results[0].Store
|
||||
}
|
||||
|
||||
// --continue is a second operation after the close commits. Against a
|
||||
// server that cannot run it (no issues.advanceMolecule), or whose
|
||||
// handshake cannot be read, refuse BEFORE closing: refusing only at the
|
||||
// advance would leave the step closed and the next step unclaimed, the
|
||||
// half-done state --continue exists to avoid.
|
||||
if continueFlag {
|
||||
served, err := storage.ServesMoleculeAdvance(ctx, postCloseStore)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("--continue could not read whether the server serves issues.advanceMolecule: %v; nothing was closed", err)
|
||||
}
|
||||
if !served {
|
||||
return HandleErrorRespectJSON("--continue needs the server's issues.advanceMolecule operation, which this server does not advertise; nothing was closed (close without --continue, then claim the next step with bd update --claim)")
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
|
|
@ -165,11 +189,14 @@ the flags appear in the command line.`,
|
|||
session, force, postCloseStore, closeClaimNextRequest(claimNext, continueFlag))
|
||||
|
||||
// Report and follow up on every argument, in the order it was typed.
|
||||
closedIssues := []*types.Issue{}
|
||||
closedIssues := []closedIssueJSON{}
|
||||
closedCount := 0
|
||||
alreadyClosed := 0
|
||||
var failures []closeIDFailure
|
||||
firstSettledID := ""
|
||||
// The roots noticeUnservedMoleculeAutoClose already named, so a batch
|
||||
// that closes several steps of one molecule names it once.
|
||||
unservedRoots := map[string]bool{}
|
||||
|
||||
for i, id := range resolvedIDs {
|
||||
res := outcomes[i]
|
||||
|
|
@ -215,21 +242,9 @@ the flags appear in the command line.`,
|
|||
// Exit stays 0.
|
||||
alreadyClosed++
|
||||
|
||||
// Molecule auto-close is itself a retry-safe, fully state-derived
|
||||
// post-close contract, so it must replay on an already-closed re-close
|
||||
// just like the contracts above. If the final step's real close
|
||||
// persisted but its molecule auto-close did not (a crash between the two
|
||||
// commits, or the root CloseIssue failing with only a warning), this
|
||||
// idempotent re-close is the ONLY thing that re-drives it — otherwise the
|
||||
// molecule root is stranded open forever. autoCloseCompletedMolecule
|
||||
// early-returns unless the root is genuinely open, auto-close-eligible,
|
||||
// and complete, so it heals only that case and reintroduces none of the
|
||||
// suppressed real-close side effects (no audit, no closed→closed on the
|
||||
// step). Register the store when it actually closed the root so the
|
||||
// pending-commit sweep persists it — closedCount==0 would not commit.
|
||||
if molID := autoCloseCompletedMolecule(ctx, activeStore, id, currentActor(), session); molID != "" {
|
||||
mutatedStores[activeStore] = append(mutatedStores[activeStore], molID)
|
||||
}
|
||||
// The molecule auto-close is state-derived, so the library
|
||||
// replays it on an already-closed re-close too (healing a root a
|
||||
// crash left open); reportMoleculeAutoClose below covers both arms.
|
||||
} else {
|
||||
mutatedStores[activeStore] = append(mutatedStores[activeStore], id)
|
||||
|
||||
|
|
@ -241,12 +256,17 @@ the flags appear in the command line.`,
|
|||
audit.LogFieldChange(id, "status", oldStatus, "closed", currentActor(), reason)
|
||||
|
||||
closedCount++
|
||||
|
||||
// Auto-close parent molecule if all steps are now complete.
|
||||
// Runs against the same store the step was closed in.
|
||||
autoCloseCompletedMolecule(ctx, activeStore, id, currentActor(), session)
|
||||
}
|
||||
|
||||
// The molecule root this close completed, closed by the library in
|
||||
// the batch's own transaction. Register its store so the
|
||||
// pending-commit sweep persists it even when the step itself was
|
||||
// an already-closed no-op.
|
||||
if molID := reportMoleculeAutoClose(res.AutoClosedMolecule, res.MoleculeAutoCloseRefusal); molID != "" {
|
||||
mutatedStores[activeStore] = append(mutatedStores[activeStore], molID)
|
||||
}
|
||||
noticeUnservedMoleculeAutoClose(ctx, activeStore, id, unservedRoots)
|
||||
|
||||
// First id this command settled as closed — a real close or an
|
||||
// already-closed no-op both "touch" it. Drives the retry-safe last-touched
|
||||
// contract below so a re-close still points default-target commands at it.
|
||||
|
|
@ -266,7 +286,7 @@ the flags appear in the command line.`,
|
|||
|
||||
if jsonOutput {
|
||||
if closedIssue != nil {
|
||||
closedIssues = append(closedIssues, closedIssue)
|
||||
closedIssues = append(closedIssues, newClosedIssueJSON(closedIssue, res.AutoClosedMolecule, res.MoleculeAutoCloseRefusal))
|
||||
}
|
||||
} else {
|
||||
debug.PrintNormal("%s Closed %s: %s\n", ui.RenderPass("✓"), formatFeedbackID(id, issueTitleOrEmpty(issue)), reason)
|
||||
|
|
@ -313,11 +333,11 @@ the flags appear in the command line.`,
|
|||
|
||||
if continueFlag && len(resolvedIDs) == 1 && closedForCommand {
|
||||
autoClaim := !noAuto
|
||||
result, err := AdvanceToNextStep(ctx, newStandaloneStoreMolWriter(postCloseStore), resolvedIDs[0], autoClaim, currentActor())
|
||||
result, err := advanceMoleculeDirect(ctx, postCloseStore, resolvedIDs[0], autoClaim)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: could not advance to next step: %v\n", err)
|
||||
} else if result != nil {
|
||||
// Mirror --claim-next: when AdvanceToNextStep auto-claims the
|
||||
// Mirror --claim-next: when the molecule advance auto-claims the
|
||||
// next step, update .beads/last-touched so subsequent default-
|
||||
// target commands (e.g. bare `bd update`, `bd close`) target
|
||||
// it. Without this, last-touched stays pointed at the just-
|
||||
|
|
@ -742,74 +762,88 @@ func closeBeadGateGetter(gateStore storage.DoltStorage) issueGetter {
|
|||
return routedBeadGateGetter{localStore: gateStore}
|
||||
}
|
||||
|
||||
// autoCloseCompletedMolecule checks if closing a step completed an auto-closing
|
||||
// parent molecule, and if so, closes the molecule root. Ordinary epics remain
|
||||
// open when all children finish so they can become explicitly close-eligible
|
||||
// instead of being closed as a side effect of the final child close. It returns
|
||||
// the molecule root ID when it actually closed the root (and "" otherwise) so a
|
||||
// caller that did not otherwise mutate the store — an already-closed re-close in
|
||||
// particular — can register the store for the pending-commit sweep. The check is
|
||||
// fully state-derived and idempotent: it early-returns unless the root is open,
|
||||
// auto-close-eligible, and has all steps complete, so re-invoking it never
|
||||
// double-closes or reintroduces side effects.
|
||||
func autoCloseCompletedMolecule(ctx context.Context, s storage.DoltStorage, closedStepID, actorName, session string) string {
|
||||
moleculeID := findParentMolecule(ctx, s, closedStepID)
|
||||
if moleculeID == "" {
|
||||
return "" // Not part of a molecule
|
||||
// reportMoleculeAutoClose presents what the library's molecule auto-close did
|
||||
// for one close (issueops.CloseRequest.AutoCloseMolecule): the root it closed,
|
||||
// or why a completed root stayed open. It returns the closed root's id, or "".
|
||||
func reportMoleculeAutoClose(root *types.Issue, refusal string) string {
|
||||
if refusal != "" {
|
||||
fmt.Fprintf(os.Stderr, "Warning: could not auto-close completed molecule: %s\n", refusal)
|
||||
}
|
||||
|
||||
// Check if molecule root is already closed
|
||||
root, err := s.GetIssue(ctx, moleculeID)
|
||||
if err != nil || root == nil || root.Status == types.StatusClosed || !shouldAutoCloseCompletedRoot(root) {
|
||||
if root == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Load progress to check completion
|
||||
progress, err := getMoleculeProgress(ctx, s, moleculeID)
|
||||
if err != nil {
|
||||
return "" // Best effort — don't fail the close
|
||||
}
|
||||
|
||||
if progress.Completed < progress.Total {
|
||||
return "" // Not all steps complete yet
|
||||
}
|
||||
|
||||
// All steps complete — auto-close the molecule root
|
||||
if err := s.CloseIssue(ctx, moleculeID, "all steps complete", actorName, session); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: could not auto-close completed molecule %s: %v\n", moleculeID, err)
|
||||
return ""
|
||||
}
|
||||
|
||||
if !jsonOutput {
|
||||
debug.PrintNormal("%s Auto-closed completed molecule %s\n", ui.RenderPass("✓"), formatFeedbackID(moleculeID, root.Title))
|
||||
debug.PrintNormal("%s Auto-closed completed molecule %s\n", ui.RenderPass("✓"), formatFeedbackID(root.ID, root.Title))
|
||||
}
|
||||
return moleculeID
|
||||
return root.ID
|
||||
}
|
||||
|
||||
// shouldAutoCloseCompletedRoot returns true for molecule roots that should
|
||||
// auto-close when their final step closes. Regular epics stay open and become
|
||||
// explicit close-eligible work, while ephemeral wisps, template-driven
|
||||
// molecules, and molecule-type coordination roots keep their cleanup behavior.
|
||||
func shouldAutoCloseCompletedRoot(root *types.Issue) bool {
|
||||
if root == nil {
|
||||
return false
|
||||
}
|
||||
// closedIssueJSON is one entry of `bd close --json`'s list of closed issues:
|
||||
// the closed issue's own members, and beside them what its close did to the
|
||||
// molecule it completed (issueops.CloseResult.AutoClosedMolecule and
|
||||
// MoleculeAutoCloseRefusal, under the HTTP API's BatchCloseOutcome names).
|
||||
// Beside, not around: every entry still decodes as the issue it always was,
|
||||
// and both members are absent unless the close completed a molecule. A batch
|
||||
// reports each root once, on the first entry under it.
|
||||
type closedIssueJSON struct {
|
||||
*types.Issue
|
||||
AutoClosedMolecule *types.Issue `json:"auto_closed_molecule,omitempty"`
|
||||
MoleculeAutoCloseRefusal string `json:"molecule_auto_close_refusal,omitempty"`
|
||||
}
|
||||
|
||||
if root.IssueType == types.TypeMolecule || root.Ephemeral {
|
||||
return true
|
||||
// newClosedIssueJSON is closed's entry. The auto-closed root drops its
|
||||
// dependency records, as the closed issue does: `bd close` never prints them.
|
||||
func newClosedIssueJSON(closed, autoClosedMolecule *types.Issue, refusal string) closedIssueJSON {
|
||||
if autoClosedMolecule != nil {
|
||||
autoClosedMolecule.Dependencies = nil
|
||||
}
|
||||
return closedIssueJSON{Issue: closed, AutoClosedMolecule: autoClosedMolecule, MoleculeAutoCloseRefusal: refusal}
|
||||
}
|
||||
|
||||
if root.IssueType != types.TypeEpic {
|
||||
return false
|
||||
// noticeUnservedMoleculeAutoClose names, on stderr, the molecule a close left
|
||||
// complete but could not ask to auto-close. Against a server that does not
|
||||
// advertise issues.close.autoCloseMolecule (an older bd serve, or one whose
|
||||
// orchestrator owns the molecule lifecycle) the close goes out without the
|
||||
// request (storage.ServesMoleculeAutoClose), so a close after which
|
||||
// issueops.CompletedMolecule answers a root must say so: the root's auto-close
|
||||
// is that server's to run, never silently skipped. A step under an ordinary
|
||||
// epic, under a molecule with a step still open, or under a root already
|
||||
// closed prints nothing. An already-closed step whose molecule is complete
|
||||
// with its root open names the root again, as the served route replays its
|
||||
// auto-close. noted, when not nil, holds the roots this command already
|
||||
// named, so a batch names each once. A store that serves the auto-close prints
|
||||
// nothing.
|
||||
func noticeUnservedMoleculeAutoClose(ctx context.Context, s storage.DoltStorage, stepID string, noted map[string]bool) {
|
||||
if s == nil || storage.ServesMoleculeAutoClose(ctx, s) {
|
||||
return
|
||||
}
|
||||
|
||||
for _, label := range root.Labels {
|
||||
if label == BeadsTemplateLabel {
|
||||
return true
|
||||
}
|
||||
const token = "issues.close.autoCloseMolecule"
|
||||
reader, err := issueops.NewMoleculeReader(s)
|
||||
var root *types.Issue
|
||||
if err == nil {
|
||||
root, err = issueops.CompletedMolecule(ctx, reader, stepID)
|
||||
}
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "note: %s was closed without its molecule auto-close (the server does not advertise %s), and its molecule could not be read: %v\n", stepID, token, err)
|
||||
return
|
||||
}
|
||||
if root == nil || noted[root.ID] {
|
||||
return
|
||||
}
|
||||
if noted != nil {
|
||||
noted[root.ID] = true
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "note: closing %s completed molecule %s, which this close did not auto-close: the server does not advertise %s, so the molecule's auto-close is the server's to run (bd close %s closes it)\n", stepID, root.ID, token, root.ID)
|
||||
}
|
||||
|
||||
return false
|
||||
// advanceMoleculeDirect runs `bd close --continue` on the direct route through
|
||||
// the store's MoleculeStepper role.
|
||||
func advanceMoleculeDirect(ctx context.Context, s storage.DoltStorage, closedStepID string, autoClaim bool) (*ContinueResult, error) {
|
||||
roles, err := directMoleculeRoles(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return advanceMolecule(ctx, roles, closedStepID, autoClaim)
|
||||
}
|
||||
|
||||
// resolveReasonFile resolves the --reason-file flag for `bd close`.
|
||||
|
|
|
|||
|
|
@ -133,12 +133,18 @@ func closeDirectBatches(items []closeDirectItem) []closeDirectBatch {
|
|||
//
|
||||
// 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 {
|
||||
func closeDirectRequest(ctx context.Context, batch closeDirectBatch, session string, force bool, claimStore storage.DoltStorage, claimNext *issueops.ReadyRequest) issueops.CloseBatchRequest {
|
||||
request := issueops.CloseBatchRequest{
|
||||
Actor: currentActor(),
|
||||
Items: make([]issueops.BatchCloseItem, 0, len(batch.items)),
|
||||
Session: session,
|
||||
Force: force,
|
||||
// bd closes a molecule's root when its last step closes; the library
|
||||
// does it inside the batch's transaction. Opt-in at the library so an
|
||||
// orchestrator with its own molecule lifecycle is not doubled, and
|
||||
// asked for only where the store serves it (a remote server that does
|
||||
// not advertise it owns the molecule's auto-close).
|
||||
AutoCloseMolecule: storage.ServesMoleculeAutoClose(ctx, batch.store),
|
||||
}
|
||||
if claimNext != nil && batch.store == claimStore {
|
||||
request.ClaimNext = claimNext
|
||||
|
|
@ -164,7 +170,7 @@ func closeDirectRun(ctx context.Context, batches []closeDirectBatch, argCount in
|
|||
var claimed *types.IssueWithCounts
|
||||
|
||||
for _, batch := range batches {
|
||||
result, err := closeDirectCloseBatch(ctx, batch.store, closeDirectRequest(batch, session, force, claimStore, claimNext))
|
||||
result, err := closeDirectCloseBatch(ctx, batch.store, closeDirectRequest(ctx, batch, session, force, claimStore, claimNext))
|
||||
if err != nil {
|
||||
for _, item := range batch.items {
|
||||
refused := issueops.CloseOutcome{IssueID: item.id, Err: err}
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ import (
|
|||
"github.com/steveyegge/beads/internal/configfile"
|
||||
"github.com/steveyegge/beads/internal/storage/embeddeddolt"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// ===== Close-specific test helpers =====
|
||||
|
|
@ -56,6 +57,80 @@ func bdDepAdd(t *testing.T, bd, dir string, args ...string) {
|
|||
}
|
||||
}
|
||||
|
||||
// closeJSONEntry is one entry of `bd close --json`, decoded as a consumer that
|
||||
// knows the molecule auto-close members does: the closed issue's own members
|
||||
// at the top level, with the members beside them.
|
||||
type closeJSONEntry struct {
|
||||
types.Issue
|
||||
AutoClosedMolecule *types.Issue `json:"auto_closed_molecule"`
|
||||
MoleculeAutoCloseRefusal *string `json:"molecule_auto_close_refusal"`
|
||||
}
|
||||
|
||||
// decodeCloseJSON decodes the array of closed issues `bd close --json` prints
|
||||
// on stdout, and requires one entry per id in ids, in order, each closed.
|
||||
func decodeCloseJSON(t *testing.T, stdout string, ids []string) []closeJSONEntry {
|
||||
t.Helper()
|
||||
start := strings.Index(stdout, "[")
|
||||
if start < 0 {
|
||||
t.Fatalf("no JSON array in bd close --json output:\n%s", stdout)
|
||||
}
|
||||
var entries []closeJSONEntry
|
||||
if err := json.Unmarshal([]byte(stdout[start:]), &entries); err != nil {
|
||||
t.Fatalf("parse bd close --json: %v\n%s", err, stdout[start:])
|
||||
}
|
||||
if len(entries) != len(ids) {
|
||||
t.Fatalf("bd close --json has %d entries, want %d (%v):\n%s", len(entries), len(ids), ids, stdout[start:])
|
||||
}
|
||||
for i, entry := range entries {
|
||||
if entry.ID != ids[i] || entry.Status != types.StatusClosed {
|
||||
t.Fatalf("entry %d = %s (%s), want %s closed:\n%s", i, entry.ID, entry.Status, ids[i], stdout[start:])
|
||||
}
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
// requireCloseJSONReportsAutoClosedMolecule asserts a `bd close --json` of
|
||||
// stepIDs, in order, whose close completed the molecule rootID: the first
|
||||
// entry carries the closed root as auto_closed_molecule, and no entry carries
|
||||
// the root again or a refusal.
|
||||
func requireCloseJSONReportsAutoClosedMolecule(t *testing.T, stdout string, stepIDs []string, rootID string) {
|
||||
t.Helper()
|
||||
entries := decodeCloseJSON(t, stdout, stepIDs)
|
||||
root := entries[0].AutoClosedMolecule
|
||||
if root == nil {
|
||||
t.Fatalf("the close that completed molecule %s does not report it as auto_closed_molecule:\n%s", rootID, stdout)
|
||||
}
|
||||
if root.ID != rootID || root.Status != types.StatusClosed || root.CloseReason != "all steps complete" {
|
||||
t.Errorf("auto_closed_molecule = %s (%s, %q), want %s closed with %q", root.ID, root.Status, root.CloseReason, rootID, "all steps complete")
|
||||
}
|
||||
for i, entry := range entries {
|
||||
if i > 0 && entry.AutoClosedMolecule != nil {
|
||||
t.Errorf("entry %d (%s) reports molecule %s again: a batch reports each root once", i, entry.ID, entry.AutoClosedMolecule.ID)
|
||||
}
|
||||
if entry.MoleculeAutoCloseRefusal != nil {
|
||||
t.Errorf("entry %d (%s) reports a refusal for a root that closed: %q", i, entry.ID, *entry.MoleculeAutoCloseRefusal)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// requireCloseJSONReportsMoleculeRefusal asserts a `bd close --json` of
|
||||
// stepID whose close completed the molecule rootID but could not close it:
|
||||
// the entry carries no auto-closed root and reports the refusal as want, the
|
||||
// refusing guard's own sentence, on every route.
|
||||
func requireCloseJSONReportsMoleculeRefusal(t *testing.T, stdout, stepID, rootID string, want error) {
|
||||
t.Helper()
|
||||
entry := decodeCloseJSON(t, stdout, []string{stepID})[0]
|
||||
if entry.AutoClosedMolecule != nil {
|
||||
t.Errorf("a refused root is reported as auto-closed: %s", entry.AutoClosedMolecule.ID)
|
||||
}
|
||||
if entry.MoleculeAutoCloseRefusal == nil {
|
||||
t.Fatalf("the close that completed molecule %s does not report why its root stayed open:\n%s", rootID, stdout)
|
||||
}
|
||||
if got := *entry.MoleculeAutoCloseRefusal; got != want.Error() {
|
||||
t.Errorf("molecule_auto_close_refusal for %s:\n got %q\nwant %q", rootID, got, want.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// ===== Close tests =====
|
||||
|
||||
// The TestEmbeddedCloseBasic*, TestEmbeddedCloseGuardsAndEpics and
|
||||
|
|
@ -648,6 +723,44 @@ func TestEmbeddedCloseAlreadyClosedClaimNextAndMolecule(t *testing.T) {
|
|||
|
||||
}
|
||||
|
||||
// TestEmbeddedCloseJSONReportsMoleculeAutoClose pins what `bd close --json`
|
||||
// says about the molecule a close completed, on the direct route: the root it
|
||||
// closed, once per batch, or why the root stayed open.
|
||||
// TestProxiedServerClose2B's json_reports_* subtests are its proxied twins.
|
||||
func TestEmbeddedCloseJSONReportsMoleculeAutoClose(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)
|
||||
|
||||
t.Run("auto_closed_root_reported_once_per_batch", func(t *testing.T) {
|
||||
dir, _, _ := bdInit(t, bd, "--prefix", "jm")
|
||||
root := bdCreate(t, bd, dir, "JSON molecule root", "--type", "epic", "--labels", "template")
|
||||
step1 := bdCreate(t, bd, dir, "JSON molecule step one", "--type", "task", "--parent", root.ID)
|
||||
step2 := bdCreate(t, bd, dir, "JSON molecule step two", "--type", "task", "--parent", root.ID)
|
||||
step3 := bdCreate(t, bd, dir, "JSON molecule step three", "--type", "task", "--parent", root.ID)
|
||||
bdClose(t, bd, dir, step1.ID)
|
||||
|
||||
out := bdClose(t, bd, dir, "--json", step2.ID, step3.ID)
|
||||
requireCloseJSONReportsAutoClosedMolecule(t, out, []string{step2.ID, step3.ID}, root.ID)
|
||||
})
|
||||
|
||||
t.Run("refused_root_reported", func(t *testing.T) {
|
||||
dir, _, _ := bdInit(t, bd, "--prefix", "jr")
|
||||
root := bdCreate(t, bd, dir, "JSON held molecule root", "--type", "epic", "--labels", "template", "--assignee", "someone-else")
|
||||
step := bdCreate(t, bd, dir, "JSON held molecule step", "--type", "task", "--parent", root.ID)
|
||||
|
||||
out := bdClose(t, bd, dir, "--actor", "json-closer", "--json", step.ID)
|
||||
requireCloseJSONReportsMoleculeRefusal(t, out, step.ID, root.ID,
|
||||
&issueops.CloseNotAssigneeError{IssueID: root.ID, Assignee: "someone-else", Actor: "json-closer"})
|
||||
if got := bdShow(t, bd, dir, root.ID); got.Status != types.StatusOpen {
|
||||
t.Errorf("a root assigned to another actor must stay open, got %s", got.Status)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestEmbeddedCloseConcurrent exercises create, close, and list operations
|
||||
// concurrently to verify EmbeddedDoltStore handles concurrent CLI invocations
|
||||
// without panics, data corruption, or deadlocks.
|
||||
|
|
|
|||
|
|
@ -8,8 +8,7 @@ import (
|
|||
|
||||
"github.com/steveyegge/beads/internal/audit"
|
||||
"github.com/steveyegge/beads/internal/debug"
|
||||
"github.com/steveyegge/beads/internal/storage/uow"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/ui"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
|
@ -61,6 +60,10 @@ func runCloseDirectIfRevision(ctx context.Context, id, reason string, force bool
|
|||
Session: session,
|
||||
Force: force,
|
||||
ExpectedVersion: &expectedVersion,
|
||||
// The library closes the molecule root this close completes, in the
|
||||
// same transaction — and replays it on an idempotent re-close — where
|
||||
// the store serves it (storage.ServesMoleculeAutoClose).
|
||||
AutoCloseMolecule: storage.ServesMoleculeAutoClose(ctx, result.Store),
|
||||
})
|
||||
if closeErr != nil {
|
||||
if reported, ok := reportIfRevisionFailure("closing", id, closeErr, &expectedVersion); ok {
|
||||
|
|
@ -77,16 +80,11 @@ func runCloseDirectIfRevision(ctx context.Context, id, reason string, force bool
|
|||
fmt.Fprintf(os.Stderr, "warning: closing %s with %d open child issue(s) still active\n", result.ResolvedID, closeResult.OpenChildren)
|
||||
}
|
||||
|
||||
// Molecule auto-close is a retry-safe, fully state-derived post-close
|
||||
// contract (close.go's autoCloseCompletedMolecule doc), so it must replay
|
||||
// here exactly as it does on the batch route — on a real close AND on an
|
||||
// idempotent re-close, since the guarded route bypasses BatchCloser
|
||||
// entirely (mc-zndi7.75) and would otherwise leave a molecule's root
|
||||
// stranded open forever.
|
||||
mutatedIDs := []string{result.ResolvedID}
|
||||
if molID := autoCloseCompletedMolecule(ctx, result.Store, result.ResolvedID, currentActor(), session); molID != "" {
|
||||
if molID := reportMoleculeAutoClose(closeResult.AutoClosedMolecule, closeResult.MoleculeAutoCloseRefusal); molID != "" {
|
||||
mutatedIDs = append(mutatedIDs, molID)
|
||||
}
|
||||
noticeUnservedMoleculeAutoClose(ctx, result.Store, result.ResolvedID, nil)
|
||||
|
||||
if err := commitPendingIfEmbedded(ctx, result.Store, currentActor(), doltAutoCommitParams{
|
||||
Command: "close",
|
||||
|
|
@ -121,12 +119,13 @@ func runCloseProxiedIfRevision(ctx context.Context, id, reason string, force boo
|
|||
}
|
||||
|
||||
closeResult, closeErr := ops.Close(ctx, issueops.CloseRequest{
|
||||
Actor: currentActor(),
|
||||
IssueID: id,
|
||||
Reason: reason,
|
||||
Session: session,
|
||||
Force: force,
|
||||
ExpectedVersion: &expectedVersion,
|
||||
Actor: currentActor(),
|
||||
IssueID: id,
|
||||
Reason: reason,
|
||||
Session: session,
|
||||
Force: force,
|
||||
ExpectedVersion: &expectedVersion,
|
||||
AutoCloseMolecule: true,
|
||||
})
|
||||
if closeErr != nil {
|
||||
if errors.Is(closeErr, context.Canceled) || errors.Is(closeErr, context.DeadlineExceeded) {
|
||||
|
|
@ -146,48 +145,13 @@ func runCloseProxiedIfRevision(ctx context.Context, id, reason string, force boo
|
|||
fmt.Fprintf(os.Stderr, "warning: closing %s with %d open child issue(s) still active\n", id, closeResult.OpenChildren)
|
||||
}
|
||||
|
||||
// Molecule auto-close is a retry-safe, fully state-derived post-close
|
||||
// contract, so it must replay here too — on a real close AND on an
|
||||
// idempotent re-close — exactly as closeProxiedRunPostClose drives it for
|
||||
// the batch route (mc-zndi7.75).
|
||||
runCloseIfRevisionProxiedPostClose(ctx, id, session)
|
||||
reportMoleculeAutoClose(closeResult.AutoClosedMolecule, closeResult.MoleculeAutoCloseRefusal)
|
||||
|
||||
SetLastTouchedID(id)
|
||||
reportClosedIfRevisionResult(id, reason, preCloseStatus, closeResult)
|
||||
return nil
|
||||
}
|
||||
|
||||
// runCloseIfRevisionProxiedPostClose re-drives molecule auto-close after a
|
||||
// guarded proxied close, in its own unit of work exactly as
|
||||
// closeProxiedRunPostClose runs it for the batch route: outside the close's
|
||||
// own transaction, because it is outside that transaction's contract. A
|
||||
// failure here is reported and swallowed — best effort, matching
|
||||
// autoCloseCompletedMolecule's direct-route twin — so a molecule-healing
|
||||
// hiccup never turns an otherwise-successful guarded close into a failure.
|
||||
func runCloseIfRevisionProxiedPostClose(ctx context.Context, id, session string) {
|
||||
if uowProvider == nil {
|
||||
return
|
||||
}
|
||||
autoClosedMol, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (*types.Issue, string, error) {
|
||||
var warnings []string
|
||||
mol := autoCloseProxiedCompletedMolecule(ctx, uw, id, currentActor(), session, &warnings)
|
||||
for _, w := range warnings {
|
||||
fmt.Fprintf(os.Stderr, "Warning: %s\n", w)
|
||||
}
|
||||
if mol == nil {
|
||||
return nil, "", nil
|
||||
}
|
||||
return mol, "bd: auto-close " + mol.ID, nil
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: post-close work failed: %v\n", err)
|
||||
return
|
||||
}
|
||||
if autoClosedMol != nil && !jsonOutput {
|
||||
debug.PrintNormal("%s Auto-closed completed molecule %s\n", ui.RenderPass("✓"), formatFeedbackID(autoClosedMol.ID, autoClosedMol.Title))
|
||||
}
|
||||
}
|
||||
|
||||
// reportClosedIfRevisionResult is the one-id success report shared by both
|
||||
// --if-revision close routes: the audit entry (suppressed for an idempotent
|
||||
// re-close, matching close.go's batch behavior) and the human/--json output.
|
||||
|
|
@ -218,7 +182,7 @@ func reportClosedIfRevisionResult(id, reason, preCloseStatus string, closeResult
|
|||
}
|
||||
if jsonOutput {
|
||||
if closedIssue != nil {
|
||||
_ = outputJSON([]*types.Issue{closedIssue})
|
||||
_ = outputJSON([]closedIssueJSON{newClosedIssueJSON(closedIssue, closeResult.AutoClosedMolecule, closeResult.MoleculeAutoCloseRefusal)})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
|
|
|||
|
|
@ -48,9 +48,11 @@ func TestIfRevisionCloseReplaysMoleculeAutoClose(t *testing.T) {
|
|||
|
||||
// Re-close the already-closed final step, this time GUARDED. The idempotent
|
||||
// guarded re-close must replay molecule auto-close and heal the
|
||||
// stranded-open root exactly as the unguarded path does.
|
||||
// stranded-open root exactly as the unguarded path does, and its --json
|
||||
// report names the root it closed.
|
||||
rev := bdShowRevision(t, bd, dir, step2.ID)
|
||||
bdRunOK(t, bd, dir, "close", step2.ID, "--if-revision", revStr(rev), "--reason", "retry")
|
||||
out := bdClose(t, bd, dir, step2.ID, "--if-revision", revStr(rev), "--reason", "retry", "--json")
|
||||
requireCloseJSONReportsAutoClosedMolecule(t, out, []string{step2.ID}, root.ID)
|
||||
|
||||
if got := bdShow(t, bd, dir, root.ID); got.Status != types.StatusClosed {
|
||||
t.Errorf("expected stranded-open molecule root %s healed by a guarded re-close of the final step, got %s",
|
||||
|
|
|
|||
|
|
@ -40,9 +40,11 @@ func TestProxiedServerIfRevisionCloseReplaysMoleculeAutoClose(t *testing.T) {
|
|||
|
||||
// Re-close the already-closed final step, this time GUARDED. The
|
||||
// idempotent guarded re-close must replay molecule auto-close and heal
|
||||
// the stranded-open root exactly as the unguarded path does.
|
||||
// the stranded-open root exactly as the unguarded path does, and its
|
||||
// --json report names the root it closed.
|
||||
rev := bdProxiedShowRevision(t, bd, p.dir, step2.ID)
|
||||
bdProxiedClose(t, bd, p.dir, step2.ID, "--if-revision", proxiedRevStr(rev), "--reason", "retry")
|
||||
out := bdProxiedClose(t, bd, p.dir, step2.ID, "--if-revision", proxiedRevStr(rev), "--reason", "retry", "--json")
|
||||
requireCloseJSONReportsAutoClosedMolecule(t, out, []string{step2.ID}, root.ID)
|
||||
|
||||
if got := readStatus(t, db, root.ID); got != types.StatusClosed {
|
||||
t.Errorf("expected stranded-open molecule root %s healed by a guarded proxied re-close of the final step, got %q",
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
func bdProxiedClose(t *testing.T, bd, dir string, args ...string) string {
|
||||
|
|
@ -914,6 +915,31 @@ func TestProxiedServerClose2B(t *testing.T) {
|
|||
}
|
||||
})
|
||||
|
||||
t.Run("json_reports_auto_closed_molecule", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
p := newSharedProxiedProject(t, bd, "jacm")
|
||||
root := bdProxiedCreate(t, bd, p.dir, "Molecule root", "-t", "epic", "--labels", "template")
|
||||
s1 := bdProxiedCreate(t, bd, p.dir, "Step 1", "--parent", root.ID)
|
||||
s2 := bdProxiedCreate(t, bd, p.dir, "Step 2", "--parent", root.ID)
|
||||
s3 := bdProxiedCreate(t, bd, p.dir, "Step 3", "--parent", root.ID)
|
||||
bdProxiedClose(t, bd, p.dir, s1.ID)
|
||||
out := bdProxiedClose(t, bd, p.dir, "--json", s2.ID, s3.ID)
|
||||
requireCloseJSONReportsAutoClosedMolecule(t, out, []string{s2.ID, s3.ID}, root.ID)
|
||||
})
|
||||
|
||||
t.Run("json_reports_molecule_auto_close_refusal", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
p := newSharedProxiedProject(t, bd, "jmar")
|
||||
root := bdProxiedCreate(t, bd, p.dir, "Molecule root", "-t", "epic", "--labels", "template", "--assignee", "someone-else")
|
||||
s1 := bdProxiedCreate(t, bd, p.dir, "Step 1", "--parent", root.ID)
|
||||
out := bdProxiedClose(t, bd, p.dir, "--actor", "json-closer", "--json", s1.ID)
|
||||
requireCloseJSONReportsMoleculeRefusal(t, out, s1.ID, root.ID,
|
||||
&issueops.CloseNotAssigneeError{IssueID: root.ID, Assignee: "someone-else", Actor: "json-closer"})
|
||||
if got := readStatus(t, openProxiedDB(t, p), root.ID); got != types.StatusOpen {
|
||||
t.Errorf("a root assigned to another actor must stay open, got %q", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("hooks_fire_on_close", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
marker := filepath.Join(t.TempDir(), "on_close_marker")
|
||||
|
|
|
|||
|
|
@ -5,13 +5,11 @@ import (
|
|||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/steveyegge/beads/internal/audit"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
storeissueops "github.com/steveyegge/beads/internal/storage/issueops"
|
||||
"github.com/steveyegge/beads/internal/storage/uow"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
|
|
@ -65,14 +63,18 @@ type closeProxiedOutcome struct {
|
|||
closed bool
|
||||
auditOld string
|
||||
auditReason string
|
||||
// autoClosedMol and autoCloseRefusal are what the library's molecule
|
||||
// auto-close did inside the batch's transaction for this item.
|
||||
autoClosedMol *types.Issue
|
||||
autoCloseRefusal string
|
||||
}
|
||||
|
||||
// closeProxiedPostClose is the work `bd close` does AFTER the closes have
|
||||
// landed: molecule auto-close, --suggest-next and --continue.
|
||||
// landed: --suggest-next and --continue. (The molecule auto-close is not here:
|
||||
// the library runs it inside the batch's transaction.)
|
||||
type closeProxiedPostClose struct {
|
||||
unblocked []*types.Issue
|
||||
continueResult *ContinueResult
|
||||
autoClosedMol *types.Issue
|
||||
warnings []string
|
||||
}
|
||||
|
||||
|
|
@ -146,6 +148,9 @@ func runCloseProxiedServer(cmd *cobra.Command, ctx context.Context, args []strin
|
|||
Session: in.session,
|
||||
Force: in.force,
|
||||
ClaimNext: closeClaimNextRequest(in.claimNext, in.continueOn),
|
||||
// The library closes a molecule root its last step's close
|
||||
// completes, inside this batch's transaction.
|
||||
AutoCloseMolecule: true,
|
||||
})
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
|
|
@ -179,9 +184,17 @@ func runCloseProxiedServer(cmd *cobra.Command, ctx context.Context, args []strin
|
|||
claimedNextIssue = result.ClaimedNext.Issue
|
||||
}
|
||||
|
||||
for _, o := range outcomes {
|
||||
if o.autoCloseRefusal != "" {
|
||||
fmt.Fprintf(os.Stderr, "Warning: could not auto-close completed molecule: %s\n", o.autoCloseRefusal)
|
||||
}
|
||||
}
|
||||
|
||||
if !in.jsonOut {
|
||||
if post.autoClosedMol != nil {
|
||||
fmt.Printf("%s Auto-closed completed molecule %s\n", ui.RenderPass("✓"), formatFeedbackID(post.autoClosedMol.ID, post.autoClosedMol.Title))
|
||||
for _, o := range outcomes {
|
||||
if o.autoClosedMol != nil {
|
||||
fmt.Printf("%s Auto-closed completed molecule %s\n", ui.RenderPass("✓"), formatFeedbackID(o.autoClosedMol.ID, o.autoClosedMol.Title))
|
||||
}
|
||||
}
|
||||
if len(post.unblocked) > 0 {
|
||||
fmt.Printf("\nNewly unblocked:\n")
|
||||
|
|
@ -200,9 +213,9 @@ func runCloseProxiedServer(cmd *cobra.Command, ctx context.Context, args []strin
|
|||
}
|
||||
|
||||
if in.jsonOut && len(outcomes) > 0 {
|
||||
closedIssues := make([]*types.Issue, len(outcomes))
|
||||
closedIssues := make([]closedIssueJSON, len(outcomes))
|
||||
for i, o := range outcomes {
|
||||
closedIssues[i] = o.after
|
||||
closedIssues[i] = newClosedIssueJSON(o.after, o.autoClosedMol, o.autoCloseRefusal)
|
||||
}
|
||||
switch {
|
||||
case len(post.unblocked) > 0:
|
||||
|
|
@ -352,12 +365,14 @@ func closeProxiedOutcomes(pre *closeProxiedPreflight, result issueops.CloseBatch
|
|||
after.Dependencies = nil
|
||||
}
|
||||
outcomes = append(outcomes, closeProxiedOutcome{
|
||||
id: item.IssueID,
|
||||
before: before,
|
||||
after: after,
|
||||
closed: outcome.Changed,
|
||||
auditOld: oldStatus,
|
||||
auditReason: item.Reason,
|
||||
id: item.IssueID,
|
||||
before: before,
|
||||
after: after,
|
||||
closed: outcome.Changed,
|
||||
auditOld: oldStatus,
|
||||
auditReason: item.Reason,
|
||||
autoClosedMol: outcome.AutoClosedMolecule,
|
||||
autoCloseRefusal: outcome.MoleculeAutoCloseRefusal,
|
||||
})
|
||||
reasons = append(reasons, item.Reason)
|
||||
}
|
||||
|
|
@ -469,61 +484,38 @@ func closeProxiedRefusal(id string, err error) string {
|
|||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
// closeProxiedRunPostClose runs --suggest-next and --continue once the closes
|
||||
// have committed. --suggest-next is a read in a unit of work of its own;
|
||||
// --continue is the provider's MoleculeStepper role, which claims in its own
|
||||
// transaction exactly as the direct route's does.
|
||||
func closeProxiedRunPostClose(ctx context.Context, args []string, in closeProxiedInput, outcomes []closeProxiedOutcome) closeProxiedPostClose {
|
||||
var out closeProxiedPostClose
|
||||
if len(outcomes) == 0 {
|
||||
return closeProxiedPostClose{}
|
||||
return out
|
||||
}
|
||||
|
||||
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, currentActor(), in.session, &out.warnings)
|
||||
if mol != nil {
|
||||
out.autoClosedMol = mol
|
||||
wrote = append(wrote, "auto-close "+mol.ID)
|
||||
}
|
||||
}
|
||||
|
||||
if in.suggestNext && len(args) == 1 {
|
||||
if in.suggestNext && len(args) == 1 {
|
||||
_, err := uow.RunTxRead(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (struct{}, error) {
|
||||
unblocked, warn := closeProxiedSuggestNext(ctx, uw, args[0])
|
||||
out.unblocked = unblocked
|
||||
if warn != "" {
|
||||
out.warnings = append(out.warnings, warn)
|
||||
}
|
||||
return struct{}{}, nil
|
||||
})
|
||||
if err != nil {
|
||||
out.warnings = append(out.warnings, fmt.Sprintf("post-close work failed: %v", err))
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
if in.continueOn && len(args) == 1 {
|
||||
cont, warn := closeProxiedContinue(ctx, args[0], !in.noAuto)
|
||||
out.continueResult = cont
|
||||
if warn != "" {
|
||||
out.warnings = append(out.warnings, warn)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func closeProxiedSuggestNext(ctx context.Context, uw uow.UnitOfWork, closedID string) ([]*types.Issue, string) {
|
||||
|
|
@ -534,52 +526,14 @@ func closeProxiedSuggestNext(ctx context.Context, uw uow.UnitOfWork, closedID st
|
|||
return unblocked, ""
|
||||
}
|
||||
|
||||
func closeProxiedContinue(ctx context.Context, uw uow.UnitOfWork, closedID string, autoClaim bool) (*ContinueResult, string) {
|
||||
result, err := AdvanceToNextStep(ctx, newUOWMolWriter(uw), closedID, autoClaim, currentActor())
|
||||
func closeProxiedContinue(ctx context.Context, closedID string, autoClaim bool) (*ContinueResult, string) {
|
||||
roles, err := proxiedMoleculeRoles()
|
||||
if err != nil {
|
||||
return nil, fmt.Sprintf("could not advance to next step: %v", err)
|
||||
}
|
||||
result, err := advanceMolecule(ctx, roles, closedID, autoClaim)
|
||||
if err != nil {
|
||||
return nil, fmt.Sprintf("could not advance to next step: %v", err)
|
||||
}
|
||||
return result, ""
|
||||
}
|
||||
|
||||
func autoCloseProxiedCompletedMolecule(ctx context.Context, uw uow.UnitOfWork, closedStepID string, actorName, session string, warnings *[]string) *types.Issue {
|
||||
moleculeID := proxiedFindParentMolecule(ctx, uw, closedStepID)
|
||||
if moleculeID == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
root, err := uw.IssueUseCase().GetIssue(ctx, moleculeID)
|
||||
if err != nil || root == nil || root.Status == types.StatusClosed {
|
||||
return nil
|
||||
}
|
||||
// A READ, and one that has to see this transaction. The auto-close decision
|
||||
// is made from labels written earlier in the same unit of work, and
|
||||
// issueops.Reader opens a transaction of its own, so it would answer from
|
||||
// the last committed state instead. The follow-up is a reader role bound to
|
||||
// a caller's transaction; until one exists this stays (ga-2ltro.12).
|
||||
if labels, err := uw.LabelUseCase().GetLabels(ctx, moleculeID); err == nil { //nolint:forbidigo // in-transaction read; issueops.Reader would open its own
|
||||
root.Labels = labels
|
||||
}
|
||||
if !shouldAutoCloseCompletedRoot(root) {
|
||||
return nil
|
||||
}
|
||||
|
||||
progress, err := getMoleculeProgress(ctx, uowMolReader{uw: uw}, moleculeID)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
if progress.Completed < progress.Total {
|
||||
return nil
|
||||
}
|
||||
|
||||
params := domain.CloseIssueParams{Reason: "all steps complete", Session: session}
|
||||
if _, err := uw.IssueUseCase().CloseIssue(ctx, moleculeID, params, actorName); err != nil {
|
||||
*warnings = append(*warnings, fmt.Sprintf("could not auto-close completed molecule %s: %v", moleculeID, err))
|
||||
return nil
|
||||
}
|
||||
return root
|
||||
}
|
||||
|
||||
func proxiedFindParentMolecule(ctx context.Context, uw uow.UnitOfWork, issueID string) string {
|
||||
return findParentMolecule(ctx, uowMolReader{uw: uw}, issueID)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -446,8 +446,11 @@ var createCmd = &cobra.Command{
|
|||
defer func() { _ = parentLookupStore.Close() }()
|
||||
}
|
||||
|
||||
var inheritedLabels []string
|
||||
noInheritLabels, _ := cmd.Flags().GetBool("no-inherit-labels")
|
||||
inheritParentLabels := parentID != "" && !noInheritLabels
|
||||
if parentID != "" {
|
||||
// A fail-fast with the message this command has always printed;
|
||||
// the create role refuses a missing parent on its own as well.
|
||||
ctx := rootCtx
|
||||
_, err := parentLookupStore.GetIssue(ctx, parentID)
|
||||
if err != nil {
|
||||
|
|
@ -456,16 +459,20 @@ var createCmd = &cobra.Command{
|
|||
}
|
||||
return HandleError("failed to check parent issue: %v", err)
|
||||
}
|
||||
|
||||
noInheritLabels, _ := cmd.Flags().GetBool("no-inherit-labels")
|
||||
if !noInheritLabels {
|
||||
inheritedLabels, _ = parentLookupStore.GetLabels(ctx, parentID)
|
||||
}
|
||||
}
|
||||
|
||||
labels = mergeCreateLabels(labels, inheritedLabels)
|
||||
|
||||
if dryRun {
|
||||
// The preview shows what the create role would inherit; the real
|
||||
// create asks the role to inherit (CreateRequest.InheritLabelsFromParent)
|
||||
// inside its own transaction. A failed read is reported, never
|
||||
// previewed as "no labels".
|
||||
if inheritParentLabels {
|
||||
inherited, err := parentLookupStore.GetLabels(rootCtx, parentID)
|
||||
if err != nil {
|
||||
return HandleError("failed to read the labels of parent %s: %v", parentID, err)
|
||||
}
|
||||
labels = mergeCreateLabels(labels, inherited)
|
||||
}
|
||||
return renderDryRun()
|
||||
}
|
||||
|
||||
|
|
@ -482,14 +489,12 @@ var createCmd = &cobra.Command{
|
|||
}
|
||||
|
||||
createCtx := rootCtx
|
||||
if parentID != "" {
|
||||
childID, err := store.GetNextChildID(rootCtx, parentID)
|
||||
if err != nil {
|
||||
return HandleError("%v", err)
|
||||
}
|
||||
explicitID = childID
|
||||
createCtx = storage.WithReservedChildCounter(createCtx, parentID, childID)
|
||||
}
|
||||
// The --parent child id is minted by the Lifecycle role, on every
|
||||
// backend and route: a create with a ParentID and no id of its own is
|
||||
// <parent>.<n>, minted inside the create's own transaction (conformance
|
||||
// RunIssueOperationsCreateUnderAParentMintsTheNextChildID, served leg
|
||||
// included), and the role stages the advanced counter itself. An
|
||||
// explicit --id never reaches here with a parent (refused above).
|
||||
|
||||
if explicitID != "" {
|
||||
_, err := validation.ValidateIDFormat(explicitID)
|
||||
|
|
@ -568,21 +573,20 @@ var createCmd = &cobra.Command{
|
|||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
// Label inheritance stays CLI-side (mergeCreateLabels above) because the
|
||||
// dry-run preview needs it too; asking the facade to inherit as well
|
||||
// would append the parent's labels a second time.
|
||||
// The parent's labels are the role's to inherit, inside the create.
|
||||
if priorityDefault {
|
||||
issue.Priority = 0
|
||||
}
|
||||
result, err := ops.Create(opsCtx, issueops.CreateRequest{
|
||||
Actor: currentActor(),
|
||||
Issue: issue,
|
||||
ParentID: parentID,
|
||||
Dependencies: createDependencyRequests(depSpecs),
|
||||
WaitsFor: waitsForRequest(waitsForSpec),
|
||||
ForceIDPrefix: forceCreate,
|
||||
IDPrefix: createIDPrefixOverride(),
|
||||
DefaultPriority: priorityDefault,
|
||||
Actor: currentActor(),
|
||||
Issue: issue,
|
||||
ParentID: parentID,
|
||||
InheritLabelsFromParent: inheritParentLabels,
|
||||
Dependencies: createDependencyRequests(depSpecs),
|
||||
WaitsFor: waitsForRequest(waitsForSpec),
|
||||
ForceIDPrefix: forceCreate,
|
||||
IDPrefix: createIDPrefixOverride(),
|
||||
DefaultPriority: priorityDefault,
|
||||
})
|
||||
if err != nil {
|
||||
// RULING R1: an occupied --id is a refusal, not a silent full-row
|
||||
|
|
|
|||
|
|
@ -9,7 +9,9 @@ import (
|
|||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// TestBurnWisps tests direct wisp deletion via burnWisps.
|
||||
|
|
@ -122,6 +124,23 @@ func TestBurnWisps(t *testing.T) {
|
|||
})
|
||||
}
|
||||
|
||||
// closeWithMoleculeAutoClose (re-)closes a step through the store's Lifecycle
|
||||
// role with AutoCloseMolecule set — the one path `bd close` takes on every
|
||||
// route — so the library's in-transaction auto-close decides the root. The
|
||||
// rule is state-derived, so re-closing an already-closed step drives it too.
|
||||
func closeWithMoleculeAutoClose(t *testing.T, ctx context.Context, s storage.DoltStorage, stepID string) {
|
||||
t.Helper()
|
||||
ops, err := s.IssueLifecycle()
|
||||
if err != nil {
|
||||
t.Fatalf("IssueLifecycle(): %v", err)
|
||||
}
|
||||
if _, err := ops.Close(ctx, issueops.CloseRequest{
|
||||
Actor: "test-actor", IssueID: stepID, Reason: "done", Session: "test-session", AutoCloseMolecule: true,
|
||||
}); err != nil {
|
||||
t.Fatalf("close %s with molecule auto-close: %v", stepID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutoCloseCompletedMolecule tests that closing the last step auto-closes the parent molecule.
|
||||
func TestAutoCloseCompletedMolecule(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
|
@ -179,7 +198,7 @@ func TestAutoCloseCompletedMolecule(t *testing.T) {
|
|||
}
|
||||
|
||||
// Now trigger auto-close
|
||||
autoCloseCompletedMolecule(ctx, s, step2.ID, "test-actor", "test-session")
|
||||
closeWithMoleculeAutoClose(t, ctx, s, step2.ID)
|
||||
|
||||
// Verify root is now closed
|
||||
updatedRoot, err := s.GetIssue(ctx, root.ID)
|
||||
|
|
@ -235,7 +254,7 @@ func TestAutoCloseCompletedMolecule(t *testing.T) {
|
|||
}
|
||||
|
||||
// Auto-close after closing step1 — step2 still open
|
||||
autoCloseCompletedMolecule(ctx, s, step1.ID, "test-actor", "test-session")
|
||||
closeWithMoleculeAutoClose(t, ctx, s, step1.ID)
|
||||
|
||||
// Verify root is still open
|
||||
updatedRoot, err := s.GetIssue(ctx, root.ID)
|
||||
|
|
@ -261,7 +280,7 @@ func TestAutoCloseCompletedMolecule(t *testing.T) {
|
|||
}
|
||||
|
||||
// Should not panic or error — just no-op
|
||||
autoCloseCompletedMolecule(ctx, s, orphan.ID, "test-actor", "test-session")
|
||||
closeWithMoleculeAutoClose(t, ctx, s, orphan.ID)
|
||||
})
|
||||
|
||||
t.Run("NoOpForAlreadyClosedMolecule", func(t *testing.T) {
|
||||
|
|
@ -297,7 +316,7 @@ func TestAutoCloseCompletedMolecule(t *testing.T) {
|
|||
}
|
||||
|
||||
// Should not panic — early return because root is already closed
|
||||
autoCloseCompletedMolecule(ctx, s, step.ID, "test-actor", "test-session")
|
||||
closeWithMoleculeAutoClose(t, ctx, s, step.ID)
|
||||
})
|
||||
|
||||
t.Run("ClosesWhenReparentedStepExcluded", func(t *testing.T) {
|
||||
|
|
@ -370,7 +389,7 @@ func TestAutoCloseCompletedMolecule(t *testing.T) {
|
|||
}
|
||||
|
||||
// Trigger auto-close — should succeed since only 2 children remain
|
||||
autoCloseCompletedMolecule(ctx, s, steps[1].ID, "test-actor", "test-session")
|
||||
closeWithMoleculeAutoClose(t, ctx, s, steps[1].ID)
|
||||
|
||||
// Verify root auto-closed (reparented step should be excluded from molecule)
|
||||
updatedRoot, err := s.GetIssue(ctx, root.ID)
|
||||
|
|
|
|||
|
|
@ -496,8 +496,10 @@ func validateFullGraphPlan(plan *GraphApplyPlan, cfg graphPlanConfig, opts Graph
|
|||
// duplicate ID (matching `bd create --id`), which for an atomic graph create
|
||||
// would silently rewrite the existing issue while reporting creation — a plan
|
||||
// must fail fast instead. Deliberately not overridable by --force: that flag
|
||||
// vouches for a foreign prefix, not for destroying existing data. Best-effort
|
||||
// by transport: exists is nil where the calling context has no store access.
|
||||
// vouches for a foreign prefix, not for destroying existing data. The probe is
|
||||
// exact on every backend, http included (its GetIssue answers a miss with
|
||||
// storage.ErrNotFound like the local stores); exists is nil only where the
|
||||
// command opened no store.
|
||||
func validateGraphApplyExplicitIDCollisions(plan *GraphApplyPlan, exists func(id string) (bool, error)) error {
|
||||
if exists == nil {
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -45,9 +45,6 @@ func (w *recordingMolWriter) DeleteIssue(context.Context, string, string) error
|
|||
func (w *recordingMolWriter) SetConfig(context.Context, string, string) error {
|
||||
panic("SetConfig: not part of the proto+proto bond")
|
||||
}
|
||||
func (w *recordingMolWriter) ClaimStepIfOpen(context.Context, string, string) error {
|
||||
panic("ClaimStepIfOpen: not part of the proto+proto bond")
|
||||
}
|
||||
|
||||
// TestBondProtoProtoLabelsTheCompoundAtCreation pins the property that makes
|
||||
// the compound's molecule label unable to land in the wrong plane: it travels
|
||||
|
|
|
|||
|
|
@ -3,15 +3,16 @@ package main
|
|||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"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/ui"
|
||||
"github.com/steveyegge/beads/internal/utils"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// LargeMoleculeThreshold is the step count above which we show summary instead of full list.
|
||||
|
|
@ -79,452 +80,100 @@ Use --limit or --range to view specific steps:
|
|||
if usesProxiedServer() {
|
||||
return runMolCurrentProxiedServer(rootCtx, args, agent, limit, rangeStr)
|
||||
}
|
||||
|
||||
ctx := rootCtx
|
||||
|
||||
if store == nil {
|
||||
return HandleErrorRespectJSON("no database connection")
|
||||
}
|
||||
|
||||
var rangeStart, rangeEnd int
|
||||
if rangeStr != "" {
|
||||
var err error
|
||||
rangeStart, rangeEnd, err = parseRange(rangeStr)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("invalid range '%s': %v", rangeStr, err)
|
||||
}
|
||||
resolve := func(ctx context.Context, arg string) (string, error) {
|
||||
return utils.ResolvePartialID(ctx, store, arg)
|
||||
}
|
||||
|
||||
explicitSteps := limit > 0 || rangeStr != ""
|
||||
|
||||
var molecules []*MoleculeProgress
|
||||
|
||||
if len(args) == 1 {
|
||||
moleculeID, err := utils.ResolvePartialID(ctx, store, args[0])
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("molecule '%s' not found", args[0])
|
||||
}
|
||||
|
||||
stats, err := store.GetMoleculeProgress(ctx, moleculeID)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("loading molecule: %v", err)
|
||||
}
|
||||
|
||||
if stats.Total > LargeMoleculeThreshold && !explicitSteps && !jsonOutput {
|
||||
printLargeMoleculeSummary(stats)
|
||||
return nil
|
||||
}
|
||||
|
||||
progress, err := getMoleculeProgress(ctx, store, moleculeID)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("loading molecule: %v", err)
|
||||
}
|
||||
|
||||
if rangeStr != "" {
|
||||
progress.Steps = filterStepsByRange(progress.Steps, rangeStart, rangeEnd)
|
||||
} else if limit > 0 && len(progress.Steps) > limit {
|
||||
progress.Steps = progress.Steps[:limit]
|
||||
}
|
||||
|
||||
molecules = append(molecules, progress)
|
||||
} else {
|
||||
molecules = findInProgressMolecules(ctx, store, agent)
|
||||
|
||||
if len(molecules) == 0 {
|
||||
molecules = findHookedMolecules(ctx, store, agent)
|
||||
}
|
||||
|
||||
if len(molecules) == 0 {
|
||||
if jsonOutput {
|
||||
return outputJSON([]interface{}{})
|
||||
}
|
||||
fmt.Printf("No molecules in progress")
|
||||
if agent != "" {
|
||||
fmt.Printf(" for %s", agent)
|
||||
}
|
||||
fmt.Println(".")
|
||||
fmt.Println("\nTo start work on a molecule:")
|
||||
fmt.Println(" bd mol wisp create <proto-id> # Instantiate as ephemeral wisp")
|
||||
fmt.Println(" bd update <step-id> --claim # Claim a step")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
return outputJSON(molecules)
|
||||
}
|
||||
|
||||
for i, mol := range molecules {
|
||||
if i > 0 {
|
||||
fmt.Println()
|
||||
}
|
||||
printMoleculeProgress(mol)
|
||||
}
|
||||
return nil
|
||||
return runMolCurrent(rootCtx, store, resolve, args, agent, limit, rangeStr)
|
||||
},
|
||||
}
|
||||
|
||||
// getMoleculeProgress loads a molecule and computes progress
|
||||
func getMoleculeProgress(ctx context.Context, s molReader, moleculeID string) (*MoleculeProgress, error) {
|
||||
subgraph, err := loadTemplateSubgraph(ctx, s, moleculeID)
|
||||
// runMolCurrent is `bd mol current` on every route. The molecule's steps,
|
||||
// their states, the progress counts and the current and next step are the
|
||||
// library's (issueops.ViewMolecule, ActiveMoleculeIDs, ReadMoleculeProgress);
|
||||
// what is here is the argument handling and the presentation.
|
||||
func runMolCurrent(ctx context.Context, s storage.DoltStorage, resolve func(context.Context, string) (string, error), args []string, agent string, limit int, rangeStr string) error {
|
||||
var rangeStart, rangeEnd int
|
||||
if rangeStr != "" {
|
||||
var err error
|
||||
rangeStart, rangeEnd, err = parseRange(rangeStr)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("invalid range '%s': %v", rangeStr, err)
|
||||
}
|
||||
}
|
||||
explicitSteps := limit > 0 || rangeStr != ""
|
||||
|
||||
roles, err := currentMoleculeRoles(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
|
||||
progress := &MoleculeProgress{
|
||||
MoleculeID: subgraph.Root.ID,
|
||||
MoleculeTitle: subgraph.Root.Title,
|
||||
Assignee: subgraph.Root.Assignee,
|
||||
Total: len(subgraph.Issues) - 1, // Exclude root
|
||||
}
|
||||
|
||||
// Compute step readiness from within-molecule dependencies.
|
||||
// Uses analyzeMoleculeParallel instead of GetReadyWork because GetReadyWork
|
||||
// excludes ephemeral issues (wisp steps are ephemeral by definition).
|
||||
// See: https://github.com/steveyegge/gastown/issues/1276 (historical reference)
|
||||
analysis := analyzeMoleculeParallel(subgraph)
|
||||
readyIDs := make(map[string]bool)
|
||||
for id, info := range analysis.Steps {
|
||||
if info.IsReady {
|
||||
readyIDs[id] = true
|
||||
}
|
||||
}
|
||||
|
||||
// Build step status list (exclude root)
|
||||
var steps []*StepStatus
|
||||
for _, issue := range subgraph.Issues {
|
||||
if issue.ID == subgraph.Root.ID {
|
||||
continue // Skip root
|
||||
}
|
||||
|
||||
step := &StepStatus{
|
||||
Issue: issue,
|
||||
}
|
||||
|
||||
switch issue.Status {
|
||||
case types.StatusClosed:
|
||||
step.Status = "done"
|
||||
progress.Completed++
|
||||
case types.StatusInProgress:
|
||||
step.Status = "current"
|
||||
step.IsCurrent = true
|
||||
progress.CurrentStep = issue
|
||||
case types.StatusBlocked:
|
||||
step.Status = "blocked"
|
||||
default:
|
||||
// Check if ready (unblocked)
|
||||
if readyIDs[issue.ID] {
|
||||
step.Status = "ready"
|
||||
if progress.NextStep == nil {
|
||||
progress.NextStep = issue
|
||||
}
|
||||
} else {
|
||||
step.Status = "pending"
|
||||
}
|
||||
}
|
||||
|
||||
steps = append(steps, step)
|
||||
}
|
||||
|
||||
// Sort steps by dependency order
|
||||
sortStepsByDependencyOrder(steps, subgraph)
|
||||
progress.Steps = steps
|
||||
|
||||
// If no current step but there's a ready step, set it as next
|
||||
if progress.CurrentStep == nil && progress.NextStep == nil {
|
||||
for _, step := range steps {
|
||||
if step.Status == "ready" {
|
||||
progress.NextStep = step.Issue
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return progress, nil
|
||||
}
|
||||
|
||||
// findInProgressMolecules finds molecules with in_progress steps for an agent
|
||||
func findInProgressMolecules(ctx context.Context, s molReader, agent string) []*MoleculeProgress {
|
||||
var inProgressIssues []*types.Issue
|
||||
|
||||
status := types.StatusInProgress
|
||||
filter := types.IssueFilter{Status: &status}
|
||||
if agent != "" {
|
||||
filter.Assignee = &agent
|
||||
}
|
||||
allIssues, err := s.SearchIssues(ctx, "", filter)
|
||||
if err == nil {
|
||||
inProgressIssues = allIssues
|
||||
}
|
||||
|
||||
if len(inProgressIssues) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Batch-find parent molecules for all in_progress issues (bd-hn4q)
|
||||
issueIDs := make([]string, len(inProgressIssues))
|
||||
for i, issue := range inProgressIssues {
|
||||
issueIDs[i] = issue.ID
|
||||
}
|
||||
moleculeRoots := findParentMolecules(ctx, s, issueIDs)
|
||||
|
||||
moleculeMap := make(map[string]*MoleculeProgress)
|
||||
for _, issue := range inProgressIssues {
|
||||
moleculeID := moleculeRoots[issue.ID]
|
||||
if moleculeID == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
if _, exists := moleculeMap[moleculeID]; !exists {
|
||||
progress, err := getMoleculeProgress(ctx, s, moleculeID)
|
||||
if err == nil {
|
||||
moleculeMap[moleculeID] = progress
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Convert to slice
|
||||
var molecules []*MoleculeProgress
|
||||
for _, mol := range moleculeMap {
|
||||
molecules = append(molecules, mol)
|
||||
}
|
||||
|
||||
// Sort by molecule ID for consistent output
|
||||
sort.Slice(molecules, func(i, j int) bool {
|
||||
return molecules[i].MoleculeID < molecules[j].MoleculeID
|
||||
})
|
||||
|
||||
return molecules
|
||||
}
|
||||
|
||||
// findHookedMolecules finds molecules bonded to hooked issues for an agent.
|
||||
// This is a fallback when no in_progress steps exist but a molecule is attached
|
||||
// to the agent's hooked work via a "blocks" dependency.
|
||||
func findHookedMolecules(ctx context.Context, s molReader, agent string) []*MoleculeProgress {
|
||||
// Query for hooked issues assigned to the agent
|
||||
status := types.StatusHooked
|
||||
filter := types.IssueFilter{Status: &status}
|
||||
if agent != "" {
|
||||
filter.Assignee = &agent
|
||||
}
|
||||
hookedIssues, err := s.SearchIssues(ctx, "", filter)
|
||||
if err != nil || len(hookedIssues) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// For each hooked issue, check if it IS a molecule or has blocks deps on one
|
||||
moleculeMap := make(map[string]*MoleculeProgress)
|
||||
for _, issue := range hookedIssues {
|
||||
// Check if the hooked issue itself is a molecule (e.g., patrol wisps
|
||||
// are directly hooked without a separate handoff bead). hq-3paz0m
|
||||
if issue.IssueType == types.TypeEpic {
|
||||
if _, exists := moleculeMap[issue.ID]; !exists {
|
||||
progress, err := getMoleculeProgress(ctx, s, issue.ID)
|
||||
if err == nil {
|
||||
moleculeMap[issue.ID] = progress
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
deps, err := s.GetDependencyRecords(ctx, issue.ID)
|
||||
if len(args) == 1 {
|
||||
moleculeID, err := resolve(ctx, args[0])
|
||||
if err != nil {
|
||||
continue
|
||||
return moleculeNotResolved(args[0], err)
|
||||
}
|
||||
|
||||
// Look for a blocks dependency pointing to a molecule (epic or template)
|
||||
for _, dep := range deps {
|
||||
if dep.Type != types.DepBlocks {
|
||||
continue
|
||||
if !explicitSteps && !jsonOutput {
|
||||
stats, err := issueops.ReadMoleculeProgress(ctx, roles.molecule, moleculeID)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("loading molecule: %v", err)
|
||||
}
|
||||
// The issue depends on (is blocked by) dep.DependsOnID
|
||||
candidate, err := s.GetIssue(ctx, dep.DependsOnID)
|
||||
if err != nil || candidate == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// Check if candidate is a molecule (epic or has template label)
|
||||
isMolecule := candidate.IssueType == types.TypeEpic
|
||||
if !isMolecule {
|
||||
for _, label := range candidate.Labels {
|
||||
if label == BeadsTemplateLabel {
|
||||
isMolecule = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if isMolecule {
|
||||
if _, exists := moleculeMap[candidate.ID]; !exists {
|
||||
progress, err := getMoleculeProgress(ctx, s, candidate.ID)
|
||||
if err == nil {
|
||||
moleculeMap[candidate.ID] = progress
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Convert to slice
|
||||
var molecules []*MoleculeProgress
|
||||
for _, mol := range moleculeMap {
|
||||
molecules = append(molecules, mol)
|
||||
}
|
||||
|
||||
// Sort by molecule ID for consistent output
|
||||
sort.Slice(molecules, func(i, j int) bool {
|
||||
return molecules[i].MoleculeID < molecules[j].MoleculeID
|
||||
})
|
||||
|
||||
return molecules
|
||||
}
|
||||
|
||||
// findParentMolecules batch-finds the root molecule for multiple issue IDs.
|
||||
// Returns a map of issueID → moleculeRootID for issues that belong to a molecule.
|
||||
// Issues not part of a molecule are omitted from the result.
|
||||
//
|
||||
// This replaces the previous N+1 pattern where findParentMolecule was called
|
||||
// in a loop, issuing GetDependencyRecords + GetIssue per level per issue.
|
||||
// Instead, this walks parent-child chains level-by-level using batch queries,
|
||||
// reducing O(N * depth) round-trips to O(depth). (bd-hn4q)
|
||||
func findParentMolecules(ctx context.Context, s molReader, issueIDs []string) map[string]string {
|
||||
if len(issueIDs) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// rootOf accumulates: startID -> rootID for chains that terminated
|
||||
rootOf := make(map[string]string, len(issueIDs))
|
||||
|
||||
// current tracks: startID -> currentAncestorID (still walking up)
|
||||
current := make(map[string]string, len(issueIDs))
|
||||
for _, id := range issueIDs {
|
||||
current[id] = id
|
||||
}
|
||||
|
||||
// Walk up parent-child chains in batch, level by level
|
||||
for depth := 0; depth < 50 && len(current) > 0; depth++ {
|
||||
// Collect unique IDs at current level
|
||||
seen := make(map[string]bool, len(current))
|
||||
toCheck := make([]string, 0, len(current))
|
||||
for _, curID := range current {
|
||||
if !seen[curID] {
|
||||
seen[curID] = true
|
||||
toCheck = append(toCheck, curID)
|
||||
if stats.Total > LargeMoleculeThreshold {
|
||||
printLargeMoleculeSummary(stats)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Batch fetch parent-child deps for all current ancestors
|
||||
allDeps, err := s.GetDependencyRecordsForIssues(ctx, toCheck)
|
||||
view, err := issueops.ViewMolecule(ctx, roles.molecule, moleculeID)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("loading molecule: %v", err)
|
||||
}
|
||||
progress := moleculeProgressOf(view)
|
||||
if rangeStr != "" {
|
||||
progress.Steps = filterStepsByRange(progress.Steps, rangeStart, rangeEnd)
|
||||
} else if limit > 0 && len(progress.Steps) > limit {
|
||||
progress.Steps = progress.Steps[:limit]
|
||||
}
|
||||
molecules = append(molecules, progress)
|
||||
} else {
|
||||
ids, err := issueops.ActiveMoleculeIDs(ctx, roles.reader, roles.molecule, agent)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
molecules, err = viewMolecules(ctx, roles, ids)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
if len(molecules) == 0 {
|
||||
if jsonOutput {
|
||||
return outputJSON([]interface{}{})
|
||||
}
|
||||
fmt.Printf("No molecules in progress")
|
||||
if agent != "" {
|
||||
fmt.Printf(" for %s", agent)
|
||||
}
|
||||
fmt.Println(".")
|
||||
fmt.Println("\nTo start work on a molecule:")
|
||||
fmt.Println(" bd mol wisp create <proto-id> # Instantiate as ephemeral wisp")
|
||||
fmt.Println(" bd update <step-id> --claim # Claim a step")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Build parent lookup: childID -> parentID
|
||||
parentOf := make(map[string]string, len(allDeps))
|
||||
for childID, deps := range allDeps {
|
||||
for _, dep := range deps {
|
||||
if dep.Type == types.DepParentChild {
|
||||
parentOf[childID] = dep.DependsOnID
|
||||
break
|
||||
}
|
||||
}
|
||||
if jsonOutput {
|
||||
return outputJSON(molecules)
|
||||
}
|
||||
for i, mol := range molecules {
|
||||
if i > 0 {
|
||||
fmt.Println()
|
||||
}
|
||||
|
||||
// Advance chains that have parents, finalize those that don't
|
||||
nextCurrent := make(map[string]string)
|
||||
for startID, curID := range current {
|
||||
if parent, ok := parentOf[curID]; ok {
|
||||
nextCurrent[startID] = parent
|
||||
} else {
|
||||
rootOf[startID] = curID
|
||||
}
|
||||
}
|
||||
current = nextCurrent
|
||||
printMoleculeProgress(mol)
|
||||
}
|
||||
|
||||
// Anything still walking after max depth — treat as root
|
||||
for startID, curID := range current {
|
||||
rootOf[startID] = curID
|
||||
}
|
||||
|
||||
// Batch fetch root issues to check if they're molecules
|
||||
uniqueRoots := make(map[string]bool, len(rootOf))
|
||||
for _, rootID := range rootOf {
|
||||
uniqueRoots[rootID] = true
|
||||
}
|
||||
rootIDs := make([]string, 0, len(uniqueRoots))
|
||||
for id := range uniqueRoots {
|
||||
rootIDs = append(rootIDs, id)
|
||||
}
|
||||
|
||||
// TODO(batchgetter): unbounded id list; see issueops.BatchGetter's doc and
|
||||
// the importIssueLookup TODO in import_shared.go for why this is not yet
|
||||
// routed through the role.
|
||||
rootIssues, err := s.GetIssuesByIDs(ctx, rootIDs)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
isMolecule := make(map[string]bool, len(rootIssues))
|
||||
for _, issue := range rootIssues {
|
||||
// `bd mol pour` creates roots with TypeMolecule (no template label),
|
||||
// while distilled-from-epic templates use TypeEpic + BeadsTemplateLabel.
|
||||
// Both shapes must be recognized so --continue can advance through
|
||||
// poured molecules. See gastownhall/beads#3719.
|
||||
if issue.IssueType == types.TypeEpic || issue.IssueType == types.TypeMolecule {
|
||||
isMolecule[issue.ID] = true
|
||||
continue
|
||||
}
|
||||
for _, label := range issue.Labels {
|
||||
if label == BeadsTemplateLabel {
|
||||
isMolecule[issue.ID] = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Filter to only molecule roots
|
||||
result := make(map[string]string, len(rootOf))
|
||||
for startID, rootID := range rootOf {
|
||||
if isMolecule[rootID] {
|
||||
result[startID] = rootID
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// findParentMolecule walks up the parent-child chain to find the root molecule
|
||||
// for a single issue. Returns "" if the issue is not part of a molecule.
|
||||
func findParentMolecule(ctx context.Context, s molReader, issueID string) string {
|
||||
roots := findParentMolecules(ctx, s, []string{issueID})
|
||||
return roots[issueID]
|
||||
}
|
||||
|
||||
// sortStepsByDependencyOrder sorts steps by their dependency order
|
||||
func sortStepsByDependencyOrder(steps []*StepStatus, subgraph *TemplateSubgraph) {
|
||||
// Build dependency graph
|
||||
depCount := make(map[string]int) // issue ID -> number of deps
|
||||
for _, step := range steps {
|
||||
depCount[step.Issue.ID] = 0
|
||||
}
|
||||
|
||||
// Count blocking dependencies within the step set
|
||||
stepIDs := make(map[string]bool)
|
||||
for _, step := range steps {
|
||||
stepIDs[step.Issue.ID] = true
|
||||
}
|
||||
|
||||
for _, dep := range subgraph.Dependencies {
|
||||
if dep.Type == types.DepBlocks && stepIDs[dep.IssueID] && stepIDs[dep.DependsOnID] {
|
||||
depCount[dep.IssueID]++
|
||||
}
|
||||
}
|
||||
|
||||
// Stable sort by dependency count (fewer deps first)
|
||||
sort.SliceStable(steps, func(i, j int) bool {
|
||||
return depCount[steps[i].Issue.ID] < depCount[steps[j].Issue.ID]
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// printMoleculeProgress prints the progress in human-readable format
|
||||
|
|
@ -590,77 +239,6 @@ type ContinueResult struct {
|
|||
MoleculeID string `json:"molecule_id,omitempty"`
|
||||
}
|
||||
|
||||
// AdvanceToNextStep finds the next ready step in a molecule after closing a step.
|
||||
// If autoClaim is true, it marks the next step as in_progress using optimistic
|
||||
// concurrency control: the step's status is re-verified before claiming to
|
||||
// guard against TOCTOU races where multiple agents identify and try to claim the
|
||||
// same step concurrently.
|
||||
// Returns nil if the issue is not part of a molecule.
|
||||
func AdvanceToNextStep(ctx context.Context, s molWriter, closedStepID string, autoClaim bool, actorName string) (*ContinueResult, error) {
|
||||
if s == nil {
|
||||
return nil, fmt.Errorf("no database connection")
|
||||
}
|
||||
|
||||
// Get the closed step
|
||||
closedStep, err := s.GetIssue(ctx, closedStepID)
|
||||
if err != nil || closedStep == nil {
|
||||
return nil, fmt.Errorf("could not get closed step: %w", err)
|
||||
}
|
||||
|
||||
result := &ContinueResult{
|
||||
ClosedStep: closedStep,
|
||||
}
|
||||
|
||||
// Find parent molecule
|
||||
moleculeID := findParentMolecule(ctx, s, closedStepID)
|
||||
if moleculeID == "" {
|
||||
// Not part of a molecule - nothing to advance
|
||||
return nil, nil
|
||||
}
|
||||
result.MoleculeID = moleculeID
|
||||
|
||||
// Load molecule progress
|
||||
progress, err := getMoleculeProgress(ctx, s, moleculeID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("could not load molecule: %w", err)
|
||||
}
|
||||
|
||||
// Check if molecule is complete
|
||||
if progress.Completed >= progress.Total {
|
||||
result.MolComplete = true
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Collect all ready steps (not just the first) so we can fall back
|
||||
// if a concurrent agent claims one before us.
|
||||
var readySteps []*types.Issue
|
||||
for _, step := range progress.Steps {
|
||||
if step.Status == "ready" {
|
||||
readySteps = append(readySteps, step.Issue)
|
||||
}
|
||||
}
|
||||
|
||||
if len(readySteps) == 0 {
|
||||
// No ready steps - might be blocked
|
||||
return result, nil
|
||||
}
|
||||
|
||||
result.NextStep = readySteps[0]
|
||||
|
||||
if autoClaim {
|
||||
for _, candidate := range readySteps {
|
||||
if err := s.ClaimStepIfOpen(ctx, candidate.ID, actorName); err == nil {
|
||||
result.NextStep = candidate
|
||||
result.AutoAdvanced = true
|
||||
break
|
||||
}
|
||||
// This candidate was already claimed; try the next ready step
|
||||
}
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// PrintContinueResult prints the result of advancing to the next step
|
||||
func PrintContinueResult(result *ContinueResult) {
|
||||
if result == nil {
|
||||
|
|
|
|||
|
|
@ -37,7 +37,6 @@ type molReader interface {
|
|||
GetConfig(ctx context.Context, key string) (string, error)
|
||||
IsInfraTypeCtx(ctx context.Context, t types.IssueType) bool
|
||||
GetCustomStatusesDetailed(ctx context.Context) ([]types.CustomStatus, error)
|
||||
GetMoleculeProgress(ctx context.Context, moleculeID string) (*types.MoleculeProgressStats, error)
|
||||
GetMoleculeLastActivity(ctx context.Context, moleculeID string) (*types.MoleculeLastActivity, error)
|
||||
FindWispDependentsRecursive(ctx context.Context, ids []string) (map[string]bool, error)
|
||||
}
|
||||
|
|
@ -58,7 +57,6 @@ type molWriter interface {
|
|||
CloseIssue(ctx context.Context, id, reason, actor string) error
|
||||
DeleteIssue(ctx context.Context, id, actor string) error
|
||||
SetConfig(ctx context.Context, key, value string) error
|
||||
ClaimStepIfOpen(ctx context.Context, id, actor string) error
|
||||
}
|
||||
|
||||
type storeMolWriter struct {
|
||||
|
|
@ -103,26 +101,6 @@ func (w storeMolWriter) GetConfig(ctx context.Context, key string) (string, erro
|
|||
return w.DoltStorage.GetConfig(ctx, key)
|
||||
}
|
||||
|
||||
func (w storeMolWriter) ClaimStepIfOpen(ctx context.Context, id, actor string) error {
|
||||
return w.DoltStorage.RunInTransaction(ctx, fmt.Sprintf("bd: advance to step %s", id), func(tx storage.Transaction) error {
|
||||
current, err := tx.GetIssue(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if current == nil {
|
||||
return fmt.Errorf("step %s not found", id)
|
||||
}
|
||||
if current.Status != types.StatusOpen {
|
||||
return fmt.Errorf("step %s already claimed (status: %s)", id, current.Status)
|
||||
}
|
||||
return tx.UpdateIssue(ctx, id, map[string]interface{}{"status": types.StatusInProgress}, actor)
|
||||
})
|
||||
}
|
||||
|
||||
func newStandaloneStoreMolWriter(store storage.DoltStorage) storeMolWriter {
|
||||
return storeMolWriter{DoltStorage: store}
|
||||
}
|
||||
|
||||
type uowMolReader struct {
|
||||
uw uow.UnitOfWork
|
||||
}
|
||||
|
|
@ -266,40 +244,6 @@ func (r uowMolReader) GetCustomStatusesDetailed(ctx context.Context) ([]types.Cu
|
|||
return r.uw.ConfigUseCase().GetCustomStatuses(ctx)
|
||||
}
|
||||
|
||||
func (r uowMolReader) GetMoleculeProgress(ctx context.Context, moleculeID string) (*types.MoleculeProgressStats, error) {
|
||||
stats := &types.MoleculeProgressStats{MoleculeID: moleculeID}
|
||||
|
||||
root, err := r.GetIssue(ctx, moleculeID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get molecule: %w", err)
|
||||
}
|
||||
if root != nil {
|
||||
stats.MoleculeTitle = root.Title
|
||||
}
|
||||
|
||||
dependents, err := r.GetDependentsWithMetadata(ctx, moleculeID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get molecule children: %w", err)
|
||||
}
|
||||
|
||||
for _, dependent := range dependents {
|
||||
if dependent.DependencyType != types.DepParentChild {
|
||||
continue
|
||||
}
|
||||
stats.Total++
|
||||
switch dependent.Status {
|
||||
case types.StatusClosed:
|
||||
stats.Completed++
|
||||
case types.StatusInProgress:
|
||||
stats.InProgress++
|
||||
if stats.CurrentStepID == "" {
|
||||
stats.CurrentStepID = dependent.ID
|
||||
}
|
||||
}
|
||||
}
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
func (r uowMolReader) GetMoleculeLastActivity(ctx context.Context, moleculeID string) (*types.MoleculeLastActivity, error) {
|
||||
dependents, err := r.GetDependentsWithMetadata(ctx, moleculeID)
|
||||
if err != nil {
|
||||
|
|
@ -459,16 +403,3 @@ func (w *uowMolWriter) DeleteIssue(ctx context.Context, id, actor string) error
|
|||
func (w *uowMolWriter) SetConfig(ctx context.Context, key, value string) error {
|
||||
return w.uw.ConfigUseCase().SetConfig(ctx, key, value)
|
||||
}
|
||||
|
||||
func (w *uowMolWriter) ClaimStepIfOpen(ctx context.Context, id, actor string) error {
|
||||
isWisp, err := w.isWisp(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if isWisp {
|
||||
_, err := w.uw.IssueUseCase().ClaimWispIfOpen(ctx, id, actor)
|
||||
return err
|
||||
}
|
||||
_, err = w.uw.IssueUseCase().ClaimIssueIfOpen(ctx, id, actor)
|
||||
return err
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,9 +6,11 @@ import (
|
|||
|
||||
"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/ui"
|
||||
"github.com/steveyegge/beads/internal/utils"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
var molProgressCmd = &cobra.Command{
|
||||
|
|
@ -43,102 +45,82 @@ Example:
|
|||
if usesProxiedServer() {
|
||||
return runMolProgressProxiedServer(rootCtx, args)
|
||||
}
|
||||
|
||||
ctx := rootCtx
|
||||
|
||||
if store == nil {
|
||||
return HandleErrorRespectJSON("no database connection")
|
||||
}
|
||||
|
||||
var moleculeID string
|
||||
if len(args) == 1 {
|
||||
resolved, err := utils.ResolvePartialID(ctx, store, args[0])
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("molecule '%s' not found", args[0])
|
||||
}
|
||||
moleculeID = resolved
|
||||
} else {
|
||||
moleculeIDs := findInProgressMoleculeIDs(ctx, store, currentActor())
|
||||
if len(moleculeIDs) == 0 {
|
||||
if jsonOutput {
|
||||
return outputJSON([]interface{}{})
|
||||
}
|
||||
fmt.Println("No molecules in progress.")
|
||||
fmt.Println("\nUse: bd mol progress <molecule-id>")
|
||||
return nil
|
||||
}
|
||||
moleculeID = moleculeIDs[0]
|
||||
resolve := func(ctx context.Context, arg string) (string, error) {
|
||||
return utils.ResolvePartialID(ctx, store, arg)
|
||||
}
|
||||
|
||||
stats, err := store.GetMoleculeProgress(ctx, moleculeID)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
output := map[string]interface{}{
|
||||
"molecule_id": stats.MoleculeID,
|
||||
"molecule_title": stats.MoleculeTitle,
|
||||
"total": stats.Total,
|
||||
"completed": stats.Completed,
|
||||
"in_progress": stats.InProgress,
|
||||
"current_step_id": stats.CurrentStepID,
|
||||
}
|
||||
if stats.Total > 0 {
|
||||
output["percent"] = float64(stats.Completed) * 100 / float64(stats.Total)
|
||||
}
|
||||
if stats.FirstClosed != nil && stats.LastClosed != nil && stats.Completed > 1 {
|
||||
duration := stats.LastClosed.Sub(*stats.FirstClosed)
|
||||
if duration > 0 {
|
||||
rate := float64(stats.Completed-1) / duration.Hours()
|
||||
output["rate_per_hour"] = rate
|
||||
remaining := stats.Total - stats.Completed
|
||||
if rate > 0 {
|
||||
etaHours := float64(remaining) / rate
|
||||
output["eta_hours"] = etaHours
|
||||
}
|
||||
}
|
||||
}
|
||||
return outputJSON(output)
|
||||
}
|
||||
|
||||
printMoleculeProgressStats(stats)
|
||||
return nil
|
||||
return runMolProgress(rootCtx, store, resolve, args)
|
||||
},
|
||||
}
|
||||
|
||||
// findInProgressMoleculeIDs finds molecule IDs with in_progress steps for an agent.
|
||||
// This is a lightweight version that only returns IDs without loading subgraphs.
|
||||
func findInProgressMoleculeIDs(ctx context.Context, s molReader, agent string) []string {
|
||||
// Query for in_progress issues
|
||||
status := types.StatusInProgress
|
||||
filter := types.IssueFilter{Status: &status}
|
||||
if agent != "" {
|
||||
filter.Assignee = &agent
|
||||
}
|
||||
inProgressIssues, err := s.SearchIssues(ctx, "", filter)
|
||||
if err != nil || len(inProgressIssues) == 0 {
|
||||
return nil
|
||||
// runMolProgress is `bd mol progress` on every route: the counts are
|
||||
// issueops.ReadMoleculeProgress over the molecule's direct steps, and the
|
||||
// molecule without an id is the first of issueops.InProgressMoleculeIDs.
|
||||
func runMolProgress(ctx context.Context, s storage.DoltStorage, resolve func(context.Context, string) (string, error), args []string) error {
|
||||
roles, err := currentMoleculeRoles(s)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
|
||||
// Batch-find parent molecules for all in_progress issues (bd-hn4q)
|
||||
issueIDs := make([]string, len(inProgressIssues))
|
||||
for i, issue := range inProgressIssues {
|
||||
issueIDs[i] = issue.ID
|
||||
}
|
||||
moleculeRoots := findParentMolecules(ctx, s, issueIDs)
|
||||
|
||||
seen := make(map[string]bool)
|
||||
var moleculeIDs []string
|
||||
for _, issue := range inProgressIssues {
|
||||
moleculeID := moleculeRoots[issue.ID]
|
||||
if moleculeID != "" && !seen[moleculeID] {
|
||||
seen[moleculeID] = true
|
||||
moleculeIDs = append(moleculeIDs, moleculeID)
|
||||
var moleculeID string
|
||||
if len(args) == 1 {
|
||||
resolved, err := resolve(ctx, args[0])
|
||||
if err != nil {
|
||||
return moleculeNotResolved(args[0], err)
|
||||
}
|
||||
moleculeID = resolved
|
||||
} else {
|
||||
moleculeIDs, err := issueops.InProgressMoleculeIDs(ctx, roles.reader, roles.molecule, currentActor())
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("finding molecules in progress: %v", err)
|
||||
}
|
||||
if len(moleculeIDs) == 0 {
|
||||
if jsonOutput {
|
||||
return outputJSON([]interface{}{})
|
||||
}
|
||||
fmt.Println("No molecules in progress.")
|
||||
fmt.Println("\nUse: bd mol progress <molecule-id>")
|
||||
return nil
|
||||
}
|
||||
moleculeID = moleculeIDs[0]
|
||||
}
|
||||
|
||||
return moleculeIDs
|
||||
stats, err := issueops.ReadMoleculeProgress(ctx, roles.molecule, moleculeID)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
output := map[string]interface{}{
|
||||
"molecule_id": stats.MoleculeID,
|
||||
"molecule_title": stats.MoleculeTitle,
|
||||
"total": stats.Total,
|
||||
"completed": stats.Completed,
|
||||
"in_progress": stats.InProgress,
|
||||
"current_step_id": stats.CurrentStepID,
|
||||
}
|
||||
if stats.Total > 0 {
|
||||
output["percent"] = float64(stats.Completed) * 100 / float64(stats.Total)
|
||||
}
|
||||
if stats.FirstClosed != nil && stats.LastClosed != nil && stats.Completed > 1 {
|
||||
duration := stats.LastClosed.Sub(*stats.FirstClosed)
|
||||
if duration > 0 {
|
||||
rate := float64(stats.Completed-1) / duration.Hours()
|
||||
output["rate_per_hour"] = rate
|
||||
remaining := stats.Total - stats.Completed
|
||||
if rate > 0 {
|
||||
etaHours := float64(remaining) / rate
|
||||
output["eta_hours"] = etaHours
|
||||
}
|
||||
}
|
||||
}
|
||||
return outputJSON(output)
|
||||
}
|
||||
|
||||
printMoleculeProgressStats(stats)
|
||||
return nil
|
||||
}
|
||||
|
||||
// printMoleculeProgressStats prints molecule progress in human-readable format
|
||||
|
|
|
|||
|
|
@ -160,158 +160,55 @@ func runPourProxiedServer(ctx context.Context, in pourInput) error {
|
|||
}
|
||||
|
||||
func runMolShowProxiedServer(ctx context.Context, arg string) error {
|
||||
uw, err := proxiedOpenReadUOW(ctx)
|
||||
moleculeID, err := proxiedResolvePartialID(ctx, arg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer uw.Close(ctx)
|
||||
|
||||
r := uowMolReader{uw: uw}
|
||||
moleculeID, err := utils.ResolvePartialID(ctx, r, arg)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("molecule '%s' not found", arg)
|
||||
return moleculeNotResolved(arg, err)
|
||||
}
|
||||
|
||||
subgraph, err := loadTemplateSubgraph(ctx, r, moleculeID)
|
||||
roles, err := proxiedMoleculeRoles()
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("loading molecule: %v", err)
|
||||
}
|
||||
|
||||
if molShowParallel {
|
||||
return showMoleculeWithParallel(subgraph)
|
||||
}
|
||||
return showMolecule(subgraph)
|
||||
return runMolShow(ctx, roles, moleculeID)
|
||||
}
|
||||
|
||||
func runMolCurrentProxiedServer(ctx context.Context, args []string, agent string, limit int, rangeStr string) error {
|
||||
uw, err := proxiedOpenReadUOW(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer uw.Close(ctx)
|
||||
|
||||
r := uowMolReader{uw: uw}
|
||||
|
||||
var rangeStart, rangeEnd int
|
||||
if rangeStr != "" {
|
||||
rangeStart, rangeEnd, err = parseRange(rangeStr)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("invalid range '%s': %v", rangeStr, err)
|
||||
}
|
||||
}
|
||||
explicitSteps := limit > 0 || rangeStr != ""
|
||||
|
||||
var molecules []*MoleculeProgress
|
||||
|
||||
if len(args) == 1 {
|
||||
moleculeID, err := utils.ResolvePartialID(ctx, r, args[0])
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("molecule '%s' not found", args[0])
|
||||
}
|
||||
|
||||
stats, err := r.GetMoleculeProgress(ctx, moleculeID)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("loading molecule: %v", err)
|
||||
}
|
||||
if stats.Total > LargeMoleculeThreshold && !explicitSteps && !jsonOutput {
|
||||
printLargeMoleculeSummary(stats)
|
||||
return nil
|
||||
}
|
||||
|
||||
progress, err := getMoleculeProgress(ctx, r, moleculeID)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("loading molecule: %v", err)
|
||||
}
|
||||
if rangeStr != "" {
|
||||
progress.Steps = filterStepsByRange(progress.Steps, rangeStart, rangeEnd)
|
||||
} else if limit > 0 && len(progress.Steps) > limit {
|
||||
progress.Steps = progress.Steps[:limit]
|
||||
}
|
||||
molecules = append(molecules, progress)
|
||||
} else {
|
||||
molecules = findInProgressMolecules(ctx, r, agent)
|
||||
if len(molecules) == 0 {
|
||||
molecules = findHookedMolecules(ctx, r, agent)
|
||||
}
|
||||
if len(molecules) == 0 {
|
||||
if jsonOutput {
|
||||
return outputJSON([]interface{}{})
|
||||
}
|
||||
fmt.Printf("No molecules in progress")
|
||||
if agent != "" {
|
||||
fmt.Printf(" for %s", agent)
|
||||
}
|
||||
fmt.Println(".")
|
||||
fmt.Println("\nTo start work on a molecule:")
|
||||
fmt.Println(" bd mol wisp create <proto-id> # Instantiate as ephemeral wisp")
|
||||
fmt.Println(" bd update <step-id> --claim # Claim a step")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
return outputJSON(molecules)
|
||||
}
|
||||
for i, mol := range molecules {
|
||||
if i > 0 {
|
||||
fmt.Println()
|
||||
}
|
||||
printMoleculeProgress(mol)
|
||||
}
|
||||
return nil
|
||||
return runMolCurrent(ctx, nil, proxiedResolvePartialID, args, agent, limit, rangeStr)
|
||||
}
|
||||
|
||||
func runMolProgressProxiedServer(ctx context.Context, args []string) error {
|
||||
return runMolProgress(ctx, nil, proxiedResolvePartialID, args)
|
||||
}
|
||||
|
||||
// proxiedResolvePartialID resolves a partial id inside a read unit of work of
|
||||
// its own. A unit of work that cannot be opened is reported as itself
|
||||
// (proxiedOpenReadUOW) and answered as a reportedResolveError, so the caller
|
||||
// does not report a connection failure as a molecule that was not found.
|
||||
func proxiedResolvePartialID(ctx context.Context, arg string) (string, error) {
|
||||
uw, err := proxiedOpenReadUOW(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
return "", reportedResolveError{err: err}
|
||||
}
|
||||
defer uw.Close(ctx)
|
||||
return utils.ResolvePartialID(ctx, uowMolReader{uw: uw}, arg)
|
||||
}
|
||||
|
||||
r := uowMolReader{uw: uw}
|
||||
// reportedResolveError is an id resolution that failed before it could look
|
||||
// the id up, and whose failure was already reported.
|
||||
type reportedResolveError struct{ err error }
|
||||
|
||||
var moleculeID string
|
||||
if len(args) == 1 {
|
||||
resolved, err := utils.ResolvePartialID(ctx, r, args[0])
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("molecule '%s' not found", args[0])
|
||||
}
|
||||
moleculeID = resolved
|
||||
} else {
|
||||
moleculeIDs := findInProgressMoleculeIDs(ctx, r, currentActor())
|
||||
if len(moleculeIDs) == 0 {
|
||||
if jsonOutput {
|
||||
return outputJSON([]interface{}{})
|
||||
}
|
||||
fmt.Println("No molecules in progress.")
|
||||
fmt.Println("\nUse: bd mol progress <molecule-id>")
|
||||
return nil
|
||||
}
|
||||
moleculeID = moleculeIDs[0]
|
||||
func (e reportedResolveError) Error() string { return e.err.Error() }
|
||||
func (e reportedResolveError) Unwrap() error { return e.err }
|
||||
|
||||
// moleculeNotResolved reports a molecule id argument that did not resolve:
|
||||
// "not found" when the lookup ran, and the failure as already reported when
|
||||
// the lookup never ran (reportedResolveError).
|
||||
func moleculeNotResolved(arg string, err error) error {
|
||||
var reported reportedResolveError
|
||||
if errors.As(err, &reported) {
|
||||
return reported.err
|
||||
}
|
||||
|
||||
stats, err := r.GetMoleculeProgress(ctx, moleculeID)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
output := map[string]interface{}{
|
||||
"molecule_id": stats.MoleculeID,
|
||||
"molecule_title": stats.MoleculeTitle,
|
||||
"total": stats.Total,
|
||||
"completed": stats.Completed,
|
||||
"in_progress": stats.InProgress,
|
||||
"current_step_id": stats.CurrentStepID,
|
||||
}
|
||||
if stats.Total > 0 {
|
||||
output["percent"] = float64(stats.Completed) * 100 / float64(stats.Total)
|
||||
}
|
||||
return outputJSON(output)
|
||||
}
|
||||
|
||||
printMoleculeProgressStats(stats)
|
||||
return nil
|
||||
return HandleErrorRespectJSON("molecule '%s' not found", arg)
|
||||
}
|
||||
|
||||
func runMolLastActivityProxiedServer(ctx context.Context, arg string) error {
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import (
|
|||
"github.com/steveyegge/beads/internal/metrics"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/internal/ui"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// GatedMolecule represents a molecule ready for gate-resume dispatch
|
||||
|
|
@ -197,7 +198,10 @@ func findGateReadyMolecules(ctx context.Context, s molReader) ([]*GatedMolecule,
|
|||
hookedIDs[i] = issue.ID
|
||||
hookedMolecules[issue.ID] = true // Mark hooked issue itself
|
||||
}
|
||||
hookedRoots := findParentMolecules(ctx, s, hookedIDs)
|
||||
hookedRoots, err := issueops.MoleculeRoots(ctx, rawMoleculeReader{s: s}.moleculeReader(), hookedIDs)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("finding molecules of hooked issues: %w", err)
|
||||
}
|
||||
for _, molID := range hookedRoots {
|
||||
hookedMolecules[molID] = true
|
||||
}
|
||||
|
|
@ -226,7 +230,10 @@ func findGateReadyMolecules(ctx context.Context, s molReader) ([]*GatedMolecule,
|
|||
}
|
||||
|
||||
// Batch-find molecule roots for all ready dependents
|
||||
depMolRoots := findParentMolecules(ctx, s, readyDepIDs)
|
||||
depMolRoots, err := issueops.MoleculeRoots(ctx, rawMoleculeReader{s: s}.moleculeReader(), readyDepIDs)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("finding molecules of ready steps: %w", err)
|
||||
}
|
||||
|
||||
moleculeMap := make(map[string]*GatedMolecule)
|
||||
for _, gd := range readyDependents {
|
||||
|
|
|
|||
233
cmd/bd/mol_roles.go
Normal file
233
cmd/bd/mol_roles.go
Normal file
|
|
@ -0,0 +1,233 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/storage/uow"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// moleculeRoles is where `bd mol current`, `bd mol progress`, `bd ready --mol`
|
||||
// and `bd close --continue` get their answers on the route this command runs
|
||||
// on. Every field is a library role; the molecule rules (membership, readiness,
|
||||
// progress, the advance and its claim) are the issueops functions composed over
|
||||
// them, so the direct, proxied-server and remote routes answer one way. What
|
||||
// stays in cmd/bd is presentation.
|
||||
type moleculeRoles struct {
|
||||
reader issueops.Reader
|
||||
molecule issueops.MoleculeReader
|
||||
stepper func() (issueops.MoleculeStepper, error)
|
||||
}
|
||||
|
||||
// directMoleculeRoles binds the roles to the opened store: a local backend, or
|
||||
// a registered remote one (http), each through its own accessors.
|
||||
func directMoleculeRoles(s storage.DoltStorage) (moleculeRoles, error) {
|
||||
if s == nil {
|
||||
return moleculeRoles{}, errors.New("no database connection")
|
||||
}
|
||||
reader, err := s.IssueReader()
|
||||
if err != nil {
|
||||
return moleculeRoles{}, err
|
||||
}
|
||||
molecule, err := issueops.NewMoleculeReader(s)
|
||||
if err != nil {
|
||||
return moleculeRoles{}, err
|
||||
}
|
||||
return moleculeRoles{reader: reader, molecule: molecule, stepper: s.MoleculeStepper}, nil
|
||||
}
|
||||
|
||||
// proxiedMoleculeRoles binds the roles to the proxied server's provider,
|
||||
// through the provider's own accessors (where each of its layers is added).
|
||||
func proxiedMoleculeRoles() (moleculeRoles, error) {
|
||||
if uowProvider == nil {
|
||||
return moleculeRoles{}, errors.New("proxied-server UOW provider not initialized")
|
||||
}
|
||||
reader, err := proxiedIssueReader()
|
||||
if err != nil {
|
||||
return moleculeRoles{}, err
|
||||
}
|
||||
src, ok := uowProvider.(interface {
|
||||
BatchGetter() (issueops.BatchGetter, error)
|
||||
IssueRelations() (issueops.Relations, error)
|
||||
EdgeReader() (issueops.EdgeReader, error)
|
||||
})
|
||||
if !ok {
|
||||
return moleculeRoles{}, fmt.Errorf("proxied-server provider %T does not offer the molecule read roles", uowProvider)
|
||||
}
|
||||
molecule, err := issueops.NewMoleculeReader(src)
|
||||
if err != nil {
|
||||
return moleculeRoles{}, err
|
||||
}
|
||||
stepper := func() (issueops.MoleculeStepper, error) {
|
||||
src, ok := uowProvider.(uow.MoleculeStepperSource)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("proxied-server provider %T does not offer the molecule advance", uowProvider)
|
||||
}
|
||||
return src.MoleculeStepper()
|
||||
}
|
||||
return moleculeRoles{reader: reader, molecule: molecule, stepper: stepper}, nil
|
||||
}
|
||||
|
||||
// currentMoleculeRoles picks the route.
|
||||
func currentMoleculeRoles(s storage.DoltStorage) (moleculeRoles, error) {
|
||||
if usesProxiedServer() {
|
||||
return proxiedMoleculeRoles()
|
||||
}
|
||||
return directMoleculeRoles(s)
|
||||
}
|
||||
|
||||
// moleculeProgressOf presents a library MoleculeView as `bd mol current`'s
|
||||
// MoleculeProgress.
|
||||
func moleculeProgressOf(view *issueops.MoleculeView) *MoleculeProgress {
|
||||
root := view.Graph.Root
|
||||
progress := &MoleculeProgress{
|
||||
MoleculeID: root.ID,
|
||||
MoleculeTitle: root.Title,
|
||||
Assignee: root.Assignee,
|
||||
CurrentStep: view.CurrentStep,
|
||||
NextStep: view.NextStep,
|
||||
Completed: view.Completed,
|
||||
Total: view.Total,
|
||||
}
|
||||
for _, step := range view.Steps {
|
||||
progress.Steps = append(progress.Steps, &StepStatus{Issue: step.Issue, Status: step.State, IsCurrent: step.IsCurrent})
|
||||
}
|
||||
return progress
|
||||
}
|
||||
|
||||
// viewMolecules loads and presents each molecule, sorted by id.
|
||||
func viewMolecules(ctx context.Context, roles moleculeRoles, ids []string) ([]*MoleculeProgress, error) {
|
||||
out := make([]*MoleculeProgress, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
view, err := issueops.ViewMolecule(ctx, roles.molecule, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("loading molecule %s: %w", id, err)
|
||||
}
|
||||
out = append(out, moleculeProgressOf(view))
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].MoleculeID < out[j].MoleculeID })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// continueResultOf presents a library AdvanceResult as `bd close --continue`'s
|
||||
// ContinueResult. A step in no molecule presents as nil, as it always has.
|
||||
func continueResultOf(result issueops.AdvanceResult) *ContinueResult {
|
||||
if result.MoleculeID == "" {
|
||||
return nil
|
||||
}
|
||||
return &ContinueResult{
|
||||
ClosedStep: result.ClosedStep,
|
||||
NextStep: result.NextStep,
|
||||
AutoAdvanced: result.Claimed,
|
||||
MolComplete: result.Complete,
|
||||
MoleculeID: result.MoleculeID,
|
||||
}
|
||||
}
|
||||
|
||||
// advanceMolecule runs `bd close --continue` through the route's
|
||||
// MoleculeStepper role.
|
||||
func advanceMolecule(ctx context.Context, roles moleculeRoles, closedStepID string, autoClaim bool) (*ContinueResult, error) {
|
||||
stepper, err := roles.stepper()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, err := stepper.Advance(ctx, issueops.AdvanceRequest{Actor: currentActor(), ClosedStepID: closedStepID, AutoClaim: autoClaim})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return continueResultOf(result), nil
|
||||
}
|
||||
|
||||
// rawMoleculeReader binds the library's molecule rules to a molReader — the
|
||||
// raw-method port the template commands (`mol ready --gated`, pour, bond)
|
||||
// still read through, including the proxied route's in-transaction port. It
|
||||
// is a data binding, like the in-transaction ones in internal/storage: it
|
||||
// answers the three role reads from raw methods and decides nothing.
|
||||
type rawMoleculeReader struct{ s molReader }
|
||||
|
||||
// moleculeReader binds the library's rules to this port.
|
||||
func (r rawMoleculeReader) moleculeReader() issueops.MoleculeReader {
|
||||
return issueops.MoleculeReaderOver(r)
|
||||
}
|
||||
|
||||
func (r rawMoleculeReader) GetMany(ctx context.Context, req issueops.GetManyRequest) (issueops.GetManyResult, error) {
|
||||
issues, err := r.s.GetIssuesByIDs(ctx, req.IDs)
|
||||
if err != nil {
|
||||
return issueops.GetManyResult{}, err
|
||||
}
|
||||
found := make(map[string]*types.Issue, len(issues))
|
||||
for _, issue := range issues {
|
||||
if issue != nil {
|
||||
found[issue.ID] = issue
|
||||
}
|
||||
}
|
||||
out := issueops.GetManyResult{Issues: []*issueops.Issue{}, Missing: []string{}}
|
||||
seen := map[string]bool{}
|
||||
for _, id := range req.IDs {
|
||||
if seen[id] {
|
||||
continue
|
||||
}
|
||||
seen[id] = true
|
||||
if issue := found[id]; issue != nil {
|
||||
out.Issues = append(out.Issues, issue)
|
||||
} else {
|
||||
out.Missing = append(out.Missing, id)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (r rawMoleculeReader) Related(ctx context.Context, req issueops.RelatedRequest) ([]*issueops.RelatedIssue, error) {
|
||||
var (
|
||||
items []*types.IssueWithDependencyMetadata
|
||||
err error
|
||||
)
|
||||
if req.Direction == issueops.RelationIn {
|
||||
items, err = r.s.GetDependentsWithMetadata(ctx, req.ID)
|
||||
} else {
|
||||
return nil, fmt.Errorf("%w: raw molecule reads answer inbound relations only", issueops.ErrValidation)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]*issueops.RelatedIssue, 0, len(items))
|
||||
for _, item := range items {
|
||||
if item != nil && (len(req.Types) == 0 || containsDependencyType(req.Types, item.DependencyType)) {
|
||||
out = append(out, item)
|
||||
}
|
||||
}
|
||||
sort.SliceStable(out, func(i, j int) bool { return out[i].ID < out[j].ID })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (r rawMoleculeReader) ReadEdges(ctx context.Context, req issueops.EdgeReadRequest) (issueops.EdgeReadResult, error) {
|
||||
records, err := r.s.GetDependencyRecordsForIssues(ctx, req.IDs)
|
||||
if err != nil {
|
||||
return issueops.EdgeReadResult{}, err
|
||||
}
|
||||
out := issueops.EdgeReadResult{Anchors: make([]issueops.AnchorEdges, 0, len(req.IDs))}
|
||||
for _, id := range req.IDs {
|
||||
var edges []*issueops.Dependency
|
||||
for _, edge := range records[id] {
|
||||
if edge != nil && (len(req.Types) == 0 || containsDependencyType(req.Types, edge.Type)) {
|
||||
edges = append(edges, edge)
|
||||
}
|
||||
}
|
||||
out.Anchors = append(out.Anchors, issueops.AnchorEdges{ID: id, Edges: edges})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func containsDependencyType(set []types.DependencyType, t types.DependencyType) bool {
|
||||
for _, candidate := range set {
|
||||
if candidate == t {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
140
cmd/bd/mol_route_parity_integration_test.go
Normal file
140
cmd/bd/mol_route_parity_integration_test.go
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
//go:build cgo
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestProxiedServerMoleculeLifecycleAgreesOnEveryRoute drives one molecule
|
||||
// lifecycle — `bd create --parent`, `bd close --continue`, `bd ready --mol`,
|
||||
// `bd mol current`, `bd mol progress` and the auto-close after the last step —
|
||||
// through the real bd binary on the three routes a workspace can take:
|
||||
//
|
||||
// - direct: a server-mode workspace, the CLI on the opened store;
|
||||
// - proxied: a --proxied-server workspace, the CLI on the provider;
|
||||
// - remote: `bd connect` to a `bd serve` of a third server-mode workspace.
|
||||
//
|
||||
// Each step of the lifecycle has ONE library entry (issueops), so every route
|
||||
// must leave the same rows behind and print the same JSON, timestamps aside.
|
||||
// The fixture puts a ready step that ANOTHER actor holds first in line, which is
|
||||
// the case the old direct route got wrong (a status-only claim that took it).
|
||||
func TestProxiedServerMoleculeLifecycleAgreesOnEveryRoute(t *testing.T) {
|
||||
requireSharedProxiedServer(t)
|
||||
bd := buildEmbeddedBD(t)
|
||||
|
||||
directProject := newServerModeProject(t, bd, "mr")
|
||||
proxiedProject := newSharedProxiedProject(t, bd, "mr")
|
||||
servedProject := newServerModeProject(t, bd, "mr")
|
||||
sp := startServe(t, bd, servedProject.dir, servedProject.env)
|
||||
remoteDir := t.TempDir()
|
||||
initGitRepoAt(t, remoteDir)
|
||||
remoteEnv := bdEnv(remoteDir)
|
||||
|
||||
routes := []moleculeFrontDoorRunner{
|
||||
{name: "direct", dir: directProject.dir, env: func(string) []string { return directProject.env }},
|
||||
{name: "proxied", dir: proxiedProject.dir, env: bdProxiedEnv},
|
||||
{name: "remote", dir: remoteDir, env: func(string) []string { return remoteEnv }},
|
||||
}
|
||||
routes[2].mustRun(t, bd, "connect", "http://"+sp.addr, "--json")
|
||||
|
||||
as := func(args ...string) []string { return append([]string{"--actor", "worker"}, args...) }
|
||||
|
||||
// The fixture. Child ids are minted by the create role on every route.
|
||||
for _, r := range routes {
|
||||
r.mustRun(t, bd, as("create", "Route molecule", "--type", "molecule", "--id", "mr-root")...)
|
||||
for i, title := range []string{"first step", "held step", "free step"} {
|
||||
out := r.mustRun(t, bd, as("create", title, "--type", "task", "--parent", "mr-root", "--json")...)
|
||||
var created struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(strings.TrimSpace(out)), &created); err != nil {
|
||||
t.Fatalf("[%s] parse create: %v\n%s", r.name, err, out)
|
||||
}
|
||||
if want := "mr-root." + string(rune('1'+i)); created.ID != want {
|
||||
t.Fatalf("[%s] create --parent minted %q, want %q", r.name, created.ID, want)
|
||||
}
|
||||
}
|
||||
r.mustRun(t, bd, as("update", "mr-root.1", "--status", "in_progress", "--assignee", "worker")...)
|
||||
r.mustRun(t, bd, as("update", "mr-root.2", "--assignee", "someone-else")...)
|
||||
}
|
||||
|
||||
compare := func(t *testing.T, name string, args ...string) {
|
||||
t.Helper()
|
||||
var first any
|
||||
for i, r := range routes {
|
||||
got := dropMoleculeRouteRevisions(normalizedMoleculeJSON(t, r.mustRun(t, bd, as(args...)...)))
|
||||
if i == 0 {
|
||||
first = got
|
||||
continue
|
||||
}
|
||||
if !reflect.DeepEqual(first, got) {
|
||||
t.Errorf("%s diverged: %s answered\n%v\n%s answered\n%v", name, routes[0].name, first, r.name, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
compare(t, "mol current", "mol", "current", "mr-root", "--json")
|
||||
compare(t, "mol progress", "mol", "progress", "mr-root", "--json")
|
||||
compare(t, "ready --mol", "ready", "--mol", "mr-root", "--json")
|
||||
|
||||
// close --continue: the next ready step is mr-root.2, but someone else
|
||||
// holds it, so the advance claims mr-root.3 for worker and leaves .2 alone.
|
||||
compare(t, "close --continue", "close", "mr-root.1", "--continue", "--json")
|
||||
for _, r := range routes {
|
||||
assertMoleculeRouteRow(t, bd, r, "mr-root.2", "open", "someone-else")
|
||||
assertMoleculeRouteRow(t, bd, r, "mr-root.3", "in_progress", "worker")
|
||||
assertMoleculeRouteRow(t, bd, r, "mr-root", "open", "")
|
||||
}
|
||||
|
||||
// Closing the last two steps closes the root, in the close's own
|
||||
// transaction, on every route.
|
||||
compare(t, "close free step", "close", "mr-root.3", "--json")
|
||||
compare(t, "close held step", "close", "mr-root.2", "--force", "--json")
|
||||
for _, r := range routes {
|
||||
assertMoleculeRouteRow(t, bd, r, "mr-root", "closed", "")
|
||||
out := r.mustRun(t, bd, "show", "mr-root", "--json")
|
||||
if !strings.Contains(out, `"close_reason": "all steps complete"`) && !strings.Contains(out, `"close_reason":"all steps complete"`) {
|
||||
t.Errorf("[%s] root close_reason is not the auto-close's:\n%s", r.name, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func assertMoleculeRouteRow(t *testing.T, bd string, r moleculeFrontDoorRunner, id, status, assignee string) {
|
||||
t.Helper()
|
||||
out := r.mustRun(t, bd, "show", id, "--json")
|
||||
var rows []struct {
|
||||
Status string `json:"status"`
|
||||
Assignee string `json:"assignee"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(strings.TrimSpace(out)), &rows); err != nil || len(rows) != 1 {
|
||||
t.Fatalf("[%s] parse show %s: %v\n%s", r.name, id, err, out)
|
||||
}
|
||||
if rows[0].Status != status || rows[0].Assignee != assignee {
|
||||
t.Errorf("[%s] %s = %s/%q, want %s/%q", r.name, id, rows[0].Status, rows[0].Assignee, status, assignee)
|
||||
}
|
||||
}
|
||||
|
||||
// dropMoleculeRouteRevisions removes the opaque row-version tokens, which each
|
||||
// database mints on its own, and the lease's wall-clock fields.
|
||||
func dropMoleculeRouteRevisions(value any) any {
|
||||
switch v := value.(type) {
|
||||
case []any:
|
||||
for i := range v {
|
||||
v[i] = dropMoleculeRouteRevisions(v[i])
|
||||
}
|
||||
case map[string]any:
|
||||
// The claim's lease clock is wall time, like the timestamps the shared
|
||||
// normalizer already drops.
|
||||
for _, key := range []string{"revision", "heartbeat_at", "lease_expires_at"} {
|
||||
delete(v, key)
|
||||
}
|
||||
for key, item := range v {
|
||||
v[key] = dropMoleculeRouteRevisions(item)
|
||||
}
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
|
@ -10,6 +10,7 @@ import (
|
|||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/internal/ui"
|
||||
"github.com/steveyegge/beads/internal/utils"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
var (
|
||||
|
|
@ -21,6 +22,10 @@ var molShowCmd = &cobra.Command{
|
|||
Short: "Show molecule details",
|
||||
Long: `Show molecule structure and details.
|
||||
|
||||
A molecule's steps are the issues linked to its root by parent-child
|
||||
dependencies (bd create --parent, bd mol pour); an id that merely looks
|
||||
hierarchical, like bd-xyz.4, does not make an issue a step.
|
||||
|
||||
The --parallel flag highlights parallelizable steps:
|
||||
- Steps with no blocking dependencies can run in parallel
|
||||
- Shows which steps are ready to start now
|
||||
|
|
@ -54,18 +59,35 @@ Example:
|
|||
return HandleErrorRespectJSON("molecule '%s' not found", args[0])
|
||||
}
|
||||
|
||||
subgraph, err := loadTemplateSubgraph(ctx, store, moleculeID)
|
||||
roles, err := directMoleculeRoles(store)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("loading molecule: %v", err)
|
||||
}
|
||||
|
||||
if molShowParallel {
|
||||
return showMoleculeWithParallel(subgraph)
|
||||
}
|
||||
return showMolecule(subgraph)
|
||||
return runMolShow(ctx, roles, moleculeID)
|
||||
},
|
||||
}
|
||||
|
||||
// runMolShow loads the molecule through the library's one molecule read
|
||||
// (issueops.LoadMolecule, over the route's roles) and renders it. Membership
|
||||
// is the parent-child edge on every route, as for mol current, mol progress
|
||||
// and ready --mol.
|
||||
func runMolShow(ctx context.Context, roles moleculeRoles, moleculeID string) error {
|
||||
graph, err := issueops.LoadMolecule(ctx, roles.molecule, moleculeID)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("loading molecule: %v", err)
|
||||
}
|
||||
subgraph := &MoleculeSubgraph{
|
||||
Root: graph.Root,
|
||||
Issues: graph.Issues,
|
||||
Dependencies: graph.Dependencies,
|
||||
IssueMap: graph.IssueMap,
|
||||
}
|
||||
if molShowParallel {
|
||||
return showMoleculeWithParallel(subgraph)
|
||||
}
|
||||
return showMolecule(subgraph)
|
||||
}
|
||||
|
||||
func showMolecule(subgraph *MoleculeSubgraph) error {
|
||||
if jsonOutput {
|
||||
return outputJSON(map[string]interface{}{
|
||||
|
|
@ -150,272 +172,22 @@ func formatBondType(bondType string) string {
|
|||
}
|
||||
}
|
||||
|
||||
// ParallelInfo holds parallel analysis information for a step
|
||||
type ParallelInfo struct {
|
||||
StepID string `json:"step_id"`
|
||||
Status string `json:"status"`
|
||||
IsReady bool `json:"is_ready"` // Can start now (no blocking deps)
|
||||
ParallelGroup string `json:"parallel_group"` // Group ID (steps with same group can parallelize)
|
||||
BlockedBy []string `json:"blocked_by"` // IDs of open steps blocking this one
|
||||
Blocks []string `json:"blocks"` // IDs of steps this one blocks
|
||||
CanParallel []string `json:"can_parallel"` // IDs of steps that can run in parallel with this
|
||||
}
|
||||
// ParallelInfo is a step's readiness and parallelism, as the library's
|
||||
// molecule analysis answers it.
|
||||
type ParallelInfo = issueops.MoleculeStepInfo
|
||||
|
||||
// ParallelAnalysis holds the complete parallel analysis for a molecule
|
||||
type ParallelAnalysis struct {
|
||||
MoleculeID string `json:"molecule_id"`
|
||||
TotalSteps int `json:"total_steps"`
|
||||
ReadySteps int `json:"ready_steps"`
|
||||
ParallelGroups map[string][]string `json:"parallel_groups"` // group ID -> step IDs
|
||||
Steps map[string]*ParallelInfo `json:"steps"`
|
||||
}
|
||||
// ParallelAnalysis is the readiness and parallelism of a whole molecule.
|
||||
type ParallelAnalysis = issueops.MoleculeAnalysis
|
||||
|
||||
// analyzeMoleculeParallel performs parallel detection on a molecule subgraph.
|
||||
// Returns analysis of which steps can run in parallel.
|
||||
// analyzeMoleculeParallel runs the library's molecule analysis
|
||||
// (issueops.AnalyzeMolecule) over a loaded template subgraph.
|
||||
func analyzeMoleculeParallel(subgraph *MoleculeSubgraph) *ParallelAnalysis {
|
||||
analysis := &ParallelAnalysis{
|
||||
MoleculeID: subgraph.Root.ID,
|
||||
TotalSteps: len(subgraph.Issues),
|
||||
ParallelGroups: make(map[string][]string),
|
||||
Steps: make(map[string]*ParallelInfo),
|
||||
}
|
||||
|
||||
// Build dependency maps
|
||||
// blockedBy[id] = set of issue IDs that block this issue
|
||||
// blocks[id] = set of issue IDs that this issue blocks
|
||||
blockedBy := make(map[string]map[string]bool)
|
||||
blocks := make(map[string]map[string]bool)
|
||||
parentChildren := make(map[string][]string)
|
||||
|
||||
for _, issue := range subgraph.Issues {
|
||||
blockedBy[issue.ID] = make(map[string]bool)
|
||||
blocks[issue.ID] = make(map[string]bool)
|
||||
}
|
||||
|
||||
// Build child index for waits-for gate evaluation.
|
||||
for _, dep := range subgraph.Dependencies {
|
||||
if dep.Type == types.DepParentChild {
|
||||
parentChildren[dep.DependsOnID] = append(parentChildren[dep.DependsOnID], dep.IssueID)
|
||||
}
|
||||
}
|
||||
|
||||
// Process dependencies to find blocking relationships
|
||||
for _, dep := range subgraph.Dependencies {
|
||||
switch dep.Type {
|
||||
case types.DepBlocks, types.DepConditionalBlocks:
|
||||
// dep.IssueID depends on (is blocked by) dep.DependsOnID
|
||||
if _, ok := blockedBy[dep.IssueID]; ok {
|
||||
blockedBy[dep.IssueID][dep.DependsOnID] = true
|
||||
}
|
||||
if _, ok := blocks[dep.DependsOnID]; ok {
|
||||
blocks[dep.DependsOnID][dep.IssueID] = true
|
||||
}
|
||||
case types.DepWaitsFor:
|
||||
children := parentChildren[dep.DependsOnID]
|
||||
if len(children) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
gate := types.ParseWaitsForGateMetadata(dep.Metadata)
|
||||
if gate == types.WaitsForAnyChildren {
|
||||
hasClosedChild := false
|
||||
for _, childID := range children {
|
||||
child := subgraph.IssueMap[childID]
|
||||
if child != nil && child.Status == types.StatusClosed {
|
||||
hasClosedChild = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if hasClosedChild {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// For all-children (and unresolved any-children), each open child blocks the gate.
|
||||
for _, childID := range children {
|
||||
child := subgraph.IssueMap[childID]
|
||||
if child == nil || child.Status == types.StatusClosed {
|
||||
continue
|
||||
}
|
||||
|
||||
if _, ok := blockedBy[dep.IssueID]; ok {
|
||||
blockedBy[dep.IssueID][childID] = true
|
||||
}
|
||||
if _, ok := blocks[childID]; ok {
|
||||
blocks[childID][dep.IssueID] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Identify which steps are ready (no open blockers)
|
||||
readySteps := make(map[string]bool)
|
||||
for _, issue := range subgraph.Issues {
|
||||
info := &ParallelInfo{
|
||||
StepID: issue.ID,
|
||||
Status: string(issue.Status),
|
||||
BlockedBy: []string{},
|
||||
Blocks: []string{},
|
||||
}
|
||||
|
||||
// Check what blocks this step
|
||||
for blockerID := range blockedBy[issue.ID] {
|
||||
blocker := subgraph.IssueMap[blockerID]
|
||||
if blocker != nil && blocker.Status != types.StatusClosed {
|
||||
info.BlockedBy = append(info.BlockedBy, blockerID)
|
||||
}
|
||||
}
|
||||
|
||||
// Check what this step blocks
|
||||
for blockedID := range blocks[issue.ID] {
|
||||
info.Blocks = append(info.Blocks, blockedID)
|
||||
}
|
||||
|
||||
// A step is ready if it's open/in_progress and has no open blockers
|
||||
info.IsReady = (issue.Status == types.StatusOpen || issue.Status == types.StatusInProgress) &&
|
||||
len(info.BlockedBy) == 0
|
||||
|
||||
if info.IsReady {
|
||||
readySteps[issue.ID] = true
|
||||
analysis.ReadySteps++
|
||||
}
|
||||
|
||||
// Sort for consistent output
|
||||
sort.Strings(info.BlockedBy)
|
||||
sort.Strings(info.Blocks)
|
||||
|
||||
analysis.Steps[issue.ID] = info
|
||||
}
|
||||
|
||||
// Identify parallel groups: steps that can run concurrently
|
||||
// Two steps can parallelize if:
|
||||
// 1. Both are ready (or will be ready at same time)
|
||||
// 2. Neither blocks the other (directly or transitively)
|
||||
// 3. They share the same blocking depth (distance from root)
|
||||
|
||||
// Calculate blocking depth for each step
|
||||
depths := calculateBlockingDepths(subgraph, blockedBy)
|
||||
|
||||
// Group steps by depth - steps at same depth can potentially parallelize
|
||||
depthGroups := make(map[int][]string)
|
||||
for id, depth := range depths {
|
||||
depthGroups[depth] = append(depthGroups[depth], id)
|
||||
}
|
||||
|
||||
// For each depth level, identify parallel groups
|
||||
groupCounter := 0
|
||||
for depth := 0; depth <= len(subgraph.Issues); depth++ {
|
||||
stepsAtDepth := depthGroups[depth]
|
||||
if len(stepsAtDepth) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
// Group steps that can parallelize (no blocking between them)
|
||||
// Use union-find approach: start with each step in its own group
|
||||
parent := make(map[string]string)
|
||||
for _, id := range stepsAtDepth {
|
||||
parent[id] = id
|
||||
}
|
||||
|
||||
find := func(x string) string {
|
||||
for parent[x] != x {
|
||||
parent[x] = parent[parent[x]]
|
||||
x = parent[x]
|
||||
}
|
||||
return x
|
||||
}
|
||||
|
||||
union := func(x, y string) {
|
||||
px, py := find(x), find(y)
|
||||
if px != py {
|
||||
parent[px] = py
|
||||
}
|
||||
}
|
||||
|
||||
// Merge steps that CAN parallelize (no mutual blocking)
|
||||
for i, id1 := range stepsAtDepth {
|
||||
for j := i + 1; j < len(stepsAtDepth); j++ {
|
||||
id2 := stepsAtDepth[j]
|
||||
// Can parallelize if neither blocks the other
|
||||
if !blocks[id1][id2] && !blocks[id2][id1] &&
|
||||
!blockedBy[id1][id2] && !blockedBy[id2][id1] {
|
||||
union(id1, id2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Collect groups
|
||||
groups := make(map[string][]string)
|
||||
for _, id := range stepsAtDepth {
|
||||
root := find(id)
|
||||
groups[root] = append(groups[root], id)
|
||||
}
|
||||
|
||||
// Assign group names and record can_parallel relationships
|
||||
for _, members := range groups {
|
||||
if len(members) > 1 {
|
||||
groupCounter++
|
||||
groupName := fmt.Sprintf("group-%d", groupCounter)
|
||||
analysis.ParallelGroups[groupName] = members
|
||||
|
||||
// Update each step's parallel info
|
||||
for _, id := range members {
|
||||
info := analysis.Steps[id]
|
||||
info.ParallelGroup = groupName
|
||||
// Record all other members as can_parallel
|
||||
for _, otherId := range members {
|
||||
if otherId != id {
|
||||
info.CanParallel = append(info.CanParallel, otherId)
|
||||
}
|
||||
}
|
||||
sort.Strings(info.CanParallel)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return analysis
|
||||
}
|
||||
|
||||
// calculateBlockingDepths calculates the "blocking depth" of each step.
|
||||
// Depth 0 = no blockers, Depth 1 = blocked by depth-0 steps, etc.
|
||||
func calculateBlockingDepths(subgraph *MoleculeSubgraph, blockedBy map[string]map[string]bool) map[string]int {
|
||||
depths := make(map[string]int)
|
||||
visited := make(map[string]bool)
|
||||
|
||||
var calculateDepth func(id string) int
|
||||
calculateDepth = func(id string) int {
|
||||
if d, ok := depths[id]; ok {
|
||||
return d
|
||||
}
|
||||
if visited[id] {
|
||||
// Cycle detected, return 0 to break
|
||||
return 0
|
||||
}
|
||||
visited[id] = true
|
||||
|
||||
maxBlockerDepth := -1
|
||||
for blockerID := range blockedBy[id] {
|
||||
// Only count open blockers
|
||||
blocker := subgraph.IssueMap[blockerID]
|
||||
if blocker != nil && blocker.Status != types.StatusClosed {
|
||||
blockerDepth := calculateDepth(blockerID)
|
||||
if blockerDepth > maxBlockerDepth {
|
||||
maxBlockerDepth = blockerDepth
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
depth := maxBlockerDepth + 1
|
||||
depths[id] = depth
|
||||
return depth
|
||||
}
|
||||
|
||||
for _, issue := range subgraph.Issues {
|
||||
calculateDepth(issue.ID)
|
||||
}
|
||||
|
||||
return depths
|
||||
return issueops.AnalyzeMolecule(&issueops.MoleculeGraph{
|
||||
Root: subgraph.Root,
|
||||
Issues: subgraph.Issues,
|
||||
Dependencies: subgraph.Dependencies,
|
||||
IssueMap: subgraph.IssueMap,
|
||||
})
|
||||
}
|
||||
|
||||
func showMoleculeWithParallel(subgraph *MoleculeSubgraph) error {
|
||||
|
|
|
|||
|
|
@ -3,8 +3,14 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage/uow"
|
||||
)
|
||||
|
||||
func TestProxiedServerMolShow(t *testing.T) {
|
||||
|
|
@ -96,3 +102,111 @@ func TestProxiedServerMolShow(t *testing.T) {
|
|||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestProxiedMolResolveReportsAnUnopenableReadAsItself pins that the proxied
|
||||
// molecule resolver (proxiedResolvePartialID: mol show, current, progress and
|
||||
// ready --mol) reports a read unit of work it cannot open as that failure,
|
||||
// never as a molecule that was not found, while an id the lookup does not find
|
||||
// still reads as not found (moleculeNotResolved).
|
||||
func TestProxiedMolResolveReportsAnUnopenableReadAsItself(t *testing.T) {
|
||||
oldProvider := uowProvider
|
||||
t.Cleanup(func() { uowProvider = oldProvider })
|
||||
uowProvider = nil
|
||||
ctx := context.Background()
|
||||
const unopenable = "proxied-server UOW provider not initialized"
|
||||
|
||||
var resolveErr error
|
||||
stderr := captureStderr(t, func() {
|
||||
_, resolveErr = proxiedResolvePartialID(ctx, "mol-x")
|
||||
})
|
||||
var reported reportedResolveError
|
||||
if !errors.As(resolveErr, &reported) {
|
||||
t.Fatalf("proxiedResolvePartialID error = %v, want a reportedResolveError", resolveErr)
|
||||
}
|
||||
if !strings.Contains(stderr, unopenable) {
|
||||
t.Errorf("proxiedResolvePartialID stderr = %q, want the open failure %q", stderr, unopenable)
|
||||
}
|
||||
|
||||
stderr = captureStderr(t, func() {
|
||||
if got := moleculeNotResolved("mol-x", resolveErr); !errors.Is(got, reported.err) {
|
||||
t.Errorf("moleculeNotResolved = %v, want the already-reported %v", got, reported.err)
|
||||
}
|
||||
})
|
||||
if stderr != "" {
|
||||
t.Errorf("moleculeNotResolved reported an already-reported failure again: %q", stderr)
|
||||
}
|
||||
|
||||
stderr = captureStderr(t, func() {
|
||||
_ = moleculeNotResolved("mol-x", errors.New("no issue found matching \"mol-x\""))
|
||||
})
|
||||
if !strings.Contains(stderr, "molecule 'mol-x' not found") {
|
||||
t.Errorf("an id the lookup did not find reported %q, want molecule 'mol-x' not found", stderr)
|
||||
}
|
||||
|
||||
var showErr error
|
||||
stderr = captureStderr(t, func() { showErr = runMolShowProxiedServer(ctx, "mol-x") })
|
||||
if showErr == nil || !strings.Contains(stderr, unopenable) || strings.Contains(stderr, "not found") {
|
||||
t.Errorf("mol show over an unopenable read: err = %v, stderr = %q; want the open failure, not \"not found\"", showErr, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// unopenableUOWProvider fails every NewUOW, as a proxied route's provider does
|
||||
// when the server cannot be reached.
|
||||
type unopenableUOWProvider struct{ err error }
|
||||
|
||||
func (p unopenableUOWProvider) NewUOW(context.Context) (uow.UnitOfWork, error) { return nil, p.err }
|
||||
func (unopenableUOWProvider) Close(context.Context) error { return nil }
|
||||
|
||||
// TestProxiedReadyMolReportsAnUnopenableReadOnce pins `bd ready --mol` on the
|
||||
// proxied route to the resolver contract above: a read unit of work that will
|
||||
// not open is reported once, as itself, and is not followed by a "not found"
|
||||
// for the molecule. Under --json that is one error document on stdout, not two.
|
||||
func TestProxiedReadyMolReportsAnUnopenableReadOnce(t *testing.T) {
|
||||
oldProvider, oldJSON := uowProvider, jsonOutput
|
||||
t.Cleanup(func() { uowProvider, jsonOutput = oldProvider, oldJSON })
|
||||
const openFailure = "connection refused"
|
||||
uowProvider = unopenableUOWProvider{err: errors.New(openFailure)}
|
||||
ctx := context.Background()
|
||||
|
||||
t.Run("text", func(t *testing.T) {
|
||||
jsonOutput = false
|
||||
var readyErr error
|
||||
stderr := captureStderr(t, func() {
|
||||
readyErr = runMoleculeReady(ctx, nil, proxiedResolvePartialID, "mol-x")
|
||||
})
|
||||
if readyErr == nil {
|
||||
t.Error("runMoleculeReady over an unopenable read returned nil")
|
||||
}
|
||||
if strings.Count(stderr, "Error:") != 1 || !strings.Contains(stderr, openFailure) || strings.Contains(stderr, "not found") {
|
||||
t.Errorf("stderr = %q; want one Error: line reporting the open failure, not \"not found\"", stderr)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("json", func(t *testing.T) {
|
||||
jsonOutput = true
|
||||
var readyErr error
|
||||
stdout := captureStdout(t, func() error {
|
||||
readyErr = runMoleculeReady(ctx, nil, proxiedResolvePartialID, "mol-x")
|
||||
return nil
|
||||
})
|
||||
if readyErr == nil {
|
||||
t.Error("runMoleculeReady over an unopenable read returned nil")
|
||||
}
|
||||
dec := json.NewDecoder(strings.NewReader(stdout))
|
||||
docs := 0
|
||||
for {
|
||||
var doc map[string]any
|
||||
err := dec.Decode(&doc)
|
||||
if errors.Is(err, io.EOF) {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("stdout is not a JSON document stream: %v\n%s", err, stdout)
|
||||
}
|
||||
docs++
|
||||
}
|
||||
if docs != 1 || !strings.Contains(stdout, openFailure) || strings.Contains(stdout, "not found") {
|
||||
t.Errorf("stdout carries %d JSON documents:\n%s\nwant one, reporting the open failure, not \"not found\"", docs, stdout)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,7 +9,9 @@ import (
|
|||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/formula"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
func TestParseDistillVar(t *testing.T) {
|
||||
|
|
@ -1400,7 +1402,7 @@ func TestGetMoleculeProgress(t *testing.T) {
|
|||
}
|
||||
|
||||
// Get progress
|
||||
progress, err := getMoleculeProgress(ctx, s, root.ID)
|
||||
progress, err := viewMoleculeProgress(ctx, s, root.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("getMoleculeProgress failed: %v", err)
|
||||
}
|
||||
|
|
@ -1486,19 +1488,19 @@ func TestFindParentMolecule(t *testing.T) {
|
|||
}
|
||||
|
||||
// Find parent molecule from grandchild
|
||||
moleculeID := findParentMolecule(ctx, s, grandchild.ID)
|
||||
moleculeID := mustFindParentMolecule(t, ctx, s, grandchild.ID)
|
||||
if moleculeID != root.ID {
|
||||
t.Errorf("findParentMolecule(grandchild) = %q, want %q", moleculeID, root.ID)
|
||||
}
|
||||
|
||||
// Find parent molecule from child
|
||||
moleculeID = findParentMolecule(ctx, s, child.ID)
|
||||
moleculeID = mustFindParentMolecule(t, ctx, s, child.ID)
|
||||
if moleculeID != root.ID {
|
||||
t.Errorf("findParentMolecule(child) = %q, want %q", moleculeID, root.ID)
|
||||
}
|
||||
|
||||
// Find parent molecule from root
|
||||
moleculeID = findParentMolecule(ctx, s, root.ID)
|
||||
moleculeID = mustFindParentMolecule(t, ctx, s, root.ID)
|
||||
if moleculeID != root.ID {
|
||||
t.Errorf("findParentMolecule(root) = %q, want %q", moleculeID, root.ID)
|
||||
}
|
||||
|
|
@ -1515,7 +1517,7 @@ func TestFindParentMolecule(t *testing.T) {
|
|||
}
|
||||
|
||||
// Should return empty for orphan
|
||||
moleculeID = findParentMolecule(ctx, s, orphan.ID)
|
||||
moleculeID = mustFindParentMolecule(t, ctx, s, orphan.ID)
|
||||
if moleculeID != "" {
|
||||
t.Errorf("findParentMolecule(orphan) = %q, want empty", moleculeID)
|
||||
}
|
||||
|
|
@ -1587,7 +1589,10 @@ func TestFindParentMoleculesBatch(t *testing.T) {
|
|||
}
|
||||
|
||||
// Batch-find molecule roots for all issues at once
|
||||
roots := findParentMolecules(ctx, s, []string{grandchild.ID, child.ID, root.ID, orphan.ID})
|
||||
roots, err := moleculeRootsOf(ctx, s, []string{grandchild.ID, child.ID, root.ID, orphan.ID})
|
||||
if err != nil {
|
||||
t.Fatalf("findParentMolecules: %v", err)
|
||||
}
|
||||
|
||||
if got := roots[grandchild.ID]; got != root.ID {
|
||||
t.Errorf("findParentMolecules[grandchild] = %q, want %q", got, root.ID)
|
||||
|
|
@ -1602,9 +1607,9 @@ func TestFindParentMoleculesBatch(t *testing.T) {
|
|||
t.Errorf("findParentMolecules[orphan] = %q, want empty", got)
|
||||
}
|
||||
|
||||
// Empty input should return nil
|
||||
if result := findParentMolecules(ctx, s, nil); result != nil {
|
||||
t.Errorf("findParentMolecules(nil) = %v, want nil", result)
|
||||
// Empty input answers no roots.
|
||||
if result, err := moleculeRootsOf(ctx, s, nil); err != nil || len(result) != 0 {
|
||||
t.Errorf("MoleculeRoots(nil) = %v, %v, want none", result, err)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1668,12 +1673,15 @@ func TestFindParentMolecule_RootShapes(t *testing.T) {
|
|||
if tt.isMolecule {
|
||||
wantSingle = root.ID
|
||||
}
|
||||
if got := findParentMolecule(ctx, s, child.ID); got != wantSingle {
|
||||
if got := mustFindParentMolecule(t, ctx, s, child.ID); got != wantSingle {
|
||||
t.Errorf("findParentMolecule(child) = %q, want %q", got, wantSingle)
|
||||
}
|
||||
|
||||
wantBatch := map[string]string{child.ID: wantSingle}
|
||||
gotBatch := findParentMolecules(ctx, s, []string{child.ID})
|
||||
gotBatch, err := moleculeRootsOf(ctx, s, []string{child.ID})
|
||||
if err != nil {
|
||||
t.Fatalf("findParentMolecules: %v", err)
|
||||
}
|
||||
if got := gotBatch[child.ID]; got != wantBatch[child.ID] {
|
||||
t.Errorf("findParentMolecules(child) = %q, want %q", got, wantBatch[child.ID])
|
||||
}
|
||||
|
|
@ -1733,7 +1741,7 @@ func TestAdvanceToNextStep_PouredMolecule(t *testing.T) {
|
|||
t.Fatalf("Failed to add blocking dep: %v", err)
|
||||
}
|
||||
|
||||
result, err := AdvanceToNextStep(ctx, newStandaloneStoreMolWriter(s), step1.ID, true, "test")
|
||||
result, err := advanceForTest(ctx, s, step1.ID, true, "test")
|
||||
if err != nil {
|
||||
t.Fatalf("AdvanceToNextStep failed: %v", err)
|
||||
}
|
||||
|
|
@ -1815,7 +1823,7 @@ func TestFindHookedMolecules(t *testing.T) {
|
|||
}
|
||||
|
||||
// Test: findHookedMolecules should find the molecule for this agent
|
||||
molecules := findHookedMolecules(ctx, s, "test-agent")
|
||||
molecules := mustFindHookedMolecules(t, ctx, s, "test-agent")
|
||||
if len(molecules) != 1 {
|
||||
t.Fatalf("findHookedMolecules() got %d molecules, want 1", len(molecules))
|
||||
}
|
||||
|
|
@ -1824,13 +1832,13 @@ func TestFindHookedMolecules(t *testing.T) {
|
|||
}
|
||||
|
||||
// Test: different agent should not find the molecule
|
||||
molecules = findHookedMolecules(ctx, s, "other-agent")
|
||||
molecules = mustFindHookedMolecules(t, ctx, s, "other-agent")
|
||||
if len(molecules) != 0 {
|
||||
t.Errorf("findHookedMolecules(other-agent) got %d molecules, want 0", len(molecules))
|
||||
}
|
||||
|
||||
// Test: no agent filter should find the molecule
|
||||
molecules = findHookedMolecules(ctx, s, "")
|
||||
molecules = mustFindHookedMolecules(t, ctx, s, "")
|
||||
if len(molecules) != 1 {
|
||||
t.Errorf("findHookedMolecules('') got %d molecules, want 1", len(molecules))
|
||||
}
|
||||
|
|
@ -1890,7 +1898,7 @@ func TestAdvanceToNextStep(t *testing.T) {
|
|||
}
|
||||
|
||||
// Advance from step1 (just closed) without auto-claim
|
||||
result, err := AdvanceToNextStep(ctx, newStandaloneStoreMolWriter(s), step1.ID, false, "test")
|
||||
result, err := advanceForTest(ctx, s, step1.ID, false, "test")
|
||||
if err != nil {
|
||||
t.Fatalf("AdvanceToNextStep failed: %v", err)
|
||||
}
|
||||
|
|
@ -1916,7 +1924,7 @@ func TestAdvanceToNextStep(t *testing.T) {
|
|||
}
|
||||
|
||||
// Now test with auto-claim
|
||||
result, err = AdvanceToNextStep(ctx, newStandaloneStoreMolWriter(s), step1.ID, true, "test")
|
||||
result, err = advanceForTest(ctx, s, step1.ID, true, "test")
|
||||
if err != nil {
|
||||
t.Fatalf("AdvanceToNextStep with auto-claim failed: %v", err)
|
||||
}
|
||||
|
|
@ -1967,7 +1975,7 @@ func TestAdvanceToNextStepMoleculeComplete(t *testing.T) {
|
|||
}
|
||||
|
||||
// Advance from the only step (molecule should be complete)
|
||||
result, err := AdvanceToNextStep(ctx, newStandaloneStoreMolWriter(s), step1.ID, false, "test")
|
||||
result, err := advanceForTest(ctx, s, step1.ID, false, "test")
|
||||
if err != nil {
|
||||
t.Fatalf("AdvanceToNextStep failed: %v", err)
|
||||
}
|
||||
|
|
@ -2000,7 +2008,7 @@ func TestAdvanceToNextStepOrphanIssue(t *testing.T) {
|
|||
}
|
||||
|
||||
// Advance should return nil (not part of molecule)
|
||||
result, err := AdvanceToNextStep(ctx, newStandaloneStoreMolWriter(s), orphan.ID, false, "test")
|
||||
result, err := advanceForTest(ctx, s, orphan.ID, false, "test")
|
||||
if err != nil {
|
||||
t.Fatalf("AdvanceToNextStep failed: %v", err)
|
||||
}
|
||||
|
|
@ -2083,7 +2091,7 @@ func TestAdvanceToNextStepConcurrentClaim(t *testing.T) {
|
|||
// Now our agent tries to advance with autoClaim — step2 was identified as
|
||||
// ready during the read phase, but it's already in_progress. The function
|
||||
// should fall back to step3.
|
||||
result, err := AdvanceToNextStep(ctx, newStandaloneStoreMolWriter(s), step1.ID, true, "our-agent")
|
||||
result, err := advanceForTest(ctx, s, step1.ID, true, "our-agent")
|
||||
if err != nil {
|
||||
t.Fatalf("AdvanceToNextStep failed: %v", err)
|
||||
}
|
||||
|
|
@ -2169,7 +2177,7 @@ func TestAdvanceToNextStepAllClaimed(t *testing.T) {
|
|||
}
|
||||
|
||||
// Advance with autoClaim — should fail gracefully (no steps to claim)
|
||||
result, err := AdvanceToNextStep(ctx, newStandaloneStoreMolWriter(s), step1.ID, true, "our-agent")
|
||||
result, err := advanceForTest(ctx, s, step1.ID, true, "our-agent")
|
||||
if err != nil {
|
||||
t.Fatalf("AdvanceToNextStep failed: %v", err)
|
||||
}
|
||||
|
|
@ -2846,43 +2854,6 @@ func TestAnalyzeMoleculeParallelMultipleArms(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestCalculateBlockingDepths tests the depth calculation
|
||||
func TestCalculateBlockingDepths(t *testing.T) {
|
||||
// Create chain: root -> step1 -> step2 -> step3
|
||||
root := &types.Issue{ID: "root", Status: types.StatusOpen}
|
||||
step1 := &types.Issue{ID: "step1", Status: types.StatusOpen}
|
||||
step2 := &types.Issue{ID: "step2", Status: types.StatusOpen}
|
||||
step3 := &types.Issue{ID: "step3", Status: types.StatusOpen}
|
||||
|
||||
subgraph := &MoleculeSubgraph{
|
||||
Root: root,
|
||||
Issues: []*types.Issue{root, step1, step2, step3},
|
||||
IssueMap: map[string]*types.Issue{"root": root, "step1": step1, "step2": step2, "step3": step3},
|
||||
}
|
||||
|
||||
blockedBy := map[string]map[string]bool{
|
||||
"root": {},
|
||||
"step1": {"root": true},
|
||||
"step2": {"step1": true},
|
||||
"step3": {"step2": true},
|
||||
}
|
||||
|
||||
depths := calculateBlockingDepths(subgraph, blockedBy)
|
||||
|
||||
if depths["root"] != 0 {
|
||||
t.Errorf("root depth = %d, want 0", depths["root"])
|
||||
}
|
||||
if depths["step1"] != 1 {
|
||||
t.Errorf("step1 depth = %d, want 1", depths["step1"])
|
||||
}
|
||||
if depths["step2"] != 2 {
|
||||
t.Errorf("step2 depth = %d, want 2", depths["step2"])
|
||||
}
|
||||
if depths["step3"] != 3 {
|
||||
t.Errorf("step3 depth = %d, want 3", depths["step3"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestSpawnMoleculeEphemeralFlag verifies that spawnMolecule with ephemeral=true
|
||||
// creates issues with the Ephemeral flag set (bd-phin)
|
||||
func TestSpawnMoleculeEphemeralFlag(t *testing.T) {
|
||||
|
|
@ -3370,3 +3341,70 @@ func TestPourRootNoVars(t *testing.T) {
|
|||
t.Errorf("Root description should be formula desc, got: %q", spawnedRoot.Description)
|
||||
}
|
||||
}
|
||||
|
||||
// The molecule tests below drive the library's molecule rules through the
|
||||
// store's own roles — the path every route takes — via these thin shims.
|
||||
|
||||
func testMolRoles(t *testing.T, s storage.DoltStorage) moleculeRoles {
|
||||
t.Helper()
|
||||
roles, err := directMoleculeRoles(s)
|
||||
if err != nil {
|
||||
t.Fatalf("directMoleculeRoles: %v", err)
|
||||
}
|
||||
return roles
|
||||
}
|
||||
|
||||
func mustFindParentMolecule(t *testing.T, ctx context.Context, s storage.DoltStorage, id string) string {
|
||||
t.Helper()
|
||||
got, err := issueops.MoleculeRoot(ctx, testMolRoles(t, s).molecule, id)
|
||||
if err != nil {
|
||||
t.Fatalf("MoleculeRoot(%s): %v", id, err)
|
||||
}
|
||||
return got
|
||||
}
|
||||
|
||||
func moleculeRootsOf(ctx context.Context, s storage.DoltStorage, ids []string) (map[string]string, error) {
|
||||
roles, err := directMoleculeRoles(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return issueops.MoleculeRoots(ctx, roles.molecule, ids)
|
||||
}
|
||||
|
||||
func viewMoleculeProgress(ctx context.Context, s storage.DoltStorage, id string) (*MoleculeProgress, error) {
|
||||
roles, err := directMoleculeRoles(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
view, err := issueops.ViewMolecule(ctx, roles.molecule, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return moleculeProgressOf(view), nil
|
||||
}
|
||||
|
||||
func mustFindHookedMolecules(t *testing.T, ctx context.Context, s storage.DoltStorage, agent string) []*MoleculeProgress {
|
||||
t.Helper()
|
||||
roles := testMolRoles(t, s)
|
||||
ids, err := issueops.ActiveMoleculeIDs(ctx, roles.reader, roles.molecule, agent)
|
||||
if err != nil {
|
||||
t.Fatalf("ActiveMoleculeIDs(%q): %v", agent, err)
|
||||
}
|
||||
got, err := viewMolecules(ctx, roles, ids)
|
||||
if err != nil {
|
||||
t.Fatalf("viewMolecules(%q): %v", agent, err)
|
||||
}
|
||||
return got
|
||||
}
|
||||
|
||||
func advanceForTest(ctx context.Context, s storage.DoltStorage, closedStepID string, autoClaim bool, actor string) (*ContinueResult, error) {
|
||||
stepper, err := s.MoleculeStepper()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, err := stepper.Advance(ctx, issueops.AdvanceRequest{Actor: actor, ClosedStepID: closedStepID, AutoClaim: autoClaim})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return continueResultOf(result), nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -97,7 +97,13 @@ This is useful for agents executing molecules to see which steps can run next.`,
|
|||
if claimReady {
|
||||
return HandleErrorRespectJSON("--claim cannot be combined with --mol")
|
||||
}
|
||||
return runMoleculeReady(cmd, molID)
|
||||
if store == nil {
|
||||
return HandleErrorRespectJSON("no database connection")
|
||||
}
|
||||
resolve := func(ctx context.Context, arg string) (string, error) {
|
||||
return utils.ResolvePartialID(ctx, store, arg)
|
||||
}
|
||||
return runMoleculeReady(rootCtx, store, resolve, molID)
|
||||
}
|
||||
|
||||
explain, _ := cmd.Flags().GetBool("explain")
|
||||
|
|
@ -637,37 +643,32 @@ func runReadyExplain(_ *cobra.Command) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func runMoleculeReady(_ *cobra.Command, molIDArg string) error {
|
||||
ctx := rootCtx
|
||||
|
||||
if store == nil {
|
||||
return HandleErrorRespectJSON("no database connection")
|
||||
}
|
||||
|
||||
moleculeID, err := utils.ResolvePartialID(ctx, store, molIDArg)
|
||||
// runMoleculeReady is `bd ready --mol` on every route. The molecule's nodes,
|
||||
// their readiness, the ready list and parallel groups are the library's one
|
||||
// derivation (issueops.ViewMolecule, shared with `mol current`); what is here
|
||||
// is presentation.
|
||||
func runMoleculeReady(ctx context.Context, s storage.DoltStorage, resolve func(context.Context, string) (string, error), molIDArg string) error {
|
||||
moleculeID, err := resolve(ctx, molIDArg)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("molecule '%s' not found", molIDArg)
|
||||
return moleculeNotResolved(molIDArg, err)
|
||||
}
|
||||
|
||||
subgraph, err := loadTemplateSubgraph(ctx, store, moleculeID)
|
||||
roles, err := currentMoleculeRoles(s)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
view, err := issueops.ViewMolecule(ctx, roles.molecule, moleculeID)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("loading molecule: %v", err)
|
||||
}
|
||||
|
||||
// Get parallel analysis to find ready steps
|
||||
analysis := analyzeMoleculeParallel(subgraph)
|
||||
|
||||
// Collect ready steps
|
||||
subgraph, analysis := view.Graph, view.Analysis
|
||||
var readySteps []*MoleculeReadyStep
|
||||
for _, issue := range subgraph.Issues {
|
||||
for _, issue := range view.Ready {
|
||||
info := analysis.Steps[issue.ID]
|
||||
if info != nil && info.IsReady {
|
||||
readySteps = append(readySteps, &MoleculeReadyStep{
|
||||
Issue: issue,
|
||||
ParallelInfo: info,
|
||||
ParallelGroup: info.ParallelGroup,
|
||||
})
|
||||
}
|
||||
readySteps = append(readySteps, &MoleculeReadyStep{
|
||||
Issue: issue,
|
||||
ParallelInfo: info,
|
||||
ParallelGroup: info.ParallelGroup,
|
||||
})
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
|
|
|
|||
|
|
@ -53,6 +53,12 @@ func runReadyProxiedServer(cmd *cobra.Command, ctx context.Context) error {
|
|||
// same sweep from its role (uow.readyClaimer.ClaimNext).
|
||||
uow.WakeExpiredDefersAdvisory(ctx, uowProvider)
|
||||
|
||||
// --mol reads through the provider's roles, each in a unit of work of its
|
||||
// own, so it runs before this route opens the one it holds below.
|
||||
if in.molID != "" {
|
||||
return runMoleculeReady(ctx, nil, proxiedResolvePartialID, in.molID)
|
||||
}
|
||||
|
||||
uw, err := uowProvider.NewUOW(ctx)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("open unit of work: %v", err)
|
||||
|
|
@ -62,8 +68,6 @@ func runReadyProxiedServer(cmd *cobra.Command, ctx context.Context) error {
|
|||
switch {
|
||||
case in.gated:
|
||||
return runReadyProxiedGated(ctx, uw, in)
|
||||
case in.molID != "":
|
||||
return runReadyProxiedMolecule(ctx, uw, in)
|
||||
case in.explain:
|
||||
return runReadyProxiedExplain(ctx, uw, in)
|
||||
default:
|
||||
|
|
@ -397,89 +401,6 @@ func runReadyProxiedExplain(ctx context.Context, uw uow.UnitOfWork, _ readyInput
|
|||
return nil
|
||||
}
|
||||
|
||||
func runReadyProxiedMolecule(ctx context.Context, uw uow.UnitOfWork, in readyInput) error {
|
||||
moleculeID := in.molID
|
||||
subgraph, err := loadTemplateSubgraph(ctx, uowMolReader{uw: uw}, moleculeID)
|
||||
if err != nil {
|
||||
return HandleError("loading molecule: %v", err)
|
||||
}
|
||||
|
||||
analysis := analyzeMoleculeParallel(subgraph)
|
||||
|
||||
var readySteps []*MoleculeReadyStep
|
||||
for _, issue := range subgraph.Issues {
|
||||
info := analysis.Steps[issue.ID]
|
||||
if info != nil && info.IsReady {
|
||||
readySteps = append(readySteps, &MoleculeReadyStep{
|
||||
Issue: issue,
|
||||
ParallelInfo: info,
|
||||
ParallelGroup: info.ParallelGroup,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if in.jsonOut {
|
||||
output := MoleculeReadyOutput{
|
||||
MoleculeID: moleculeID,
|
||||
MoleculeTitle: subgraph.Root.Title,
|
||||
TotalSteps: analysis.TotalSteps,
|
||||
ReadySteps: len(readySteps),
|
||||
Steps: readySteps,
|
||||
ParallelGroups: analysis.ParallelGroups,
|
||||
}
|
||||
_ = outputJSON(output)
|
||||
return nil
|
||||
}
|
||||
|
||||
fmt.Printf("\n%s Ready steps in molecule: %s\n", ui.RenderAccent("🧪"), subgraph.Root.Title)
|
||||
fmt.Printf(" ID: %s\n", moleculeID)
|
||||
fmt.Printf(" Total: %d steps, %d ready\n", analysis.TotalSteps, len(readySteps))
|
||||
if len(readySteps) == 0 {
|
||||
fmt.Printf("\n%s No ready steps (all blocked or completed)\n\n", ui.RenderWarn("✨"))
|
||||
return nil
|
||||
}
|
||||
if len(analysis.ParallelGroups) > 0 {
|
||||
fmt.Printf("\n%s Parallel Groups:\n", ui.RenderPass("⚡"))
|
||||
for groupName, members := range analysis.ParallelGroups {
|
||||
readyInGroup := 0
|
||||
for _, id := range members {
|
||||
if info := analysis.Steps[id]; info != nil && info.IsReady {
|
||||
readyInGroup++
|
||||
}
|
||||
}
|
||||
if readyInGroup > 0 {
|
||||
fmt.Printf(" %s: %d ready\n", groupName, readyInGroup)
|
||||
}
|
||||
}
|
||||
}
|
||||
fmt.Printf("\n%s Ready steps:\n\n", ui.RenderPass("📋"))
|
||||
for i, step := range readySteps {
|
||||
groupAnnotation := ""
|
||||
if step.ParallelGroup != "" {
|
||||
groupAnnotation = fmt.Sprintf(" [%s]", ui.RenderAccent(step.ParallelGroup))
|
||||
}
|
||||
fmt.Printf("%d. [%s] [%s] %s: %s%s\n", i+1,
|
||||
ui.RenderPriority(step.Issue.Priority),
|
||||
ui.RenderType(string(step.Issue.IssueType)),
|
||||
ui.RenderID(step.Issue.ID),
|
||||
step.Issue.Title,
|
||||
groupAnnotation)
|
||||
if len(step.ParallelInfo.CanParallel) > 0 {
|
||||
readyParallel := []string{}
|
||||
for _, pID := range step.ParallelInfo.CanParallel {
|
||||
if pInfo := analysis.Steps[pID]; pInfo != nil && pInfo.IsReady {
|
||||
readyParallel = append(readyParallel, pID)
|
||||
}
|
||||
}
|
||||
if len(readyParallel) > 0 {
|
||||
fmt.Printf(" Can run with: %v\n", readyParallel)
|
||||
}
|
||||
}
|
||||
}
|
||||
fmt.Println()
|
||||
return nil
|
||||
}
|
||||
|
||||
func runReadyProxiedGated(ctx context.Context, uw uow.UnitOfWork, _ readyInput) error {
|
||||
molecules, err := findGateReadyMolecules(ctx, uowMolReader{uw: uw})
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"sort"
|
||||
|
|
@ -16,6 +17,7 @@ import (
|
|||
"github.com/steveyegge/beads/internal/storage/issueops"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/internal/utils"
|
||||
publicops "github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// configReader is the minimal slice of storage.Storage that config-reading
|
||||
|
|
@ -26,8 +28,10 @@ type configReader interface {
|
|||
GetConfig(ctx context.Context, key string) (string, error)
|
||||
}
|
||||
|
||||
// BeadsTemplateLabel is the label used to identify Beads-based templates
|
||||
const BeadsTemplateLabel = "template"
|
||||
// BeadsTemplateLabel is the label used to identify Beads-based templates. It
|
||||
// is the label molecule membership and auto-close read
|
||||
// (issueops.MoleculeTemplateLabel), so the two cannot drift apart.
|
||||
const BeadsTemplateLabel = publicops.MoleculeTemplateLabel
|
||||
|
||||
// variablePattern matches {{variable}} placeholders
|
||||
var variablePattern = regexp.MustCompile(`\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}`)
|
||||
|
|
@ -212,8 +216,17 @@ func loadDescendants(ctx context.Context, s molReader, subgraph *TemplateSubgrap
|
|||
// Hierarchical IDs follow the pattern: parentID.N (e.g., "gt-abc.1", "gt-abc.2")
|
||||
hierarchicalChildren, err := findHierarchicalChildren(ctx, s, parentID)
|
||||
if err != nil {
|
||||
// Non-fatal: continue with what we have
|
||||
return nil
|
||||
// The parent-child edges read above are the molecule's membership;
|
||||
// this id-pattern scan only heals children whose edge is missing. A
|
||||
// backend that cannot express an id-prefix search (a remote backend)
|
||||
// therefore loads the edge-linked subgraph without the heal. Any other
|
||||
// failure is a failed read and is returned, not treated as "no
|
||||
// children".
|
||||
var unsupported *storage.ErrUnsupported
|
||||
if errors.As(err, &unsupported) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("failed to find hierarchical children of %s: %w", parentID, err)
|
||||
}
|
||||
|
||||
for _, child := range hierarchicalChildren {
|
||||
|
|
|
|||
|
|
@ -220,6 +220,29 @@ items, plus:
|
|||
`bd ready` also withholds because a blocked parent blocks its children,
|
||||
carries no `gated_by`
|
||||
|
||||
### bd close --json
|
||||
|
||||
Returns a top-level JSON array with one entry per closed issue, in the order
|
||||
the IDs were given; an issue that was already closed is reported too. Each
|
||||
entry is the closed issue (`status` is `closed`, with `closed_at` and
|
||||
`close_reason`) without its `dependencies`, plus two optional members present
|
||||
only when that close completed a molecule (see
|
||||
[Molecules](/workflows/molecules)):
|
||||
- `auto_closed_molecule` (object, optional): The molecule root the close also
|
||||
closed, as an issue object whose `close_reason` is `all steps complete`
|
||||
- `molecule_auto_close_refusal` (string, optional): Why the molecule root
|
||||
stayed open — for example an open blocker on the root, or a root assigned
|
||||
to someone else. Human-readable prose; the step's close itself succeeded
|
||||
|
||||
When one command closes several steps of the same molecule, only the first
|
||||
of their entries carries these members.
|
||||
|
||||
With `--suggest-next`, `--continue`, or `--claim-next`, the output is an
|
||||
object instead: the array moves under `closed`, beside `unblocked` (issue
|
||||
array), `continue` (`closed_step`, `next_step`, `auto_advanced`,
|
||||
`molecule_complete`, `molecule_id`), or `claimed` (issue) respectively. When
|
||||
the flag has nothing to report, the plain array is returned.
|
||||
|
||||
### `import --json`
|
||||
|
||||
Returns a summary object when `--json` is active:
|
||||
|
|
|
|||
|
|
@ -74,6 +74,11 @@ bd mol show <molecule-id> --parallel # Highlight steps that can run concurrentl
|
|||
bd dep tree <molecule-id> # Shows full hierarchy
|
||||
```
|
||||
|
||||
A molecule's steps are the issues linked to its root by a `parent-child`
|
||||
dependency (what `--parent` and `bd mol pour` create). An ID that only looks
|
||||
hierarchical, such as `bd-xyz.4` with no such dependency, does not make an
|
||||
issue a step.
|
||||
|
||||
## Working with Molecules
|
||||
|
||||
### The Execution Model
|
||||
|
|
@ -146,8 +151,17 @@ bd close bd-xyz.1 --reason "Done"
|
|||
|
||||
# Check what's ready next
|
||||
bd ready --mol bd-xyz
|
||||
|
||||
# Or complete a step and claim the next ready one in one command
|
||||
bd close bd-xyz.1 --continue
|
||||
```
|
||||
|
||||
`--continue` claims the next ready step for you (it becomes `in_progress` and
|
||||
yours), skipping any step someone else already holds; add `--no-auto` to see
|
||||
the next step without claiming it. Against a `bd serve` that cannot advance a
|
||||
molecule, `bd close --continue` refuses before closing anything, so a step is
|
||||
never left closed with the next one unclaimed.
|
||||
|
||||
### Viewing Progress
|
||||
|
||||
```bash
|
||||
|
|
@ -175,9 +189,46 @@ Completed Molecule
|
|||
Closed / Squashed / Burned
|
||||
```
|
||||
|
||||
Closing the last child does not close the molecule root — epics stay open as
|
||||
close-eligible work until closed explicitly (`bd epic close-eligible` sweeps
|
||||
them). For cleanup of the beads themselves:
|
||||
### When the Last Step Closes
|
||||
|
||||
Closing a molecule's last open step closes its root in the same command, with
|
||||
the reason `all steps complete`:
|
||||
|
||||
```bash
|
||||
bd close bd-xyz.3
|
||||
# ✓ Auto-closed completed molecule bd-xyz — Release 1.0.0
|
||||
# ✓ Closed bd-xyz.3 — Verify: Closed
|
||||
```
|
||||
|
||||
Not every root closes this way:
|
||||
|
||||
| Root | After its last step closes |
|
||||
|------|----------------------------|
|
||||
| Poured molecule (`bd mol pour`) or wisp (`bd mol wisp`) | Closes |
|
||||
| Epic with the `template` label | Closes |
|
||||
| Any other epic | Stays open as close-eligible work: close it yourself, or sweep with `bd epic close-eligible` |
|
||||
|
||||
A root that `bd close` would refuse on its own stays open too — for example,
|
||||
it has an open blocker, it is pinned, or it is assigned to someone else. The
|
||||
step still closes, and a warning names the root and the reason:
|
||||
|
||||
```bash
|
||||
bd close bd-abc.2
|
||||
# Warning: could not auto-close completed molecule: cannot close bd-abc: assignee is "bob", actor is "alice"; reclaim or use --force to override
|
||||
# ✓ Closed bd-abc.2 — Check: Closed
|
||||
```
|
||||
|
||||
Once the obstacle is gone, `bd close <root-id>` closes the root, and so does
|
||||
closing the last step again.
|
||||
|
||||
A `bd serve` that does not close molecule roots for its clients (an older
|
||||
server, or one whose orchestrator manages molecules) leaves the root open:
|
||||
`bd close` prints a note naming it, and `bd close <root-id>` closes it.
|
||||
|
||||
With `--json`, the step's entry reports the closed root, or why it stayed
|
||||
open — see the [JSON Output Schema Contract](/reference/json-schema).
|
||||
|
||||
For cleanup of the beads themselves:
|
||||
|
||||
- `bd mol squash <id>` condenses a molecule's ephemeral children into a
|
||||
permanent digest issue.
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ load("@rules_go//go:def.bzl", "go_library", "go_test")
|
|||
go_library(
|
||||
name = "httpapi",
|
||||
srcs = [
|
||||
"advance_molecule.go",
|
||||
"auth.go",
|
||||
"batch_apply.go",
|
||||
"batch_close.go",
|
||||
|
|
@ -63,6 +64,7 @@ go_library(
|
|||
go_test(
|
||||
name = "httpapi_test",
|
||||
srcs = [
|
||||
"advance_molecule_test.go",
|
||||
"auth_test.go",
|
||||
"batch_apply_test.go",
|
||||
"batch_close_test.go",
|
||||
|
|
|
|||
64
internal/httpapi/advance_molecule.go
Normal file
64
internal/httpapi/advance_molecule.go
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/steveyegge/beads/internal/httpapi/apigen"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// advanceMoleculeRequestMembers is the document's member list for
|
||||
// AdvanceMoleculeRequest, refused BY NAME for the reason every other body on
|
||||
// this surface is.
|
||||
var advanceMoleculeRequestMembers = []string{claimActorMember, "auto_claim"}
|
||||
|
||||
// handleAdvanceMolecule moves a molecule on after one of its steps closed: the
|
||||
// operation behind `bd close --continue`. Decode, issueops.MoleculeStepper,
|
||||
// encode — the readiness rule and the claim are the role's.
|
||||
func (s *Server) handleAdvanceMolecule(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.PathValue(customMethodIDValue)
|
||||
if !s.requireNoQuery(w, r) {
|
||||
return
|
||||
}
|
||||
if !s.requireJSONContent(w, r) {
|
||||
return
|
||||
}
|
||||
members, res := decodeJSONObjectBody(w, r)
|
||||
if res != nil {
|
||||
s.fail(w, r, *res)
|
||||
return
|
||||
}
|
||||
if offender, unknown := unknownMember(members, advanceMoleculeRequestMembers); unknown {
|
||||
s.failUnknownMember(w, r, offender, advanceMoleculeRequestMembers)
|
||||
return
|
||||
}
|
||||
actor, ok := s.bodyActor(w, r, members)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
autoClaim, ok := s.booleanMember(w, r, members, "auto_claim")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
stepper, err := s.moleculeStepper(r)
|
||||
if err != nil {
|
||||
s.failErr(w, r, err)
|
||||
return
|
||||
}
|
||||
result, err := stepper.Advance(r.Context(), issueops.AdvanceRequest{Actor: actor, ClosedStepID: id, AutoClaim: autoClaim})
|
||||
if err != nil {
|
||||
s.failErr(w, r, err)
|
||||
return
|
||||
}
|
||||
body := apigen.AdvanceMoleculeResponse{
|
||||
Complete: result.Complete,
|
||||
Claimed: result.Claimed,
|
||||
MoleculeId: optionalString(result.MoleculeID),
|
||||
NextStep: result.NextStep,
|
||||
}
|
||||
if result.ClosedStep != nil {
|
||||
body.ClosedStep = *result.ClosedStep
|
||||
}
|
||||
writeJSON(w, body)
|
||||
}
|
||||
238
internal/httpapi/advance_molecule_test.go
Normal file
238
internal/httpapi/advance_molecule_test.go
Normal file
|
|
@ -0,0 +1,238 @@
|
|||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sort"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// handlerMolecule is a tiny stateful store behind the roles the advance is
|
||||
// composed over (BatchGetter, Relations, EdgeReader, Claimer): root m (a
|
||||
// molecule) <- m.1 (closed), m.2 (open). The handler tests below prove the
|
||||
// wire edge; the rule itself is pinned by the molecule contract on every leg.
|
||||
type handlerMolecule struct {
|
||||
mu sync.Mutex
|
||||
issues map[string]*types.Issue
|
||||
deps []*types.Dependency
|
||||
claims []issueops.ClaimRequest
|
||||
}
|
||||
|
||||
func newHandlerMolecule() *handlerMolecule {
|
||||
h := &handlerMolecule{issues: map[string]*types.Issue{
|
||||
"m": {ID: "m", Title: "molecule", IssueType: types.TypeMolecule, Status: types.StatusOpen},
|
||||
"m.1": {ID: "m.1", Title: "one", IssueType: types.TypeTask, Status: types.StatusClosed},
|
||||
"m.2": {ID: "m.2", Title: "two", IssueType: types.TypeTask, Status: types.StatusOpen},
|
||||
"o": {ID: "o", Title: "orphan", IssueType: types.TypeTask, Status: types.StatusClosed},
|
||||
}}
|
||||
h.deps = []*types.Dependency{
|
||||
{IssueID: "m.1", DependsOnID: "m", Type: types.DepParentChild},
|
||||
{IssueID: "m.2", DependsOnID: "m", Type: types.DepParentChild},
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
func (h *handlerMolecule) GetMany(_ context.Context, req issueops.GetManyRequest) (issueops.GetManyResult, error) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
out := issueops.GetManyResult{Issues: []*issueops.Issue{}, Missing: []string{}}
|
||||
for _, id := range req.IDs {
|
||||
if issue := h.issues[id]; issue != nil {
|
||||
clone := *issue
|
||||
out.Issues = append(out.Issues, &clone)
|
||||
} else {
|
||||
out.Missing = append(out.Missing, id)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (h *handlerMolecule) Related(_ context.Context, req issueops.RelatedRequest) ([]*issueops.RelatedIssue, error) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if h.issues[req.ID] == nil {
|
||||
return nil, fmt.Errorf("%w: %s", issueops.ErrNotFound, req.ID)
|
||||
}
|
||||
var out []*issueops.RelatedIssue
|
||||
for _, dep := range h.deps {
|
||||
if dep.DependsOnID == req.ID {
|
||||
out = append(out, &issueops.RelatedIssue{Issue: *h.issues[dep.IssueID], DependencyType: dep.Type})
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (h *handlerMolecule) ReadEdges(_ context.Context, req issueops.EdgeReadRequest) (issueops.EdgeReadResult, error) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
var out issueops.EdgeReadResult
|
||||
for _, id := range req.IDs {
|
||||
anchor := issueops.AnchorEdges{ID: id, Missing: h.issues[id] == nil}
|
||||
for _, dep := range h.deps {
|
||||
if dep.IssueID == id {
|
||||
anchor.Edges = append(anchor.Edges, dep)
|
||||
}
|
||||
}
|
||||
out.Anchors = append(out.Anchors, anchor)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (h *handlerMolecule) Claim(_ context.Context, req issueops.ClaimRequest) (issueops.ClaimResult, error) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
h.claims = append(h.claims, req)
|
||||
issue := h.issues[req.IssueID]
|
||||
issue.Status, issue.Assignee = types.StatusInProgress, req.Actor
|
||||
clone := *issue
|
||||
return issueops.ClaimResult{Issue: &clone, Changed: true}, nil
|
||||
}
|
||||
|
||||
func newAdvanceServer(t *testing.T, h *handlerMolecule) *testServer {
|
||||
t.Helper()
|
||||
return newTestServer(t, rolesConfig(Config{BatchGetter: h, Relations: h, EdgeReader: h, Claimer: h}))
|
||||
}
|
||||
|
||||
func TestAdvanceMoleculeClaimsTheNextStepThroughTheRole(t *testing.T) {
|
||||
h := newHandlerMolecule()
|
||||
ts := newAdvanceServer(t, h)
|
||||
|
||||
resp := ts.postBody(t, "/v0/beads/issues/m.1:advanceMolecule", "application/json", `{"actor":"alice","auto_claim":true}`)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
|
||||
}
|
||||
body := decodeBody(t, resp)
|
||||
if body["molecule_id"] != "m" || body["claimed"] != true || body["complete"] != false {
|
||||
t.Fatalf("body = %v, want molecule m, claimed, incomplete", body)
|
||||
}
|
||||
next, _ := body["next_step"].(map[string]any)
|
||||
if next["id"] != "m.2" || next["assignee"] != "alice" {
|
||||
t.Errorf("next_step = %v, want m.2 assigned to alice", next)
|
||||
}
|
||||
closed, _ := body["closed_step"].(map[string]any)
|
||||
if closed["id"] != "m.1" {
|
||||
t.Errorf("closed_step = %v, want m.1", closed)
|
||||
}
|
||||
if len(h.claims) != 1 || h.claims[0] != (issueops.ClaimRequest{Actor: "alice", IssueID: "m.2"}) {
|
||||
t.Errorf("the Claimer received %+v, want one claim of m.2 for alice", h.claims)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdvanceMoleculeWithoutAutoClaimWritesNothing(t *testing.T) {
|
||||
h := newHandlerMolecule()
|
||||
ts := newAdvanceServer(t, h)
|
||||
resp := ts.postBody(t, "/v0/beads/issues/m.1:advanceMolecule", "application/json", `{"actor":"alice"}`)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
|
||||
}
|
||||
body := decodeBody(t, resp)
|
||||
if body["claimed"] != false || len(h.claims) != 0 {
|
||||
t.Errorf("body = %v claims = %v, want nothing claimed", body, h.claims)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdvanceMoleculeOutsideAMoleculeOmitsTheMolecule(t *testing.T) {
|
||||
ts := newAdvanceServer(t, newHandlerMolecule())
|
||||
resp := ts.postBody(t, "/v0/beads/issues/o:advanceMolecule", "application/json", `{"actor":"alice","auto_claim":true}`)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
|
||||
}
|
||||
body := decodeBody(t, resp)
|
||||
if _, ok := body["molecule_id"]; ok {
|
||||
t.Errorf("molecule_id = %v, want it absent for a step in no molecule", body["molecule_id"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdvanceMoleculeRefusesBadRequestsBeforeTheRole(t *testing.T) {
|
||||
h := newHandlerMolecule()
|
||||
ts := newAdvanceServer(t, h)
|
||||
for _, tc := range []struct {
|
||||
path, body string
|
||||
status int
|
||||
}{
|
||||
{"/v0/beads/issues/m.1:advanceMolecule", `{"actor":"alice","extra":1}`, http.StatusBadRequest},
|
||||
{"/v0/beads/issues/m.1:advanceMolecule", `{"auto_claim":true}`, http.StatusBadRequest},
|
||||
{"/v0/beads/issues/m.1:advanceMolecule", `{"actor":"alice","auto_claim":"yes"}`, http.StatusBadRequest},
|
||||
{"/v0/beads/issues/nope:advanceMolecule", `{"actor":"alice"}`, http.StatusNotFound},
|
||||
} {
|
||||
resp := ts.postBody(t, tc.path, "application/json", tc.body)
|
||||
if resp.StatusCode != tc.status {
|
||||
t.Errorf("%s %s: status = %d, want %d: %s", tc.path, tc.body, resp.StatusCode, tc.status, readAll(t, resp))
|
||||
}
|
||||
}
|
||||
if len(h.claims) != 0 {
|
||||
t.Errorf("a refused request reached the Claimer: %+v", h.claims)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloseForwardsAutoCloseMoleculeAndReportsTheRoot(t *testing.T) {
|
||||
root := closedIssue("bd-root")
|
||||
lifecycle := &roleLifecycle{closeResult: issueops.CloseResult{
|
||||
Issue: closedIssue("bd-1"), Changed: true, AutoClosedMolecule: root,
|
||||
}}
|
||||
ts := newCloseServer(t, lifecycle)
|
||||
resp := ts.closeIssue(t, closePath, `{"actor":"alice","auto_close_molecule":true}`)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
|
||||
}
|
||||
got := lifecycle.closeRequests()
|
||||
if len(got) != 1 || !got[0].AutoCloseMolecule {
|
||||
t.Fatalf("the role received %+v, want AutoCloseMolecule set", got)
|
||||
}
|
||||
body := decodeBody(t, resp)
|
||||
auto, _ := body["auto_closed_molecule"].(map[string]any)
|
||||
if auto["id"] != "bd-root" {
|
||||
t.Errorf("auto_closed_molecule = %v, want bd-root", body["auto_closed_molecule"])
|
||||
}
|
||||
if _, ok := body["molecule_auto_close_refusal"]; ok {
|
||||
t.Errorf("molecule_auto_close_refusal present on a clean auto-close: %v", body)
|
||||
}
|
||||
|
||||
lifecycle = &roleLifecycle{closeResult: issueops.CloseResult{
|
||||
Issue: closedIssue("bd-1"), Changed: true, MoleculeAutoCloseRefusal: "cannot close blocked issue",
|
||||
}}
|
||||
ts = newCloseServer(t, lifecycle)
|
||||
resp = ts.closeIssue(t, closePath, `{"actor":"alice"}`)
|
||||
if got := lifecycle.closeRequests(); len(got) != 1 || got[0].AutoCloseMolecule {
|
||||
t.Fatalf("an absent member reached the role as %+v, want AutoCloseMolecule unset (opt-in)", got)
|
||||
}
|
||||
body = decodeBody(t, resp)
|
||||
if body["molecule_auto_close_refusal"] != "cannot close blocked issue" {
|
||||
t.Errorf("molecule_auto_close_refusal = %v, want the refusal", body["molecule_auto_close_refusal"])
|
||||
}
|
||||
if _, ok := body["auto_closed_molecule"]; ok {
|
||||
t.Errorf("auto_closed_molecule present with nothing auto-closed: %v", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBatchCloseForwardsAutoCloseMoleculeAndReportsItPerItem(t *testing.T) {
|
||||
closer := &roleBatchCloser{result: issueops.CloseBatchResult{Outcomes: []issueops.CloseOutcome{
|
||||
{IssueID: "bd-1", Issue: closedIssue("bd-1"), Changed: true},
|
||||
{IssueID: "bd-2", Issue: closedIssue("bd-2"), Changed: true, AutoClosedMolecule: closedIssue("bd-root")},
|
||||
}}}
|
||||
ts := newBatchCloseServer(t, closer)
|
||||
resp := ts.batchClose(t, `{"actor":"alice","items":[{"id":"bd-1"},{"id":"bd-2"}],"auto_close_molecule":true}`)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
|
||||
}
|
||||
closer.mu.Lock()
|
||||
requests := append([]issueops.CloseBatchRequest(nil), closer.requests...)
|
||||
closer.mu.Unlock()
|
||||
if len(requests) != 1 || !requests[0].AutoCloseMolecule {
|
||||
t.Fatalf("the role received %+v, want AutoCloseMolecule set", requests)
|
||||
}
|
||||
outcomes := outcomesOf(t, resp)
|
||||
if _, ok := outcomes[0]["auto_closed_molecule"]; ok {
|
||||
t.Errorf("outcome 0 = %v, want no auto-closed root", outcomes[0])
|
||||
}
|
||||
auto, _ := outcomes[1]["auto_closed_molecule"].(map[string]any)
|
||||
if auto["id"] != "bd-root" {
|
||||
t.Errorf("outcome 1 auto_closed_molecule = %v, want bd-root", outcomes[1]["auto_closed_molecule"])
|
||||
}
|
||||
}
|
||||
|
|
@ -321,6 +321,33 @@ type AddDependenciesResponse struct {
|
|||
Added []DependencyEdge `json:"added"`
|
||||
}
|
||||
|
||||
// AdvanceMoleculeRequest defines model for AdvanceMoleculeRequest.
|
||||
type AdvanceMoleculeRequest struct {
|
||||
// Actor Who advances, and with `auto_claim` the claimed step's assignee. `ClaimRequest.actor`'s rules exactly.
|
||||
Actor string `json:"actor"`
|
||||
|
||||
// AutoClaim Claim the next ready step for `actor`. Without it the operation writes nothing and only names the step.
|
||||
AutoClaim *bool `json:"auto_claim,omitempty"`
|
||||
}
|
||||
|
||||
// AdvanceMoleculeResponse defines model for AdvanceMoleculeResponse.
|
||||
type AdvanceMoleculeResponse struct {
|
||||
// Claimed `next_step` was claimed for `actor`, and is the post-claim row.
|
||||
Claimed bool `json:"claimed"`
|
||||
|
||||
// ClosedStep A tracked work item. Property semantics documented here apply to every schema that repeats them below.
|
||||
ClosedStep Issue `json:"closed_step"`
|
||||
|
||||
// Complete Every step of the molecule is closed; `next_step` is then absent.
|
||||
Complete bool `json:"complete"`
|
||||
|
||||
// MoleculeId The step's molecule root. ABSENT when the step belongs to no molecule, and then nothing else below is set.
|
||||
MoleculeId *string `json:"molecule_id,omitempty"`
|
||||
|
||||
// NextStep A tracked work item. Property semantics documented here apply to every schema that repeats them below.
|
||||
NextStep *Issue `json:"next_step,omitempty"`
|
||||
}
|
||||
|
||||
// AnchorEdgeCount One anchor's edge cardinality, or the report that it is not there.
|
||||
type AnchorEdgeCount struct {
|
||||
// Count How many stored edges match, in the requested direction, after the type and status filters. Never negative.
|
||||
|
|
@ -764,6 +791,11 @@ type BatchCloseRequest struct {
|
|||
// Actor Who is closing. `ClaimRequest.actor`'s rules exactly, and the value is recorded against every item.
|
||||
Actor string `json:"actor"`
|
||||
|
||||
// AutoCloseMolecule Behind the `issues.close.autoCloseMolecule` behavior token: an older server answers `unknown_parameter` for this name.
|
||||
//
|
||||
// Close each item's molecule root when the batch completed it: `CloseIssueRequest.auto_close_molecule` for every item that closed or was already closed, run after all the closes inside the same transaction. A batch that closes several steps of one molecule decides its root once, and the root it closed, or its refusal, is reported on the outcome of the first successful item under that root.
|
||||
AutoCloseMolecule *bool `json:"auto_close_molecule,omitempty"`
|
||||
|
||||
// Force Bypass close policy — the open-children refusal and the live-blocker refusal — and the pin and the assignee guard for EVERY item, and nothing else. It never bypasses the template guard or validation, and it never bypasses existence: an id that names nothing refuses whether or not this is set. It is request-wide because the flag that spells it is.
|
||||
Force *bool `json:"force,omitempty"`
|
||||
|
||||
|
|
@ -920,6 +952,13 @@ type CloseIssueRequest struct {
|
|||
// Actor Who is closing the issue. `ClaimRequest.actor`'s rules exactly: the server trims it, then refuses an empty result, anything longer than 256 BYTES (the `maxLength` above counts characters — the byte limit is the binding one), and any control character including newline. The value reaches stored columns, event-stream attribution and the storage commit message, so an unvalidated newline would forge audit-trail lines.
|
||||
Actor string `json:"actor"`
|
||||
|
||||
// AutoCloseMolecule Behind the `issues.close.autoCloseMolecule` behavior token: an older server answers `unknown_parameter` for this name, and a client checks the token before sending it.
|
||||
//
|
||||
// Close the issue's molecule root IN THE SAME TRANSACTION when this close completed it: the root is an auto-closing molecule root (a `molecule`-typed or ephemeral root, or a template-labeled epic), it is open, and every step under it is now closed. The root close is unforced, guarded on the root revision read inside that transaction, and records `all steps complete` and this request's `session`. It runs for an idempotent re-close too, so replaying the close of a molecule's last step heals a root left open.
|
||||
//
|
||||
// OPT-IN, because an orchestrator may run its own molecule lifecycle. A root that its close policy refuses (a live blocker) or a close guard refuses (a template, a pinned root, a root assigned to another actor) stays open, is named in `molecule_auto_close_refusal`, and never fails this close. Any other failure of the root close, such as a storage error, fails this close with it.
|
||||
AutoCloseMolecule *bool `json:"auto_close_molecule,omitempty"`
|
||||
|
||||
// ExpectedVersion Requires the row's revision to equal this value BEFORE the close. A miss refuses the whole request with `409 precondition_failed` and writes nothing — `UpdateIssueRequest.expected_version`'s contract, on the operation that closes one row.
|
||||
//
|
||||
// IT IS CHECKED BEFORE THE IDEMPOTENT RE-CLOSE, which is the one place this guard differs from the update's. A re-close of a row somebody else has moved since the caller read it is a `409` and not the 200-with-`already_closed` the same body earns without a guard: a replay whose premise has expired is a refusal the caller wants to see, and it is the only way `already_closed` can be trusted as "nothing has happened here since".
|
||||
|
|
@ -946,9 +985,15 @@ type CloseIssueResponse struct {
|
|||
// AlreadyClosed True when the issue was already closed and this call changed nothing — the idempotent re-close, mirroring `ClaimResponse.already_claimed`. The response still carries the row, and `reason`/`session` were not rewritten.
|
||||
AlreadyClosed bool `json:"already_closed"`
|
||||
|
||||
// AutoClosedMolecule A tracked work item. Property semantics documented here apply to every schema that repeats them below.
|
||||
AutoClosedMolecule *Issue `json:"auto_closed_molecule,omitempty"`
|
||||
|
||||
// Issue A tracked work item. Property semantics documented here apply to every schema that repeats them below.
|
||||
Issue Issue `json:"issue"`
|
||||
|
||||
// MoleculeAutoCloseRefusal With `issues.close.autoCloseMolecule` and `auto_close_molecule`: why the molecule root this close completed stayed open — the root's own close policy refused it (a live blocker on the root), or a close guard did (a template, a pinned root, a root assigned to another actor). Prose; absent when nothing was refused. `auto_closed_molecule`, beside it, is the root the close also closed, absent when none was.
|
||||
MoleculeAutoCloseRefusal *string `json:"molecule_auto_close_refusal,omitempty"`
|
||||
|
||||
// OpenChildren How many open children the close observed. Reported by a FORCED close — including an idempotent re-close — because a caller that bypassed the guard is exactly the caller that wants the number. An unforced close that got this far had none, so it reports 0.
|
||||
OpenChildren int `json:"open_children"`
|
||||
|
||||
|
|
@ -972,6 +1017,9 @@ type CloseOutcome struct {
|
|||
// Assignee With `not_assignee`: the issue's assignee the refusing transaction observed, exactly as `Problem.assignee` carries it for the single close. Absent on a successful item and on every other refusal.
|
||||
Assignee *string `json:"assignee,omitempty"`
|
||||
|
||||
// AutoClosedMolecule A tracked work item. Property semantics documented here apply to every schema that repeats them below.
|
||||
AutoClosedMolecule *Issue `json:"auto_closed_molecule,omitempty"`
|
||||
|
||||
// Blockers With `not_closable` on the live-blocker refusal: the blockers that refused THIS item, exactly as `Problem.blockers` carries them for the single close, and optional for the same reason. Absent on a successful item and on every other refusal.
|
||||
Blockers *[]Blocker `json:"blockers,omitempty"`
|
||||
|
||||
|
|
@ -989,6 +1037,9 @@ type CloseOutcome struct {
|
|||
// IssueId The id the caller asked for, echoed verbatim so an outcome can be read without indexing back into the request.
|
||||
IssueId string `json:"issue_id"`
|
||||
|
||||
// MoleculeAutoCloseRefusal `CloseIssueResponse.molecule_auto_close_refusal` for this item, under `issues.close.autoCloseMolecule`; `auto_closed_molecule` beside it is `CloseIssueResponse.auto_closed_molecule`. Present only on a successful item.
|
||||
MoleculeAutoCloseRefusal *string `json:"molecule_auto_close_refusal,omitempty"`
|
||||
|
||||
// OpenChildren How many open children the transaction observed for this item.
|
||||
//
|
||||
// ITS MEANING FOLLOWS `code`, and both readings are the ones the single close already publishes. On a SUCCESSFUL item it is always present and is `CloseIssueResponse.open_children` — the number a forced close bypassed, reported even for an idempotent re-close, and `0` for an unforced close that got that far. On a REFUSED item its PRESENCE is the discriminator between the two `not_closable` refusals, exactly as it is on a problem document: present means open children, absent means a live blocker.
|
||||
|
|
@ -1050,7 +1101,7 @@ type ContextResponse struct {
|
|||
// OPTIONAL, and absent means only that this server does not disclose its filesystem layout — never that it has no workspace. A client MUST NOT require it, MUST NOT treat absence as an error, and has no use for the value beyond display: it is a path on the SERVER's filesystem, which the client cannot open. Identify the workspace by `project_id` and `database`, which are required.
|
||||
BeadsDir *string `json:"beads_dir,omitempty"`
|
||||
|
||||
// Capabilities The tokens this server advertises: the OPERATIONS it implements, derived from its route table, and the server-wide BEHAVIORS it enforces. v0's operation vocabulary is `ready.list`, `ready.count`, `issues.list`, `issues.query`, `issues.count`, `issues.get`, `issues.related`, `issues.create`, `issues.addComment`, `issues.batchClose`, `issues.claim`, `issues.claimNext`, `issues.release`, `issues.close`, `issues.reopen`, `issues.update`, `issues.sweep`, `issues.delete`, `issues.batchGet`, `issues.reclaim`, `issues.batchCreate`, `issues.batchApply`, `stats.get`, `config.list`, `config.get`, `config.set`, `config.unset`, `dependencies.cycles`, `dependencies.list`, `dependencies.count`, `dependencies.blocking`, `dependencies.tree`, `dependencies.add`, `dependencies.remove`, `memories.list`, `memories.get`, `memories.remember`, `memories.forget`, `events.list`, `events.watch`, `issues.casMetadata`; the behavior tokens are `project.enforce`, which announces that a `Bd-Project-Id` stamp for the wrong workspace is refused here rather than silently ignored, `issues.batchApplyLarge`, which announces that `POST /v0/beads/issues:batchApply` accepts the RAISED envelope — up to 1000 items (`ApplyBatchRequest.items.maxItems`), a 16 MiB body, and (for a request over 100 items) a run budget that EXTENDS to an operator-configured ceiling (`bd serve --large-apply-ceiling`, 5 minutes by default) — rather than the original 100-item, 4 MiB bound. The ceiling is a flat whole-run budget, not a value scaled by item count: a 101-item request and a 1000-item request both get the same extended budget. A request at or under 100 items is unaffected either way and keeps the server's ordinary deadline exactly as before. A client that checks for this token before sending a plan over 100 items learns whether THIS server accepts it without paying for a round trip an older server would refuse anyway, and `issues.list.sort`, which announces that `GET /v0/beads/issues` accepts the `sort` query parameter (two closed, pageable total orders — see that parameter) rather than silently answering `unknown_parameter`, and `issues.count.scope`, which announces that `GET /v0/beads/issues:count` accepts `parent`, `no_parent`, `exclude_type`, and `exclude_status` (see those parameters) rather than silently answering `unknown_parameter` for all four, `issues.sweep.wispsPlane`, which announces that `POST /v0/beads/issues:sweep` accepts the `wisps-plane` value of `tier` rather than silently answering `invalid_value`, `issues.sweep.liveDependents`, which announces that the same operation accepts `protect_live_dependents` and answers `skipped.live_dependent` rather than silently answering `unknown_parameter`, `issues.sweep.limit`, which announces that it accepts `limit` and answers `remaining` rather than silently answering `unknown_parameter`, and `issues.batchApply.depAddLineage`, which announces that a `dep_add` item on `POST /v0/beads/issues:batchApply` accepts `has_spawner` and `thread_id` (see `ApplyDepAddItem`) rather than a `400` naming the member unknown, and `issues.update.allowTemplate`, which announces that `PATCH /v0/beads/issues/{id}` accepts `allow_template` (see `UpdateIssueRequest`) rather than a `400` naming the member unknown, and `issues.create.defaultPriority`, which announces that a create (`POST /v0/beads/issues`, `issues:batchCreate` and `issues:batchApply` create items) with no `priority` member stores the default P2 rather than P0. One behavior token is CONDITIONAL rather than build-level: `policy.external_dependencies` announces that this server's ready, claim, claim-next, close, blocking and dependency-tree operations already apply bd's external-dependency policy (an issue blocked by an unsatisfied `external:<project>:<capability>` dependency is neither ready, claimable nor closable without force). A server advertises it only when it enforces that policy; a client that sees it must not apply the policy again, and a client that does not see it applies the policy itself. The list grows additively, and an operation never appears here unless it is fully implemented. This is how a client checks for an operation or a behavior — never the version string.
|
||||
// Capabilities The tokens this server advertises: the OPERATIONS it implements, derived from its route table, and the server-wide BEHAVIORS it enforces. v0's operation vocabulary is `ready.list`, `ready.count`, `issues.list`, `issues.query`, `issues.count`, `issues.get`, `issues.related`, `issues.create`, `issues.addComment`, `issues.batchClose`, `issues.claim`, `issues.claimNext`, `issues.release`, `issues.close`, `issues.reopen`, `issues.update`, `issues.sweep`, `issues.delete`, `issues.batchGet`, `issues.reclaim`, `issues.batchCreate`, `issues.batchApply`, `stats.get`, `config.list`, `config.get`, `config.set`, `config.unset`, `dependencies.cycles`, `dependencies.list`, `dependencies.count`, `dependencies.blocking`, `dependencies.tree`, `dependencies.add`, `dependencies.remove`, `memories.list`, `memories.get`, `memories.remember`, `memories.forget`, `events.list`, `events.watch`, `issues.casMetadata`, `issues.advanceMolecule`; the behavior tokens are `project.enforce`, which announces that a `Bd-Project-Id` stamp for the wrong workspace is refused here rather than silently ignored, `issues.batchApplyLarge`, which announces that `POST /v0/beads/issues:batchApply` accepts the RAISED envelope — up to 1000 items (`ApplyBatchRequest.items.maxItems`), a 16 MiB body, and (for a request over 100 items) a run budget that EXTENDS to an operator-configured ceiling (`bd serve --large-apply-ceiling`, 5 minutes by default) — rather than the original 100-item, 4 MiB bound. The ceiling is a flat whole-run budget, not a value scaled by item count: a 101-item request and a 1000-item request both get the same extended budget. A request at or under 100 items is unaffected either way and keeps the server's ordinary deadline exactly as before. A client that checks for this token before sending a plan over 100 items learns whether THIS server accepts it without paying for a round trip an older server would refuse anyway, and `issues.list.sort`, which announces that `GET /v0/beads/issues` accepts the `sort` query parameter (two closed, pageable total orders — see that parameter) rather than silently answering `unknown_parameter`, and `issues.count.scope`, which announces that `GET /v0/beads/issues:count` accepts `parent`, `no_parent`, `exclude_type`, and `exclude_status` (see those parameters) rather than silently answering `unknown_parameter` for all four, `issues.sweep.wispsPlane`, which announces that `POST /v0/beads/issues:sweep` accepts the `wisps-plane` value of `tier` rather than silently answering `invalid_value`, `issues.sweep.liveDependents`, which announces that the same operation accepts `protect_live_dependents` and answers `skipped.live_dependent` rather than silently answering `unknown_parameter`, `issues.sweep.limit`, which announces that it accepts `limit` and answers `remaining` rather than silently answering `unknown_parameter`, and `issues.batchApply.depAddLineage`, which announces that a `dep_add` item on `POST /v0/beads/issues:batchApply` accepts `has_spawner` and `thread_id` (see `ApplyDepAddItem`) rather than a `400` naming the member unknown, and `issues.update.allowTemplate`, which announces that `PATCH /v0/beads/issues/{id}` accepts `allow_template` (see `UpdateIssueRequest`) rather than a `400` naming the member unknown, and `issues.create.defaultPriority`, which announces that a create (`POST /v0/beads/issues`, `issues:batchCreate` and `issues:batchApply` create items) with no `priority` member stores the default P2 rather than P0, and `issues.close.autoCloseMolecule`, which announces that `POST /v0/beads/issues/{id}:close` and `POST /v0/beads/issues:batchClose` accept `auto_close_molecule` and answer `auto_closed_molecule` and `molecule_auto_close_refusal` rather than a `400` naming the member unknown. One behavior token is CONDITIONAL rather than build-level: `policy.external_dependencies` announces that this server's ready, claim, claim-next, close, blocking and dependency-tree operations already apply bd's external-dependency policy (an issue blocked by an unsatisfied `external:<project>:<capability>` dependency is neither ready, claimable nor closable without force). A server advertises it only when it enforces that policy; a client that sees it must not apply the policy again, and a client that does not see it applies the policy itself. The list grows additively, and an operation never appears here unless it is fully implemented. This is how a client checks for an operation or a behavior — never the version string.
|
||||
//
|
||||
// THIS LIST IS BUILD-LEVEL, NOT WORKSPACE-LEVEL, apart from the conditional `policy.external_dependencies` above, which depends on how this server composed its roles rather than on the build. It says which operations this binary serves, and for every entry but two that is the whole answer. `events.list` and `events.watch` are the exceptions: the durable events journal is a per-workspace setting that is OFF by default, so a server that advertises them may still refuse every request to both with 409 `events_journal_disabled` — correctly, because the operations exist and the workspace has no journal. A consumer of either MUST treat the capability as "this server speaks it" and the 409 as "not on this workspace", and must not read the capability as a promise that records will arrive.
|
||||
Capabilities []string `json:"capabilities"`
|
||||
|
|
@ -2804,6 +2855,9 @@ type UpdateIssueJSONRequestBody = UpdateIssueRequest
|
|||
// AddCommentJSONRequestBody defines body for AddComment for application/json ContentType.
|
||||
type AddCommentJSONRequestBody = AddCommentRequest
|
||||
|
||||
// AdvanceMoleculeJSONRequestBody defines body for AdvanceMolecule for application/json ContentType.
|
||||
type AdvanceMoleculeJSONRequestBody = AdvanceMoleculeRequest
|
||||
|
||||
// CompareAndSetMetadataJSONRequestBody defines body for CompareAndSetMetadata for application/json ContentType.
|
||||
type CompareAndSetMetadataJSONRequestBody = CompareAndSetMetadataRequest
|
||||
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ const (
|
|||
// lists at each level, refused BY NAME for the reason every other body on this
|
||||
// surface is.
|
||||
var (
|
||||
batchCloseRequestMembers = []string{claimActorMember, "items", "session", "force"}
|
||||
batchCloseRequestMembers = []string{claimActorMember, "items", "session", "force", autoCloseMoleculeMember}
|
||||
batchCloseItemMembers = []string{"id", "reason"}
|
||||
)
|
||||
|
||||
|
|
@ -114,6 +114,8 @@ func closeOutcome(outcome issueops.CloseOutcome) apigen.CloseOutcome {
|
|||
if issue != nil {
|
||||
wire.Issue = issue
|
||||
}
|
||||
wire.AutoClosedMolecule = outcome.AutoClosedMolecule
|
||||
wire.MoleculeAutoCloseRefusal = optionalString(outcome.MoleculeAutoCloseRefusal)
|
||||
return wire
|
||||
}
|
||||
|
||||
|
|
@ -184,6 +186,10 @@ func (s *Server) batchCloseRequest(w http.ResponseWriter, r *http.Request) (issu
|
|||
if !ok {
|
||||
return issueops.CloseBatchRequest{}, false
|
||||
}
|
||||
autoCloseMolecule, ok := s.booleanMember(w, r, members, autoCloseMoleculeMember)
|
||||
if !ok {
|
||||
return issueops.CloseBatchRequest{}, false
|
||||
}
|
||||
items, ok := s.batchCloseItems(w, r, members)
|
||||
if !ok {
|
||||
return issueops.CloseBatchRequest{}, false
|
||||
|
|
@ -192,10 +198,11 @@ func (s *Server) batchCloseRequest(w http.ResponseWriter, r *http.Request) (issu
|
|||
// need a second, body-shaped spelling of the ready-filter vocabulary that
|
||||
// listReadyWork and claimNext both express as query parameters.
|
||||
return issueops.CloseBatchRequest{
|
||||
Actor: actor,
|
||||
Items: items,
|
||||
Session: session,
|
||||
Force: force,
|
||||
Actor: actor,
|
||||
Items: items,
|
||||
Session: session,
|
||||
Force: force,
|
||||
AutoCloseMolecule: autoCloseMolecule,
|
||||
}, true
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -340,6 +340,7 @@ type timedProvider struct {
|
|||
var (
|
||||
_ uow.IssueReaderSource = timedProvider{}
|
||||
_ uow.IssueClaimerSource = timedProvider{}
|
||||
_ uow.MoleculeStepperSource = timedProvider{}
|
||||
_ uow.BatchCloserSource = timedProvider{}
|
||||
_ uow.ReadyClaimerSource = timedProvider{}
|
||||
_ uow.ReleaserSource = timedProvider{}
|
||||
|
|
@ -481,6 +482,12 @@ func (p timedProvider) LeaseReclaimer() (issueops.LeaseReclaimer, error) {
|
|||
return uow.NewLeaseReclaimer(p)
|
||||
}
|
||||
|
||||
// MoleculeStepper builds the advance-a-molecule role OVER THIS WRAPPER, so
|
||||
// every read and the claim it composes go through this wrapper's roles.
|
||||
func (p timedProvider) MoleculeStepper() (issueops.MoleculeStepper, error) {
|
||||
return uow.NewMoleculeStepper(p)
|
||||
}
|
||||
|
||||
// IssueRelations builds the single-anchor neighbor role OVER THIS WRAPPER, for
|
||||
// the same reason and with the same hazard as IssueReader. It is the one
|
||||
// accessor here whose name is not the role's: the seam spells it IssueRelations
|
||||
|
|
|
|||
|
|
@ -17,7 +17,11 @@ import (
|
|||
// schema is additionalProperties: false, so anything else is refused BY NAME —
|
||||
// which is why the body is decoded as raw members first, the posture claim and
|
||||
// batchCreate already take.
|
||||
var closeRequestMembers = []string{"actor", "reason", "session", "force", expectedVersionMember}
|
||||
var closeRequestMembers = []string{"actor", "reason", "session", "force", expectedVersionMember, autoCloseMoleculeMember}
|
||||
|
||||
// autoCloseMoleculeMember is the request member behind
|
||||
// CapIssuesCloseAutoCloseMolecule, shared by the single and the batch close.
|
||||
const autoCloseMoleculeMember = "auto_close_molecule"
|
||||
|
||||
// handleClose closes one issue: the second half of the loop this surface exists
|
||||
// to serve, and the half that still forked a subprocess.
|
||||
|
|
@ -73,10 +77,12 @@ func (s *Server) handleClose(w http.ResponseWriter, r *http.Request) {
|
|||
// fill. types.Issue.RowVersion is `json:"-"`, so the Issue body cannot carry
|
||||
// it and this member is where it lives — updateIssue's arrangement exactly.
|
||||
writeJSON(w, apigen.CloseIssueResponse{
|
||||
Issue: *result.Issue,
|
||||
AlreadyClosed: !result.Changed,
|
||||
OpenChildren: result.OpenChildren,
|
||||
Revision: types.RevisionToken(result.Issue.RowVersion),
|
||||
Issue: *result.Issue,
|
||||
AlreadyClosed: !result.Changed,
|
||||
OpenChildren: result.OpenChildren,
|
||||
Revision: types.RevisionToken(result.Issue.RowVersion),
|
||||
AutoClosedMolecule: result.AutoClosedMolecule,
|
||||
MoleculeAutoCloseRefusal: optionalString(result.MoleculeAutoCloseRefusal),
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -118,14 +124,19 @@ func (s *Server) closeRequest(w http.ResponseWriter, r *http.Request, id string)
|
|||
s.fail(w, r, *res)
|
||||
return issueops.CloseRequest{}, false
|
||||
}
|
||||
autoCloseMolecule, ok := s.booleanMember(w, r, members, autoCloseMoleculeMember)
|
||||
if !ok {
|
||||
return issueops.CloseRequest{}, false
|
||||
}
|
||||
|
||||
return issueops.CloseRequest{
|
||||
Actor: actor,
|
||||
IssueID: id,
|
||||
Reason: reason,
|
||||
Session: session,
|
||||
Force: force,
|
||||
ExpectedVersion: expectedVersion,
|
||||
Actor: actor,
|
||||
IssueID: id,
|
||||
Reason: reason,
|
||||
Session: session,
|
||||
Force: force,
|
||||
ExpectedVersion: expectedVersion,
|
||||
AutoCloseMolecule: autoCloseMolecule,
|
||||
}, true
|
||||
}
|
||||
|
||||
|
|
@ -284,3 +295,11 @@ func versionPreconditionResult(expected *int64) Result {
|
|||
// the three operations that publish it so the member name a client reads off
|
||||
// `param` cannot drift from the member name it sent.
|
||||
const expectedVersionMember = "expected_version"
|
||||
|
||||
// optionalString spells "" as an absent member.
|
||||
func optionalString(value string) *string {
|
||||
if value == "" {
|
||||
return nil
|
||||
}
|
||||
return &value
|
||||
}
|
||||
|
|
|
|||
|
|
@ -443,6 +443,9 @@ const (
|
|||
// the reason and session under first-close-wins, the done-status
|
||||
// normalization, and the close policy vocabulary.
|
||||
OpCloseIssue = "closeIssue"
|
||||
// OpAdvanceMolecule moves a molecule on after one of its steps closed: the
|
||||
// operation behind `bd close --continue` (issueops.MoleculeStepper).
|
||||
OpAdvanceMolecule = "advanceMolecule"
|
||||
// OpReopenIssue is the close's mirror, and it completes the lifecycle pair
|
||||
// so a recovery flow works end to end over this surface. It is the one write
|
||||
// here with no POLICY conflict code: reopen takes an issue OUT of the done
|
||||
|
|
@ -899,6 +902,13 @@ var operationCodes = map[string][]Code{
|
|||
CodeTemplateReadOnly, CodeIssuePinned, CodeNotAssignee,
|
||||
CodeBusy, CodeDBUnavailable, CodeInternal,
|
||||
},
|
||||
// No conflict code: a ready step another actor holds, or one moved out of
|
||||
// a claimable status, is skipped for the next one rather than refused —
|
||||
// the role's own rule — so the only 404 is the path id's.
|
||||
OpAdvanceMolecule: {
|
||||
CodeInvalidArgument, CodeUnauthenticated, CodeNotFound,
|
||||
CodeBusy, CodeDBUnavailable, CodeInternal,
|
||||
},
|
||||
// ONE 409, and it is a PRECONDITION rather than a policy. Close has a policy
|
||||
// guard — open children, a live blocker — and reopen is the direction that
|
||||
// takes an issue OUT of the done category rather than putting it in, so
|
||||
|
|
|
|||
|
|
@ -204,6 +204,16 @@ const CapExternalDependencies = "policy.external_dependencies"
|
|||
// lists them; advertisedCapabilities adds each one whose condition holds.
|
||||
var conditionalCapabilities = []string{CapExternalDependencies}
|
||||
|
||||
// CapIssuesCloseAutoCloseMolecule is the behavior capability that advertises
|
||||
// CloseIssueRequest.auto_close_molecule and BatchCloseRequest.auto_close_molecule
|
||||
// with their paired response members (auto_closed_molecule,
|
||||
// molecule_auto_close_refusal): close a completed molecule's root in the same
|
||||
// transaction as the step close (issueops.CloseRequest.AutoCloseMolecule). An
|
||||
// older server answers the request member with `400
|
||||
// invalid_argument`/`unknown_parameter`; the client checks this token before
|
||||
// sending it.
|
||||
const CapIssuesCloseAutoCloseMolecule = "issues.close.autoCloseMolecule"
|
||||
|
||||
// customMethodTarget splits the custom method off the segment the router
|
||||
// matched, and reports the row that claims it.
|
||||
//
|
||||
|
|
@ -759,6 +769,16 @@ var routeTable = []route{
|
|||
implemented: true,
|
||||
handler: (*Server).handleReopen,
|
||||
},
|
||||
{
|
||||
op: OpAdvanceMolecule,
|
||||
method: http.MethodPost,
|
||||
pattern: customMethodPattern,
|
||||
specPath: "/v0/beads/issues/{id}:advanceMolecule",
|
||||
customMethod: ":advanceMolecule",
|
||||
capability: "issues.advanceMolecule",
|
||||
implemented: true,
|
||||
handler: (*Server).handleAdvanceMolecule,
|
||||
},
|
||||
{
|
||||
op: OpBatchCloseIssues,
|
||||
method: http.MethodPost,
|
||||
|
|
@ -966,6 +986,7 @@ var behaviorCapabilities = []string{
|
|||
CapProjectEnforce, CapBatchApplyLarge, CapIssuesListSort, CapIssuesCountScope,
|
||||
CapIssuesSweepWispsPlane, CapIssuesSweepLiveDependents, CapIssuesSweepLimit,
|
||||
CapBatchApplyDepAddLineage, CapIssuesUpdateAllowTemplate, CapIssuesCreateDefaultPriority,
|
||||
CapIssuesCloseAutoCloseMolecule,
|
||||
}
|
||||
|
||||
// Capabilities lists what this build advertises in ContextResponse.capabilities:
|
||||
|
|
|
|||
|
|
@ -2408,3 +2408,23 @@ func logValue(v any) string {
|
|||
func millis(d time.Duration) string {
|
||||
return strconv.FormatFloat(float64(d)/float64(time.Millisecond), 'f', 3, 64)
|
||||
}
|
||||
|
||||
// moleculeStepper returns the advance-a-molecule surface for one request.
|
||||
//
|
||||
// On the store-shaped source there is no configured field for it: the role is
|
||||
// issueops.NewMoleculeStepper composed over roles the source already carries
|
||||
// (batch getter, relations, edge reader, claimer, lifecycle), so building it
|
||||
// here from those is the same composition a store's own accessor makes. On the
|
||||
// provider it is built over the timed wrapper, the same two-step every role
|
||||
// above performs.
|
||||
func (s *Server) moleculeStepper(r *http.Request) (issueops.MoleculeStepper, error) {
|
||||
if s.provider == nil {
|
||||
return issueops.NewMoleculeStepper(issueops.MoleculeStepperRoles{
|
||||
Reader: issueops.MoleculeReader{BatchGetter: s.issueBatchGetter, Relations: s.issueRelations, EdgeReader: s.issueEdges},
|
||||
Claimer: checkedClaimer{inner: s.issueClaimer},
|
||||
Lifecycle: checkedLifecycle{inner: s.issueLifecycle},
|
||||
}), nil
|
||||
}
|
||||
var src uow.MoleculeStepperSource = timedProvider{inner: s.provider, rec: requestInfo(r.Context())}
|
||||
return src.MoleculeStepper()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -637,7 +637,8 @@ func TestCapabilitiesAdvertiseEveryImplementedOperation(t *testing.T) {
|
|||
// oracle rather than a second call to the code under test.
|
||||
want = append(want, "project.enforce", "issues.batchApplyLarge", "issues.list.sort", "issues.count.scope",
|
||||
"issues.sweep.wispsPlane", "issues.sweep.liveDependents", "issues.sweep.limit",
|
||||
"issues.batchApply.depAddLineage", "issues.update.allowTemplate", "issues.create.defaultPriority")
|
||||
"issues.batchApply.depAddLineage", "issues.update.allowTemplate", "issues.create.defaultPriority",
|
||||
"issues.close.autoCloseMolecule")
|
||||
slices.Sort(want)
|
||||
if !slices.Equal(got, want) {
|
||||
t.Errorf("capabilities = %v, want %v", got, want)
|
||||
|
|
|
|||
|
|
@ -3340,6 +3340,64 @@ paths:
|
|||
'503':
|
||||
$ref: '#/components/responses/Unavailable'
|
||||
|
||||
/v0/beads/issues/{id}:advanceMolecule:
|
||||
post:
|
||||
operationId: advanceMolecule
|
||||
summary: Advance a molecule to its next ready step
|
||||
description: >-
|
||||
The operation behind `bd close --continue`: after the step this path
|
||||
names closed, find where its molecule stands and, with `auto_claim`,
|
||||
claim the next ready step for `actor`.
|
||||
|
||||
|
||||
A step is READY when it is open and no open step of the same molecule
|
||||
blocks it (blocks, conditional-blocks or waits-for). The claim is a
|
||||
real claim — the step's assignee becomes `actor` — and a step another
|
||||
actor holds is skipped, never taken: a ready step lost that way, or one
|
||||
moved out of a claimable status since it was read, falls through to
|
||||
the next ready step. When every ready step is lost nothing is claimed
|
||||
and `next_step` names the first.
|
||||
|
||||
|
||||
A step in no molecule answers 200 with no `molecule_id`. A step id that
|
||||
names nothing is `404`.
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/IssueID'
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/AdvanceMoleculeRequest'
|
||||
security:
|
||||
- bearerToken: []
|
||||
responses:
|
||||
'200':
|
||||
description: Where the molecule stands, and what was claimed.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/AdvanceMoleculeResponse'
|
||||
'400':
|
||||
description: >-
|
||||
Invalid request: an unknown query parameter, an unparseable or
|
||||
oversized body, an unknown body member, or an `actor` that is empty
|
||||
after trimming, longer than 256 bytes, or carrying control
|
||||
characters.
|
||||
x-bd-codes: [invalid_argument]
|
||||
content:
|
||||
application/problem+json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Problem'
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthenticated'
|
||||
'404':
|
||||
$ref: '#/components/responses/NotFound'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalError'
|
||||
'503':
|
||||
$ref: '#/components/responses/Unavailable'
|
||||
|
||||
/v0/beads/issues/{id}:reopen:
|
||||
post:
|
||||
operationId: reopenIssue
|
||||
|
|
@ -8104,7 +8162,8 @@ components:
|
|||
`dependencies.add`, `dependencies.remove`,
|
||||
`memories.list`, `memories.get`, `memories.remember`,
|
||||
`memories.forget`, `events.list`, `events.watch`,
|
||||
`issues.casMetadata`; the behavior tokens are `project.enforce`,
|
||||
`issues.casMetadata`, `issues.advanceMolecule`; the behavior
|
||||
tokens are `project.enforce`,
|
||||
which announces that a `Bd-Project-Id` stamp for the wrong workspace
|
||||
is refused here rather than silently ignored,
|
||||
`issues.batchApplyLarge`, which announces that
|
||||
|
|
@ -8148,7 +8207,13 @@ components:
|
|||
`issues.create.defaultPriority`, which announces that a create
|
||||
(`POST /v0/beads/issues`, `issues:batchCreate` and
|
||||
`issues:batchApply` create items) with no `priority` member stores
|
||||
the default P2 rather than P0. One behavior token is
|
||||
the default P2 rather than P0, and
|
||||
`issues.close.autoCloseMolecule`, which announces that
|
||||
`POST /v0/beads/issues/{id}:close` and
|
||||
`POST /v0/beads/issues:batchClose` accept `auto_close_molecule`
|
||||
and answer `auto_closed_molecule` and
|
||||
`molecule_auto_close_refusal` rather than a `400` naming the
|
||||
member unknown. One behavior token is
|
||||
CONDITIONAL rather than build-level: `policy.external_dependencies`
|
||||
announces that this server's ready, claim, claim-next, close,
|
||||
blocking and dependency-tree operations already apply bd's
|
||||
|
|
@ -11155,6 +11220,21 @@ components:
|
|||
and it never bypasses existence: an id that names nothing refuses
|
||||
whether or not this is set. It is request-wide because the flag
|
||||
that spells it is.
|
||||
auto_close_molecule:
|
||||
type: boolean
|
||||
default: false
|
||||
description: >-
|
||||
Behind the `issues.close.autoCloseMolecule` behavior token: an
|
||||
older server answers `unknown_parameter` for this name.
|
||||
|
||||
|
||||
Close each item's molecule root when the batch completed it:
|
||||
`CloseIssueRequest.auto_close_molecule` for every item that closed
|
||||
or was already closed, run after all the closes inside the same
|
||||
transaction. A batch that closes several steps of one molecule
|
||||
decides its root once, and the root it closed, or its refusal, is
|
||||
reported on the outcome of the first successful item under that
|
||||
root.
|
||||
|
||||
BatchCloseItem:
|
||||
type: object
|
||||
|
|
@ -11276,6 +11356,15 @@ components:
|
|||
Prose for a refusal, never load-bearing and present only with
|
||||
`code`. It reflects the request and this server's own words rather
|
||||
than the role's message, for the reason `Problem.detail` gives.
|
||||
auto_closed_molecule:
|
||||
$ref: '#/components/schemas/Issue'
|
||||
molecule_auto_close_refusal:
|
||||
type: string
|
||||
description: >-
|
||||
`CloseIssueResponse.molecule_auto_close_refusal` for this item,
|
||||
under `issues.close.autoCloseMolecule`; `auto_closed_molecule`
|
||||
beside it is `CloseIssueResponse.auto_closed_molecule`. Present
|
||||
only on a successful item.
|
||||
|
||||
Blocker:
|
||||
type: object
|
||||
|
|
@ -11302,6 +11391,47 @@ components:
|
|||
`conditional-blocks`). ABSENT when the refusal did not report it,
|
||||
which is the case for an `external:` blocker.
|
||||
|
||||
AdvanceMoleculeRequest:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
required: [actor]
|
||||
properties:
|
||||
actor:
|
||||
type: string
|
||||
minLength: 1
|
||||
maxLength: 256
|
||||
pattern: '^[^\u0000-\u001F\u007F-\u009F\u2028\u2029]+$'
|
||||
description: >-
|
||||
Who advances, and with `auto_claim` the claimed step's assignee.
|
||||
`ClaimRequest.actor`'s rules exactly.
|
||||
auto_claim:
|
||||
type: boolean
|
||||
default: false
|
||||
description: >-
|
||||
Claim the next ready step for `actor`. Without it the operation
|
||||
writes nothing and only names the step.
|
||||
AdvanceMoleculeResponse:
|
||||
type: object
|
||||
required: [closed_step, complete, claimed]
|
||||
properties:
|
||||
closed_step:
|
||||
$ref: '#/components/schemas/Issue'
|
||||
molecule_id:
|
||||
type: string
|
||||
description: >-
|
||||
The step's molecule root. ABSENT when the step belongs to no
|
||||
molecule, and then nothing else below is set.
|
||||
complete:
|
||||
type: boolean
|
||||
description: >-
|
||||
Every step of the molecule is closed; `next_step` is then absent.
|
||||
next_step:
|
||||
$ref: '#/components/schemas/Issue'
|
||||
claimed:
|
||||
type: boolean
|
||||
description: >-
|
||||
`next_step` was claimed for `actor`, and is the post-claim row.
|
||||
|
||||
CloseIssueRequest:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
|
|
@ -11387,6 +11517,32 @@ components:
|
|||
member. The token spans the FULL 64-bit range, so a number would be
|
||||
rounded past 2^53 by an IEEE-754-double parser and the guard would miss a
|
||||
row nothing else touched; a string round-trips exactly in every consumer.
|
||||
auto_close_molecule:
|
||||
type: boolean
|
||||
default: false
|
||||
description: >-
|
||||
Behind the `issues.close.autoCloseMolecule` behavior token: an
|
||||
older server answers `unknown_parameter` for this name, and a
|
||||
client checks the token before sending it.
|
||||
|
||||
|
||||
Close the issue's molecule root IN THE SAME TRANSACTION when this
|
||||
close completed it: the root is an auto-closing molecule root (a
|
||||
`molecule`-typed or ephemeral root, or a template-labeled epic),
|
||||
it is open, and every step under it is now closed. The root close
|
||||
is unforced, guarded on the root revision read inside that
|
||||
transaction, and records `all steps complete` and this request's
|
||||
`session`. It runs for an idempotent re-close too, so replaying
|
||||
the close of a molecule's last step heals a root left open.
|
||||
|
||||
|
||||
OPT-IN, because an orchestrator may run its own molecule
|
||||
lifecycle. A root that its close policy refuses (a live blocker)
|
||||
or a close guard refuses (a template, a pinned root, a root
|
||||
assigned to another actor) stays open, is named in
|
||||
`molecule_auto_close_refusal`, and never fails this close. Any
|
||||
other failure of the root close, such as a storage error, fails
|
||||
this close with it.
|
||||
CloseIssueResponse:
|
||||
type: object
|
||||
required: [issue, already_closed, open_children, revision]
|
||||
|
|
@ -11431,6 +11587,18 @@ components:
|
|||
`float` — rounds anything past 2^53 to a value NEAR the token that is not
|
||||
it, so a guard composed from it is refused against a row nothing else
|
||||
touched. A string round-trips exactly in every consumer.
|
||||
auto_closed_molecule:
|
||||
$ref: '#/components/schemas/Issue'
|
||||
molecule_auto_close_refusal:
|
||||
type: string
|
||||
description: >-
|
||||
With `issues.close.autoCloseMolecule` and `auto_close_molecule`:
|
||||
why the molecule root this close completed stayed open — the
|
||||
root's own close policy refused it (a live blocker on the root),
|
||||
or a close guard did (a template, a pinned root, a root assigned
|
||||
to another actor). Prose; absent when nothing was refused. `auto_closed_molecule`,
|
||||
beside it, is the root the close also closed, absent when none
|
||||
was.
|
||||
ReopenIssueRequest:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
|
|
|
|||
87
internal/httpapi/wireshape/testdata/golden.json
vendored
87
internal/httpapi/wireshape/testdata/golden.json
vendored
|
|
@ -33,6 +33,48 @@
|
|||
"required": true,
|
||||
"item_type": "object"
|
||||
},
|
||||
{
|
||||
"schema": "AdvanceMoleculeRequest",
|
||||
"member": "actor",
|
||||
"type": "string",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"schema": "AdvanceMoleculeRequest",
|
||||
"member": "auto_claim",
|
||||
"type": "boolean",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "AdvanceMoleculeResponse",
|
||||
"member": "claimed",
|
||||
"type": "boolean",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"schema": "AdvanceMoleculeResponse",
|
||||
"member": "closed_step",
|
||||
"type": "object",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"schema": "AdvanceMoleculeResponse",
|
||||
"member": "complete",
|
||||
"type": "boolean",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"schema": "AdvanceMoleculeResponse",
|
||||
"member": "molecule_id",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "AdvanceMoleculeResponse",
|
||||
"member": "next_step",
|
||||
"type": "object",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "AnchorEdgeCount",
|
||||
"member": "count",
|
||||
|
|
@ -595,6 +637,12 @@
|
|||
"type": "string",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"schema": "BatchCloseRequest",
|
||||
"member": "auto_close_molecule",
|
||||
"type": "boolean",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BatchCloseRequest",
|
||||
"member": "force",
|
||||
|
|
@ -1166,6 +1214,12 @@
|
|||
"type": "string",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"schema": "CloseIssueRequest",
|
||||
"member": "auto_close_molecule",
|
||||
"type": "boolean",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "CloseIssueRequest",
|
||||
"member": "expected_version",
|
||||
|
|
@ -1196,12 +1250,24 @@
|
|||
"type": "boolean",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"schema": "CloseIssueResponse",
|
||||
"member": "auto_closed_molecule",
|
||||
"type": "object",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "CloseIssueResponse",
|
||||
"member": "issue",
|
||||
"type": "object",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"schema": "CloseIssueResponse",
|
||||
"member": "molecule_auto_close_refusal",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "CloseIssueResponse",
|
||||
"member": "open_children",
|
||||
|
|
@ -1226,6 +1292,12 @@
|
|||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "CloseOutcome",
|
||||
"member": "auto_closed_molecule",
|
||||
"type": "object",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "CloseOutcome",
|
||||
"member": "blockers",
|
||||
|
|
@ -1257,6 +1329,12 @@
|
|||
"type": "string",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"schema": "CloseOutcome",
|
||||
"member": "molecule_auto_close_refusal",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "CloseOutcome",
|
||||
"member": "open_children",
|
||||
|
|
@ -4866,6 +4944,13 @@
|
|||
"required": true,
|
||||
"style": "simple"
|
||||
},
|
||||
{
|
||||
"schema": "param:advanceMolecule",
|
||||
"member": "path:id",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"style": "simple"
|
||||
},
|
||||
{
|
||||
"schema": "param:claimIssue",
|
||||
"member": "path:id",
|
||||
|
|
@ -6106,6 +6191,8 @@
|
|||
"AddCommentRequest": "request",
|
||||
"AddDependenciesRequest": "request",
|
||||
"AddDependenciesResponse": "response",
|
||||
"AdvanceMoleculeRequest": "request",
|
||||
"AdvanceMoleculeResponse": "response",
|
||||
"AnchorEdgeCount": "response",
|
||||
"ApplyBatchRequest": "request",
|
||||
"ApplyBatchResponse": "response",
|
||||
|
|
|
|||
|
|
@ -32,6 +32,7 @@ go_library(
|
|||
"memories.go",
|
||||
"metadata.go",
|
||||
"metadatacas.go",
|
||||
"molecule.go",
|
||||
"offrole.go",
|
||||
"open_with.go",
|
||||
"order.go",
|
||||
|
|
@ -117,6 +118,7 @@ go_test(
|
|||
"lifecycle_update_test.go",
|
||||
"list_sort_test.go",
|
||||
"metadatacas_test.go",
|
||||
"molecule_test.go",
|
||||
"open_with_test.go",
|
||||
"race_detector_off_test.go",
|
||||
"race_detector_on_test.go",
|
||||
|
|
@ -149,6 +151,7 @@ go_test(
|
|||
"served_list_test.go",
|
||||
"served_memories_deps_test.go",
|
||||
"served_metadata_cas_test.go",
|
||||
"served_molecule_test.go",
|
||||
"served_project_swap_test.go",
|
||||
"served_querier_test.go",
|
||||
"served_reader_test.go",
|
||||
|
|
|
|||
|
|
@ -123,6 +123,11 @@ func (b *httpBatchCloser) CloseBatch(ctx context.Context, req issueops.CloseBatc
|
|||
if err != nil {
|
||||
return issueops.CloseBatchResult{}, err
|
||||
}
|
||||
// AutoCloseMolecule rides the member only where the server advertises it;
|
||||
// elsewhere the batch is refused before it is dialed (molecule.go).
|
||||
if err := b.store.requireAutoCloseMolecule(ctx, "BatchCloser.CloseBatch", req.AutoCloseMolecule); err != nil {
|
||||
return issueops.CloseBatchResult{}, err
|
||||
}
|
||||
if served {
|
||||
return b.serveBatch(ctx, req)
|
||||
}
|
||||
|
|
@ -175,7 +180,12 @@ func (b *httpBatchCloser) serveComposedSingle(ctx context.Context, req issueops.
|
|||
return issueops.CloseBatchResult{}, err
|
||||
}
|
||||
item := req.Items[0]
|
||||
res, err := b.wire.CloseIssue(ctx, item.IssueID, closeBody(req.Actor, item.Reason, req.Session, req.Force))
|
||||
body := closeBody(req.Actor, item.Reason, req.Session, req.Force)
|
||||
if req.AutoCloseMolecule {
|
||||
autoClose := true
|
||||
body.AutoCloseMolecule = &autoClose
|
||||
}
|
||||
res, err := b.wire.CloseIssue(ctx, item.IssueID, body)
|
||||
if err != nil {
|
||||
if outcome, ok := perItemCloseRefusal(item.IssueID, err); ok {
|
||||
// A per-item refusal is a RESULT and never the method's error. The
|
||||
|
|
@ -188,10 +198,12 @@ func (b *httpBatchCloser) serveComposedSingle(ctx context.Context, req issueops.
|
|||
|
||||
issue := res.Issue
|
||||
return issueops.CloseBatchResult{Outcomes: []issueops.CloseOutcome{{
|
||||
IssueID: item.IssueID,
|
||||
Issue: &issue,
|
||||
Changed: !res.AlreadyClosed,
|
||||
OpenChildren: res.OpenChildren,
|
||||
IssueID: item.IssueID,
|
||||
Issue: &issue,
|
||||
Changed: !res.AlreadyClosed,
|
||||
OpenChildren: res.OpenChildren,
|
||||
AutoClosedMolecule: res.AutoClosedMolecule,
|
||||
MoleculeAutoCloseRefusal: derefStringPtr(res.MoleculeAutoCloseRefusal),
|
||||
}}}, nil
|
||||
}
|
||||
|
||||
|
|
@ -218,6 +230,10 @@ func batchCloseBody(req issueops.CloseBatchRequest) apigen.BatchCloseRequest {
|
|||
force := true
|
||||
body.Force = &force
|
||||
}
|
||||
if req.AutoCloseMolecule {
|
||||
autoClose := true
|
||||
body.AutoCloseMolecule = &autoClose
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
|
|
@ -265,6 +281,10 @@ func decodeBatchCloseOutcome(actor string, item apigen.CloseOutcome) issueops.Cl
|
|||
out.OpenChildren = *item.OpenChildren
|
||||
}
|
||||
out.Changed = item.AlreadyClosed == nil || !*item.AlreadyClosed
|
||||
out.AutoClosedMolecule = item.AutoClosedMolecule
|
||||
if item.MoleculeAutoCloseRefusal != nil {
|
||||
out.MoleculeAutoCloseRefusal = *item.MoleculeAutoCloseRefusal
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ package httpclient
|
|||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
|
|
@ -66,6 +67,15 @@ func (g *httpBatchGetter) GetMany(ctx context.Context, req issueops.GetManyReque
|
|||
return issueops.GetManyResult{Issues: []*issueops.Issue{}, Missing: []string{}}, nil
|
||||
}
|
||||
|
||||
token, _ := wire.CapabilityFor(wire.OpBatchGetIssues)
|
||||
served, err := g.store.servesCapability(ctx, token)
|
||||
if err != nil {
|
||||
return issueops.GetManyResult{}, err
|
||||
}
|
||||
if !served {
|
||||
return g.getOneAtATime(ctx, req.IDs)
|
||||
}
|
||||
|
||||
var body apigen.BatchGetIssuesResult
|
||||
if err := g.store.dispatch(ctx, wire.Request{
|
||||
Op: wire.OpBatchGetIssues,
|
||||
|
|
@ -128,3 +138,39 @@ func checkGetManyIDs(ids []string) error {
|
|||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// getOneAtATime answers a GetMany against a server that does not advertise
|
||||
// issues.batchGet with one getIssue per distinct id, in first-mention order —
|
||||
// the same rows and the same Missing a batch would answer, without its single
|
||||
// snapshot. It is a transport fallback for a capability, kept here so no
|
||||
// caller of the role has to know which servers publish the batch.
|
||||
func (g *httpBatchGetter) getOneAtATime(ctx context.Context, ids []string) (issueops.GetManyResult, error) {
|
||||
reader, err := g.store.IssueReader()
|
||||
if err != nil {
|
||||
return issueops.GetManyResult{}, err
|
||||
}
|
||||
out := issueops.GetManyResult{Issues: []*issueops.Issue{}, Missing: []string{}}
|
||||
seen := make(map[string]bool, len(ids))
|
||||
for _, id := range ids {
|
||||
if seen[id] {
|
||||
continue
|
||||
}
|
||||
seen[id] = true
|
||||
details, err := reader.Get(ctx, issueops.GetRequest{ID: id})
|
||||
if errors.Is(err, issueops.ErrNotFound) {
|
||||
out.Missing = append(out.Missing, id)
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return issueops.GetManyResult{}, err
|
||||
}
|
||||
issue := details.Issue
|
||||
if len(issue.Labels) == 0 && len(details.Labels) > 0 {
|
||||
issue.Labels = append([]string(nil), details.Labels...)
|
||||
}
|
||||
// Hydration is labels only, as the batch's is.
|
||||
issue.Dependencies, issue.Comments = nil, nil
|
||||
out.Issues = append(out.Issues, &issue)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -464,6 +464,15 @@ func (l *httpLifecycle) Close(ctx context.Context, req issueops.CloseRequest) (i
|
|||
|
||||
body := closeBody(req.Actor, req.Reason, req.Session, req.Force)
|
||||
body.ExpectedVersion = revisionGuard(req.ExpectedVersion)
|
||||
// AutoCloseMolecule rides the member only where the server advertises it;
|
||||
// elsewhere the close is refused before it is dialed (molecule.go).
|
||||
if err := l.store.requireAutoCloseMolecule(ctx, "IssueLifecycle.Close", req.AutoCloseMolecule); err != nil {
|
||||
return issueops.CloseResult{}, err
|
||||
}
|
||||
if req.AutoCloseMolecule {
|
||||
autoClose := true
|
||||
body.AutoCloseMolecule = &autoClose
|
||||
}
|
||||
res, err := l.wire.CloseIssue(ctx, req.IssueID, body)
|
||||
if err != nil {
|
||||
return issueops.CloseResult{}, err
|
||||
|
|
@ -474,11 +483,16 @@ func (l *httpLifecycle) Close(ctx context.Context, req issueops.CloseRequest) (i
|
|||
if issue.RowVersion, err = parseRevision("closeIssue", res.Revision); err != nil {
|
||||
return issueops.CloseResult{}, err
|
||||
}
|
||||
return issueops.CloseResult{
|
||||
Issue: &issue,
|
||||
Changed: !res.AlreadyClosed,
|
||||
OpenChildren: res.OpenChildren,
|
||||
}, nil
|
||||
result := issueops.CloseResult{
|
||||
Issue: &issue,
|
||||
Changed: !res.AlreadyClosed,
|
||||
OpenChildren: res.OpenChildren,
|
||||
AutoClosedMolecule: res.AutoClosedMolecule,
|
||||
}
|
||||
if res.MoleculeAutoCloseRefusal != nil {
|
||||
result.MoleculeAutoCloseRefusal = *res.MoleculeAutoCloseRefusal
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Reopen dials POST issues/{id}:reopen.
|
||||
|
|
|
|||
125
internal/httpclient/molecule.go
Normal file
125
internal/httpclient/molecule.go
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
package httpclient
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"slices"
|
||||
|
||||
"github.com/steveyegge/beads/internal/httpapi/apigen"
|
||||
"github.com/steveyegge/beads/internal/httpclient/wire"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// servesCapability reports whether the server advertises token. It forces the
|
||||
// one lazy handshake the store owns and returns that handshake's error rather
|
||||
// than reading a failure as "not served": every caller below is a write whose
|
||||
// two legs both dial, so a handshake that cannot be had means the write cannot
|
||||
// be attempted at all (servesBatchClose's reasoning).
|
||||
func (s *Store) servesCapability(ctx context.Context, token string) (bool, error) {
|
||||
snap, err := s.snapshot(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return snap != nil && slices.Contains(snap.Capabilities, token), nil
|
||||
}
|
||||
|
||||
// ServesMoleculeAutoClose implements storage.MoleculeAutoCloseProber from the
|
||||
// handshake: whether this server runs CloseRequest.AutoCloseMolecule.
|
||||
func (s *Store) ServesMoleculeAutoClose(ctx context.Context) (bool, error) {
|
||||
return s.servesCapability(ctx, wire.CapCloseAutoCloseMolecule)
|
||||
}
|
||||
|
||||
var _ storage.MoleculeAutoCloseProber = (*Store)(nil)
|
||||
|
||||
// ServesMoleculeAdvance implements storage.MoleculeAdvanceProber from the
|
||||
// handshake: whether this server serves issues.advanceMolecule.
|
||||
func (s *Store) ServesMoleculeAdvance(ctx context.Context) (bool, error) {
|
||||
token, _ := wire.CapabilityFor(wire.OpAdvanceMolecule)
|
||||
return s.servesCapability(ctx, token)
|
||||
}
|
||||
|
||||
var _ storage.MoleculeAdvanceProber = (*Store)(nil)
|
||||
|
||||
// requireAutoCloseMolecule refuses, before anything is dialed, a close that
|
||||
// asks for AutoCloseMolecule against a server that does not advertise
|
||||
// wire.CapCloseAutoCloseMolecule. The rule runs in ONE place — the server's
|
||||
// library, inside the step close's transaction — so the client never runs a
|
||||
// second, client-side copy of it, and it never drops the member and closes the
|
||||
// step without the molecule either. The refusal is the typed capability error
|
||||
// (Unsup.Capability names the token).
|
||||
func (s *Store) requireAutoCloseMolecule(ctx context.Context, op string, requested bool) error {
|
||||
if !requested {
|
||||
return nil
|
||||
}
|
||||
served, err := s.servesCapability(ctx, wire.CapCloseAutoCloseMolecule)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !served {
|
||||
return s.unsupportedCapability(op, wire.CapCloseAutoCloseMolecule)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MoleculeStepper serves the advance-a-molecule role on
|
||||
// POST /v0/beads/issues/{id}:advanceMolecule.
|
||||
func (s *Store) MoleculeStepper() (issueops.MoleculeStepper, error) {
|
||||
if _, err := s.roleWire("MoleculeStepper"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &httpMoleculeStepper{store: s}, nil
|
||||
}
|
||||
|
||||
// httpMoleculeStepper dials advanceMolecule, where the server's library runs
|
||||
// the one stepper. Against a server that does not advertise
|
||||
// issues.advanceMolecule it refuses before dialing with the typed capability
|
||||
// error; it never composes a client-side copy of the advance.
|
||||
type httpMoleculeStepper struct{ store *Store }
|
||||
|
||||
var _ issueops.MoleculeStepper = (*httpMoleculeStepper)(nil)
|
||||
|
||||
func (m *httpMoleculeStepper) Advance(ctx context.Context, req issueops.AdvanceRequest) (issueops.AdvanceResult, error) {
|
||||
if err := issueops.ValidateAdvanceRequest(req); err != nil {
|
||||
return issueops.AdvanceResult{}, err
|
||||
}
|
||||
token, _ := wire.CapabilityFor(wire.OpAdvanceMolecule)
|
||||
served, err := m.store.servesCapability(ctx, token)
|
||||
if err != nil {
|
||||
return issueops.AdvanceResult{}, err
|
||||
}
|
||||
if !served {
|
||||
return issueops.AdvanceResult{}, m.store.unsupportedCapability("MoleculeStepper.Advance", token)
|
||||
}
|
||||
|
||||
path, err := wire.IssueMethodPath(req.ClosedStepID, wire.MethodAdvanceMolecule)
|
||||
if err != nil {
|
||||
return issueops.AdvanceResult{}, err
|
||||
}
|
||||
body := apigen.AdvanceMoleculeRequest{Actor: req.Actor}
|
||||
if req.AutoClaim {
|
||||
autoClaim := true
|
||||
body.AutoClaim = &autoClaim
|
||||
}
|
||||
var res apigen.AdvanceMoleculeResponse
|
||||
if err := m.store.dispatch(ctx, wire.Request{
|
||||
Op: wire.OpAdvanceMolecule,
|
||||
Method: http.MethodPost,
|
||||
Path: path,
|
||||
Body: body,
|
||||
IssueID: req.ClosedStepID,
|
||||
}, &res); err != nil {
|
||||
return issueops.AdvanceResult{}, err
|
||||
}
|
||||
closed := res.ClosedStep
|
||||
out := issueops.AdvanceResult{
|
||||
ClosedStep: &closed,
|
||||
Complete: res.Complete,
|
||||
NextStep: res.NextStep,
|
||||
Claimed: res.Claimed,
|
||||
}
|
||||
if res.MoleculeId != nil {
|
||||
out.MoleculeID = *res.MoleculeId
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
180
internal/httpclient/molecule_test.go
Normal file
180
internal/httpclient/molecule_test.go
Normal file
|
|
@ -0,0 +1,180 @@
|
|||
package httpclient
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/httpapi/apigen"
|
||||
"github.com/steveyegge/beads/internal/httpclient/wire"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// The molecule rules run in ONE place, the server's library. Against a server
|
||||
// that does not advertise them the client refuses BEFORE dialing with the
|
||||
// typed capability error: it never drops auto_close_molecule and closes the
|
||||
// step alone, and never runs a client-side copy of the auto-close or advance.
|
||||
|
||||
func requireCapabilityRefusal(t *testing.T, err error, token string, w *stubWire) {
|
||||
t.Helper()
|
||||
if err == nil {
|
||||
t.Fatal("no error, want a pre-dial capability refusal")
|
||||
}
|
||||
var unsup *storage.ErrUnsupported
|
||||
if !errors.As(err, &unsup) {
|
||||
t.Fatalf("errors.As to *storage.ErrUnsupported failed for %v", err)
|
||||
}
|
||||
if unsup.Capability != token {
|
||||
t.Errorf("Capability = %q, want %q", unsup.Capability, token)
|
||||
}
|
||||
if len(w.calls) != 0 {
|
||||
t.Errorf("dialed %v, want none: a pre-dial refusal must never reach the wire", w.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutoCloseMoleculeRefusesBeforeDialingWhenUnadvertised(t *testing.T) {
|
||||
close := issueops.CloseRequest{Actor: "alice", IssueID: "bd-1", AutoCloseMolecule: true}
|
||||
|
||||
t.Run("Close", func(t *testing.T) {
|
||||
w := &stubWire{close: &apigen.CloseIssueResponse{Revision: "0"}}
|
||||
lifecycle, err := stubStore(t, w).IssueLifecycle()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = lifecycle.Close(t.Context(), close)
|
||||
requireCapabilityRefusal(t, err, wire.CapCloseAutoCloseMolecule, w)
|
||||
})
|
||||
|
||||
for name, caps := range map[string][]string{
|
||||
"CloseBatch served": {"issues.close", "issues.batchClose"},
|
||||
"CloseBatch composed": {"issues.close"},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
w := &stubWire{}
|
||||
closer, err := New(testTarget(t), w, &apigen.ContextResponse{BdVersion: "1.2.3", Capabilities: caps}).BatchCloser()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = closer.CloseBatch(t.Context(), issueops.CloseBatchRequest{
|
||||
Actor: "alice", Items: []issueops.BatchCloseItem{{IssueID: "bd-1"}}, AutoCloseMolecule: true,
|
||||
})
|
||||
requireCapabilityRefusal(t, err, wire.CapCloseAutoCloseMolecule, w)
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("without the flag a close still dials", func(t *testing.T) {
|
||||
w := &stubWire{close: &apigen.CloseIssueResponse{Revision: "0"}}
|
||||
lifecycle, err := stubStore(t, w).IssueLifecycle()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
plain := close
|
||||
plain.AutoCloseMolecule = false
|
||||
if _, err := lifecycle.Close(t.Context(), plain); err != nil {
|
||||
t.Fatalf("Close: %v", err)
|
||||
}
|
||||
if w.lastClose.AutoCloseMolecule != nil {
|
||||
t.Errorf("auto_close_molecule = %v, want absent when not asked for", *w.lastClose.AutoCloseMolecule)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestAutoCloseMoleculeRidesTheMemberWhenAdvertised(t *testing.T) {
|
||||
snap := &apigen.ContextResponse{BdVersion: "1.2.3", Capabilities: []string{
|
||||
"issues.close", "issues.batchClose", wire.CapCloseAutoCloseMolecule,
|
||||
}}
|
||||
root := types.Issue{ID: "bd-root", Status: types.StatusClosed}
|
||||
|
||||
t.Run("Close", func(t *testing.T) {
|
||||
w := &stubWire{close: &apigen.CloseIssueResponse{Revision: "0", AutoClosedMolecule: &root}}
|
||||
lifecycle, err := New(testTarget(t), w, snap).IssueLifecycle()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res, err := lifecycle.Close(t.Context(), issueops.CloseRequest{Actor: "alice", IssueID: "bd-1", AutoCloseMolecule: true})
|
||||
if err != nil {
|
||||
t.Fatalf("Close: %v", err)
|
||||
}
|
||||
if w.lastClose.AutoCloseMolecule == nil || !*w.lastClose.AutoCloseMolecule {
|
||||
t.Errorf("auto_close_molecule = %v, want true", w.lastClose.AutoCloseMolecule)
|
||||
}
|
||||
if res.AutoClosedMolecule == nil || res.AutoClosedMolecule.ID != "bd-root" {
|
||||
t.Errorf("AutoClosedMolecule = %+v, want bd-root", res.AutoClosedMolecule)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("CloseBatch", func(t *testing.T) {
|
||||
w := &stubWire{batchClose: &apigen.BatchCloseResponse{Outcomes: []apigen.CloseOutcome{{
|
||||
IssueId: "bd-1", Issue: &types.Issue{ID: "bd-1", Status: types.StatusClosed}, AutoClosedMolecule: &root,
|
||||
}}}}
|
||||
closer, err := New(testTarget(t), w, snap).BatchCloser()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res, err := closer.CloseBatch(t.Context(), issueops.CloseBatchRequest{
|
||||
Actor: "alice", Items: []issueops.BatchCloseItem{{IssueID: "bd-1"}}, AutoCloseMolecule: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CloseBatch: %v", err)
|
||||
}
|
||||
if w.lastBatchClose.AutoCloseMolecule == nil || !*w.lastBatchClose.AutoCloseMolecule {
|
||||
t.Errorf("auto_close_molecule = %v, want true", w.lastBatchClose.AutoCloseMolecule)
|
||||
}
|
||||
if len(res.Outcomes) != 1 || res.Outcomes[0].AutoClosedMolecule == nil || res.Outcomes[0].AutoClosedMolecule.ID != "bd-root" {
|
||||
t.Errorf("Outcomes = %+v, want bd-1 reporting bd-root auto-closed", res.Outcomes)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestAdvanceMoleculeRefusesBeforeDialingWhenUnadvertised(t *testing.T) {
|
||||
token, ok := wire.CapabilityFor(wire.OpAdvanceMolecule)
|
||||
if !ok || token == "" {
|
||||
t.Fatal("advanceMolecule has no capability token")
|
||||
}
|
||||
w := &stubWire{}
|
||||
stepper, err := stubStore(t, w).MoleculeStepper()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = stepper.Advance(t.Context(), issueops.AdvanceRequest{Actor: "alice", ClosedStepID: "bd-1", AutoClaim: true})
|
||||
requireCapabilityRefusal(t, err, token, w)
|
||||
}
|
||||
|
||||
// The CLI asks for the auto-close only where the route serves it
|
||||
// (storage.ServesMoleculeAutoClose): a server silent on the token owns the
|
||||
// molecule's auto-close, and a close there goes out without the member.
|
||||
func TestServesMoleculeAutoCloseFollowsTheHandshake(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
silent := New(testTarget(t), &stubWire{}, &apigen.ContextResponse{BdVersion: "1.2.3", Capabilities: []string{"issues.close"}})
|
||||
if storage.ServesMoleculeAutoClose(ctx, silent) {
|
||||
t.Error("ServesMoleculeAutoClose = true against a server silent on the token")
|
||||
}
|
||||
served := New(testTarget(t), &stubWire{}, &apigen.ContextResponse{BdVersion: "1.2.3", Capabilities: []string{"issues.close", wire.CapCloseAutoCloseMolecule}})
|
||||
if !storage.ServesMoleculeAutoClose(ctx, served) {
|
||||
t.Error("ServesMoleculeAutoClose = false against a server advertising the token")
|
||||
}
|
||||
}
|
||||
|
||||
// `bd close --continue` asks storage.ServesMoleculeAdvance before it closes,
|
||||
// so a server silent on issues.advanceMolecule is refused up front instead of
|
||||
// after the step's close has committed. A handshake that fails is that error,
|
||||
// not a yes: answering true would close the step and then fail the advance,
|
||||
// the half-done state the probe exists to prevent.
|
||||
func TestServesMoleculeAdvanceFollowsTheHandshake(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
token, _ := wire.CapabilityFor(wire.OpAdvanceMolecule)
|
||||
silent := New(testTarget(t), &stubWire{}, &apigen.ContextResponse{BdVersion: "1.2.3", Capabilities: []string{"issues.close"}})
|
||||
if served, err := storage.ServesMoleculeAdvance(ctx, silent); served || err != nil {
|
||||
t.Errorf("ServesMoleculeAdvance = (%v, %v) against a server silent on the token, want (false, nil)", served, err)
|
||||
}
|
||||
advertised := New(testTarget(t), &stubWire{}, &apigen.ContextResponse{BdVersion: "1.2.3", Capabilities: []string{"issues.close", token}})
|
||||
if served, err := storage.ServesMoleculeAdvance(ctx, advertised); !served || err != nil {
|
||||
t.Errorf("ServesMoleculeAdvance = (%v, %v) against a server advertising the token, want (true, nil)", served, err)
|
||||
}
|
||||
boom := errors.New("handshake failed")
|
||||
failed := New(testTarget(t), handshakeWire{stubWire: &stubWire{}, err: boom}, nil)
|
||||
if served, err := storage.ServesMoleculeAdvance(ctx, failed); served || !errors.Is(err, boom) {
|
||||
t.Errorf("ServesMoleculeAdvance = (%v, %v) when the handshake fails, want (false, the handshake's error)", served, err)
|
||||
}
|
||||
}
|
||||
|
|
@ -168,7 +168,35 @@ func (r httpEdgeReader) ReadEdges(ctx context.Context, req issueops.EdgeReadRequ
|
|||
if len(ids) == 0 {
|
||||
return issueops.EdgeReadResult{Anchors: []issueops.AnchorEdges{}}, nil
|
||||
}
|
||||
// The ROLE has no anchor cap; the OPERATION refuses more than
|
||||
// maxEdgeReadAnchors per request. Splitting is therefore this transport's
|
||||
// job, never the caller's: each chunk is one round trip and the answers
|
||||
// concatenate in request order. A read loses nothing by being split — the
|
||||
// one property it gives up is the single snapshot across chunks, which
|
||||
// per-anchor answers do not rely on.
|
||||
if len(ids) > maxEdgeReadAnchors {
|
||||
anchors := make([]issueops.AnchorEdges, 0, len(ids))
|
||||
for start := 0; start < len(ids); start += maxEdgeReadAnchors {
|
||||
end := min(start+maxEdgeReadAnchors, len(ids))
|
||||
part, err := r.readEdgeChunk(ctx, ids[start:end], req.Types)
|
||||
if err != nil {
|
||||
return issueops.EdgeReadResult{}, err
|
||||
}
|
||||
anchors = append(anchors, part.Anchors...)
|
||||
}
|
||||
return issueops.EdgeReadResult{Anchors: anchors}, nil
|
||||
}
|
||||
return r.readEdgeChunk(ctx, ids, req.Types)
|
||||
}
|
||||
|
||||
// maxEdgeReadAnchors is the listDependencies operation's cap on `issue_id`
|
||||
// values (maxDependencyAnchors in internal/httpapi), redeclared because a
|
||||
// client does not import the server.
|
||||
const maxEdgeReadAnchors = 100
|
||||
|
||||
// readEdgeChunk answers at most maxEdgeReadAnchors distinct ids in one call.
|
||||
func (r httpEdgeReader) readEdgeChunk(ctx context.Context, ids []string, edgeTypes []types.DependencyType) (issueops.EdgeReadResult, error) {
|
||||
req := issueops.EdgeReadRequest{IDs: ids, Types: edgeTypes}
|
||||
q := url.Values{}
|
||||
for _, id := range ids {
|
||||
q.Add("issue_id", id)
|
||||
|
|
|
|||
235
internal/httpclient/served_molecule_test.go
Normal file
235
internal/httpclient/served_molecule_test.go
Normal file
|
|
@ -0,0 +1,235 @@
|
|||
//go:build cgo
|
||||
|
||||
package httpclient
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/backend/conformance"
|
||||
"github.com/steveyegge/beads/internal/httpclient/wire"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// The molecule contract against the served surface: the client sends
|
||||
// auto_close_molecule and dials advanceMolecule, so the server's library runs
|
||||
// the auto-close in the step close's transaction and the advance server-side.
|
||||
//
|
||||
// Against a server whose handshake lacks the two molecule tokens (an older
|
||||
// server) the client refuses before dialing; the served refusal test below
|
||||
// pins that the step it was asked to close stays open and unclaimed.
|
||||
|
||||
func moleculeContractCases() []struct {
|
||||
name string
|
||||
run func(*testing.T, context.Context, conformance.MoleculeFixture)
|
||||
} {
|
||||
return []struct {
|
||||
name string
|
||||
run func(*testing.T, context.Context, conformance.MoleculeFixture)
|
||||
}{
|
||||
{"CloseAutoClosesTheCompletedRoot", conformance.RunMoleculeCloseAutoClosesTheCompletedRoot},
|
||||
{"AutoCloseIsOptInAndRuleBound", conformance.RunMoleculeAutoCloseIsOptInAndRuleBound},
|
||||
{"RecloseHealsAStrandedRoot", conformance.RunMoleculeRecloseHealsAStrandedRoot},
|
||||
{"BatchCloseAutoClosesTheRootOnce", conformance.RunMoleculeBatchCloseAutoClosesTheRootOnce},
|
||||
{"RefusedRootKeepsTheStepClose", conformance.RunMoleculeRefusedRootKeepsTheStepClose},
|
||||
{"GuardedRootKeepsTheStepClose", conformance.RunMoleculeGuardedRootKeepsTheStepClose},
|
||||
{"StepperClaimsTheNextReadyStepForTheActor", conformance.RunMoleculeStepperClaimsTheNextReadyStepForTheActor},
|
||||
{"StepperNeverTakesAStepAnotherActorHolds", conformance.RunMoleculeStepperNeverTakesAStepAnotherActorHolds},
|
||||
{"StepperAnswersCompleteAndOutsideAMolecule", conformance.RunMoleculeStepperAnswersCompleteAndOutsideAMolecule},
|
||||
{"StepperClaimsAWispStep", conformance.RunMoleculeStepperClaimsAWispStep},
|
||||
}
|
||||
}
|
||||
|
||||
func newServedMoleculeFixture(t *testing.T, env *servedEnv, subject *Store) conformance.MoleculeFixture {
|
||||
t.Helper()
|
||||
lifecycle, err := subject.IssueLifecycle()
|
||||
if err != nil {
|
||||
t.Fatalf("IssueLifecycle(): %v", err)
|
||||
}
|
||||
closer, err := subject.BatchCloser()
|
||||
if err != nil {
|
||||
t.Fatalf("BatchCloser(): %v", err)
|
||||
}
|
||||
stepper, err := subject.MoleculeStepper()
|
||||
if err != nil {
|
||||
t.Fatalf("MoleculeStepper(): %v", err)
|
||||
}
|
||||
return conformance.MoleculeFixture{
|
||||
IssuePrefix: env.prefix,
|
||||
Lifecycle: lifecycle,
|
||||
BatchCloser: closer,
|
||||
Stepper: stepper,
|
||||
CreateIssue: env.createIssue,
|
||||
CreateWisp: env.createWisp,
|
||||
AddDependency: env.addDependency,
|
||||
QueryScalar: env.queryScalar,
|
||||
}
|
||||
}
|
||||
|
||||
// degradedSubject is a client of env's server whose handshake lacks tokens, as
|
||||
// an older server's would.
|
||||
func degradedSubject(t *testing.T, env *servedEnv, strike ...string) *Store {
|
||||
t.Helper()
|
||||
snapshot, err := env.subject.snapshot(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("handshake: %v", err)
|
||||
}
|
||||
for _, token := range strike {
|
||||
if !slices.Contains(snapshot.Capabilities, token) {
|
||||
t.Fatalf("the served build does not advertise %q; the degraded arm would prove nothing", token)
|
||||
}
|
||||
}
|
||||
masked := *snapshot
|
||||
masked.Capabilities = slices.DeleteFunc(slices.Clone(snapshot.Capabilities), func(token string) bool {
|
||||
return slices.Contains(strike, token)
|
||||
})
|
||||
return New(env.subject.target, env.subject.wire, &masked)
|
||||
}
|
||||
|
||||
func advanceToken(t *testing.T) string {
|
||||
t.Helper()
|
||||
token, ok := wire.CapabilityFor(wire.OpAdvanceMolecule)
|
||||
if !ok || token == "" {
|
||||
t.Fatal("advanceMolecule has no capability token")
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
func TestServedMoleculeContract(t *testing.T) {
|
||||
for _, tc := range moleculeContractCases() {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
env := newServedEnv(t, "hmol")
|
||||
tc.run(t, t.Context(), newServedMoleculeFixture(t, env, env.subject))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Against an older server (the molecule tokens struck from the handshake) a
|
||||
// close that asks for the auto-close and an advance are refused before they
|
||||
// are dialed: the step stays open, nothing is claimed, and the refusal names
|
||||
// the missing token.
|
||||
func TestServedMoleculeRefusesAgainstAnOlderServer(t *testing.T) {
|
||||
env := newServedEnv(t, "hmold")
|
||||
ctx := t.Context()
|
||||
subject := degradedSubject(t, env, wire.CapCloseAutoCloseMolecule, advanceToken(t))
|
||||
fixture := newServedMoleculeFixture(t, env, subject)
|
||||
for _, issue := range []*types.Issue{
|
||||
{ID: "hmold-r", Title: "root", IssueType: types.TypeMolecule, Status: types.StatusOpen},
|
||||
{ID: "hmold-r.1", Title: "step", IssueType: types.TypeTask, Status: types.StatusOpen},
|
||||
{ID: "hmold-r.2", Title: "next", IssueType: types.TypeTask, Status: types.StatusOpen},
|
||||
} {
|
||||
if err := env.createIssue(ctx, issue, "t"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, child := range []string{"hmold-r.1", "hmold-r.2"} {
|
||||
if err := env.addDependency(ctx, &types.Dependency{IssueID: child, DependsOnID: "hmold-r", Type: types.DepParentChild}, "t"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
status := func(id string) string {
|
||||
t.Helper()
|
||||
got, err := env.subject.GetIssue(ctx, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(got.Status) + "/" + got.Assignee
|
||||
}
|
||||
requireRefusal := func(what string, err error, token string) {
|
||||
t.Helper()
|
||||
var unsup *storage.ErrUnsupported
|
||||
if !errors.As(err, &unsup) || unsup.Capability != token {
|
||||
t.Fatalf("%s = %v, want the pre-dial refusal naming %q", what, err, token)
|
||||
}
|
||||
}
|
||||
|
||||
_, err := fixture.Lifecycle.Close(ctx, issueops.CloseRequest{Actor: "alice", IssueID: "hmold-r.1", AutoCloseMolecule: true})
|
||||
requireRefusal("Close", err, wire.CapCloseAutoCloseMolecule)
|
||||
_, err = fixture.BatchCloser.CloseBatch(ctx, issueops.CloseBatchRequest{
|
||||
Actor: "alice", Items: []issueops.BatchCloseItem{{IssueID: "hmold-r.1"}}, AutoCloseMolecule: true,
|
||||
})
|
||||
requireRefusal("CloseBatch", err, wire.CapCloseAutoCloseMolecule)
|
||||
if got := status("hmold-r.1"); got != "open/" {
|
||||
t.Errorf("the refused close's step = %s, want open/ (nothing dialed)", got)
|
||||
}
|
||||
|
||||
_, err = fixture.Stepper.Advance(ctx, issueops.AdvanceRequest{Actor: "alice", ClosedStepID: "hmold-r.1", AutoClaim: true})
|
||||
requireRefusal("Advance", err, advanceToken(t))
|
||||
if got := status("hmold-r.2"); got != "open/" {
|
||||
t.Errorf("the refused advance's next step = %s, want open/ (nothing claimed)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The ROLE has no anchor cap and the operation refuses more than 100: the
|
||||
// client splits, and every anchor comes back once, in request order.
|
||||
func TestServedEdgeReaderSplitsPastTheWireCap(t *testing.T) {
|
||||
env := newServedEnv(t, "hedgecap")
|
||||
ctx := t.Context()
|
||||
if err := env.createIssue(ctx, &types.Issue{ID: "hedgecap-a", Title: "a", IssueType: types.TypeTask, Status: types.StatusOpen}, "t"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := env.createIssue(ctx, &types.Issue{ID: "hedgecap-b", Title: "b", IssueType: types.TypeTask, Status: types.StatusOpen}, "t"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := env.addDependency(ctx, &types.Dependency{IssueID: "hedgecap-b", DependsOnID: "hedgecap-a", Type: types.DepBlocks}, "t"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ids := make([]string, 0, 250)
|
||||
for i := range 248 {
|
||||
ids = append(ids, fmt.Sprintf("hedgecap-missing-%03d", i))
|
||||
}
|
||||
ids = append(ids, "hedgecap-a", "hedgecap-b")
|
||||
reader, err := env.subject.EdgeReader()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res, err := reader.ReadEdges(ctx, issueops.EdgeReadRequest{IDs: ids})
|
||||
if err != nil {
|
||||
t.Fatalf("ReadEdges over %d anchors: %v", len(ids), err)
|
||||
}
|
||||
if len(res.Anchors) != len(ids) {
|
||||
t.Fatalf("ReadEdges answered %d anchors for %d", len(res.Anchors), len(ids))
|
||||
}
|
||||
for i, anchor := range res.Anchors {
|
||||
if anchor.ID != ids[i] {
|
||||
t.Fatalf("anchor %d = %s, want %s (request order)", i, anchor.ID, ids[i])
|
||||
}
|
||||
}
|
||||
last := res.Anchors[len(res.Anchors)-1]
|
||||
if last.Missing || len(last.Edges) != 1 || last.Edges[0].DependsOnID != "hedgecap-a" {
|
||||
t.Errorf("hedgecap-b = %+v, want its one edge to hedgecap-a", last)
|
||||
}
|
||||
if !res.Anchors[0].Missing {
|
||||
t.Errorf("an id naming nothing was not reported missing: %+v", res.Anchors[0])
|
||||
}
|
||||
}
|
||||
|
||||
// Against a server without issues.batchGet the role still answers: one
|
||||
// getIssue per distinct id, the same rows and the same Missing.
|
||||
func TestServedBatchGetterAnswersAgainstAServerWithoutTheBatch(t *testing.T) {
|
||||
env := newServedEnv(t, "hbgfb")
|
||||
ctx := t.Context()
|
||||
if err := env.createIssue(ctx, &types.Issue{ID: "hbgfb-a", Title: "a", IssueType: types.TypeTask, Status: types.StatusOpen, Labels: []string{"x"}}, "t"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
batchGet, _ := wire.CapabilityFor(wire.OpBatchGetIssues)
|
||||
getter, err := degradedSubject(t, env, batchGet).BatchGetter()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res, err := getter.GetMany(ctx, issueops.GetManyRequest{IDs: []string{"hbgfb-a", "hbgfb-nope", "hbgfb-a"}})
|
||||
if err != nil {
|
||||
t.Fatalf("GetMany without issues.batchGet: %v", err)
|
||||
}
|
||||
if len(res.Issues) != 1 || res.Issues[0].ID != "hbgfb-a" || !slices.Equal(res.Issues[0].Labels, []string{"x"}) || res.Issues[0].RowVersion == 0 {
|
||||
t.Errorf("Issues = %+v, want hbgfb-a once, labeled, with its revision", res.Issues)
|
||||
}
|
||||
if !slices.Equal(res.Missing, []string{"hbgfb-nope"}) {
|
||||
t.Errorf("Missing = %v, want [hbgfb-nope]", res.Missing)
|
||||
}
|
||||
}
|
||||
|
|
@ -732,4 +732,4 @@ func (unsupportedDoltStorage) VersionReconciler() (_ issueops.VersionReconciler,
|
|||
return
|
||||
}
|
||||
|
||||
// NOTE: partial shell (143 of 200 methods generated; 57 left to this package's hand-written set).
|
||||
// NOTE: partial shell (143 of 201 methods generated; 58 left to this package's hand-written set).
|
||||
|
|
|
|||
|
|
@ -107,6 +107,9 @@ var opCapability = map[string]string{
|
|||
// with a typed capability error instead of dialing a path the older server
|
||||
// would answer as a claim of an issue called ":reclaim".
|
||||
OpReclaimIssues: "issues.reclaim",
|
||||
// The advance-a-molecule role (molecule.go) dials it when served and
|
||||
// refuses before dialing when not; it never composes a client-side copy.
|
||||
OpAdvanceMolecule: "issues.advanceMolecule",
|
||||
}
|
||||
|
||||
// CapProjectEnforce is the behavior capability the server advertises to announce
|
||||
|
|
@ -230,6 +233,16 @@ const CapIssuesUpdateAllowTemplate = "issues.update.allowTemplate"
|
|||
// issueops.DefaultCreatePriority explicitly (pinCreateDefaultPriority).
|
||||
const CapIssuesCreateDefaultPriority = "issues.create.defaultPriority"
|
||||
|
||||
// CapCloseAutoCloseMolecule is the behavior capability announcing that
|
||||
// closeIssue and batchCloseIssues accept `auto_close_molecule` and answer
|
||||
// the auto-closed root, spelled exactly as httpapi's
|
||||
// CapIssuesCloseAutoCloseMolecule. lifecycle.go and batchcloser.go send the
|
||||
// member only when this is advertised; against an older server a close that
|
||||
// asks for it is refused before it is dialed with the typed capability
|
||||
// error — never a silent drop, and never a second, client-side copy of the
|
||||
// rule.
|
||||
const CapCloseAutoCloseMolecule = "issues.close.autoCloseMolecule"
|
||||
|
||||
// CapExternalDependencies is the CONDITIONAL behavior capability announcing
|
||||
// that the ready, claim and close operations of this server apply bd's
|
||||
// external-dependency policy themselves, spelled exactly as httpapi's constant
|
||||
|
|
@ -369,6 +382,7 @@ var behaviorCapabilities = []string{
|
|||
CapProjectEnforce, CapBatchApplyLarge, CapListSort, CapCountScope,
|
||||
CapSweepWispsPlane, CapSweepLiveDependents, CapSweepLimit,
|
||||
CapBatchApplyDepAddLineage, CapIssuesUpdateAllowTemplate, CapIssuesCreateDefaultPriority,
|
||||
CapCloseAutoCloseMolecule,
|
||||
}
|
||||
|
||||
// CapabilityFor reports the capability token gating op, and whether op is on
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ const (
|
|||
OpGetIssue = "getIssue"
|
||||
OpClaimIssue = "claimIssue"
|
||||
OpCloseIssue = "closeIssue"
|
||||
OpAdvanceMolecule = "advanceMolecule"
|
||||
OpReopenIssue = "reopenIssue"
|
||||
OpUpdateIssue = "updateIssue"
|
||||
OpSweepIssues = "sweepIssues"
|
||||
|
|
@ -98,11 +99,12 @@ const (
|
|||
// its colon must be literal — which is the whole reason escapeSegment escapes a
|
||||
// colon inside the id itself.
|
||||
const (
|
||||
MethodClaim = ":claim"
|
||||
MethodClose = ":close"
|
||||
MethodReopen = ":reopen"
|
||||
MethodRelease = ":release"
|
||||
MethodCASMetadata = ":casMetadata"
|
||||
MethodClaim = ":claim"
|
||||
MethodClose = ":close"
|
||||
MethodReopen = ":reopen"
|
||||
MethodAdvanceMolecule = ":advanceMolecule"
|
||||
MethodRelease = ":release"
|
||||
MethodCASMetadata = ":casMetadata"
|
||||
)
|
||||
|
||||
// The sub-resource collections that hang off the issue-detail path. Unlike a
|
||||
|
|
@ -128,7 +130,7 @@ func IssuePath(id string) (string, error) {
|
|||
// final segment: /v0/beads/issues/{id}:claim and its two siblings.
|
||||
func IssueMethodPath(id, method string) (string, error) {
|
||||
switch method {
|
||||
case MethodClaim, MethodClose, MethodReopen, MethodRelease, MethodCASMetadata:
|
||||
case MethodClaim, MethodClose, MethodReopen, MethodRelease, MethodCASMetadata, MethodAdvanceMolecule:
|
||||
default:
|
||||
return "", fmt.Errorf("no custom method %q on the issue resource", method)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -110,17 +110,18 @@ func TestAgainstAFirstSliceServerEveryPostBaselineOperationRefusesWithCaseTwoDat
|
|||
t.Fatalf("post-baseline ops on a first-slice token = %v, want exactly [claimIssue]", compat)
|
||||
}
|
||||
// The dimension is pinned so the matrix cannot shrink silently: the first
|
||||
// slice served six operations and the tip surface has forty-three, so
|
||||
// thirty-seven of them are things a first-slice server has never heard of. The
|
||||
// slice served six operations and the tip surface has forty-four, so
|
||||
// thirty-eight of them are things a first-slice server has never heard of. The
|
||||
// wire wave moved this from twenty-seven to thirty — claimNext, release and
|
||||
// count — wave 2 to thirty-two, adding the dependency-edge count and the
|
||||
// related read, the mini-sync to thirty-five: the comment write and the two
|
||||
// config writes, the batch read (upstream #7248) to thirty-six, and the
|
||||
// stale-lease sweep to thirty-seven. Each is
|
||||
// an operation a first-slice server never served and this client does not
|
||||
// yet dial, which is exactly the shape the refusal matrix is about.
|
||||
if len(refused) != 37 {
|
||||
t.Fatalf("the post-baseline set has %d operations a first-slice server never served, want 37", len(refused))
|
||||
// yet dial, which is exactly the shape the refusal matrix is about. The
|
||||
// molecule advance (S16) makes thirty-eight.
|
||||
if len(refused) != 38 {
|
||||
t.Fatalf("the post-baseline set has %d operations a first-slice server never served, want 38", len(refused))
|
||||
}
|
||||
|
||||
// The compat op forces the handshake yet preflights clean: issues.claim is on
|
||||
|
|
|
|||
|
|
@ -69,6 +69,7 @@ func TestOperationIdsMatchTheServerRouteTable(t *testing.T) {
|
|||
{OpWatchEvents, httpapi.OpWatchEvents},
|
||||
{OpBatchGetIssues, httpapi.OpBatchGetIssues},
|
||||
{OpReclaimIssues, httpapi.OpReclaimIssues},
|
||||
{OpAdvanceMolecule, httpapi.OpAdvanceMolecule},
|
||||
}
|
||||
|
||||
// The table is a HAND LIST, and a hand list's failure mode is omission: a new
|
||||
|
|
@ -200,10 +201,11 @@ func TestTheProjectIdentityVocabularyMatchesTheServer(t *testing.T) {
|
|||
httpapi.CapProjectEnforce, httpapi.CapBatchApplyLarge, httpapi.CapIssuesListSort, httpapi.CapIssuesCountScope,
|
||||
httpapi.CapIssuesSweepWispsPlane, httpapi.CapIssuesSweepLiveDependents, httpapi.CapIssuesSweepLimit,
|
||||
httpapi.CapBatchApplyDepAddLineage, httpapi.CapIssuesUpdateAllowTemplate, httpapi.CapIssuesCreateDefaultPriority,
|
||||
httpapi.CapIssuesCloseAutoCloseMolecule,
|
||||
}) {
|
||||
t.Errorf("behaviorCapabilities = %v, want the server's project.enforce, issues.batchApplyLarge, issues.list.sort, "+
|
||||
"issues.count.scope, issues.sweep.wispsPlane, issues.sweep.liveDependents, issues.sweep.limit and "+
|
||||
"issues.batchApply.depAddLineage and issues.update.allowTemplate and issues.create.defaultPriority tokens", behaviorCapabilities)
|
||||
"issues.batchApply.depAddLineage, issues.update.allowTemplate, issues.create.defaultPriority and issues.close.autoCloseMolecule tokens", behaviorCapabilities)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -192,6 +192,13 @@ func writeShapes() []writeShape {
|
|||
// (#5506) and the client wave sends it (ga-jbuyf), so it left
|
||||
// the pending set for this one.
|
||||
"ExpectedVersion": member("expected_version"),
|
||||
// Sent where issues.close.autoCloseMolecule is advertised.
|
||||
// Against a server that does not advertise it, a close that
|
||||
// asks for it is refused before dialing (the typed
|
||||
// storage.ErrUnsupported naming the token), and bd close
|
||||
// sends the close without it and prints the unserved
|
||||
// notice instead (S16).
|
||||
"AutoCloseMolecule": member("auto_close_molecule"),
|
||||
},
|
||||
},
|
||||
{
|
||||
|
|
@ -456,10 +463,11 @@ func writeShapes() []writeShape {
|
|||
source: reflect.TypeOf(issueops.CloseBatchRequest{}),
|
||||
body: reflect.TypeOf(apigen.BatchCloseRequest{}),
|
||||
carried: map[string]carriage{
|
||||
"Actor": member("actor"),
|
||||
"Items": member("items"),
|
||||
"Session": member("session"),
|
||||
"Force": member("force"),
|
||||
"Actor": member("actor"),
|
||||
"Items": member("items"),
|
||||
"Session": member("session"),
|
||||
"Force": member("force"),
|
||||
"AutoCloseMolecule": member("auto_close_molecule"),
|
||||
},
|
||||
},
|
||||
{
|
||||
|
|
|
|||
|
|
@ -41,6 +41,7 @@ go_library(
|
|||
"hook_lease_reclaimer.go",
|
||||
"hook_memories.go",
|
||||
"hook_metadata_cas.go",
|
||||
"hook_molecule_stepper.go",
|
||||
"hook_querier.go",
|
||||
"hook_ready_claimer.go",
|
||||
"hook_ready_counter.go",
|
||||
|
|
|
|||
|
|
@ -52,6 +52,7 @@ go_library(
|
|||
"merge_slot.go",
|
||||
"metadata_cas.go",
|
||||
"metadata_schema.go",
|
||||
"molecule_stepper.go",
|
||||
"open.go",
|
||||
"provenance.go",
|
||||
"pull_report.go",
|
||||
|
|
@ -285,6 +286,7 @@ go_test(
|
|||
"metadata_validation_test.go",
|
||||
"migration_0052_test.go",
|
||||
"mixed_table_lifecycle_test.go",
|
||||
"molecule_contract_test.go",
|
||||
"multistore_multiprocess_test.go",
|
||||
"open_test.go",
|
||||
"pool_timeouts_test.go",
|
||||
|
|
|
|||
266
internal/storage/dolt/molecule_contract_test.go
Normal file
266
internal/storage/dolt/molecule_contract_test.go
Normal file
|
|
@ -0,0 +1,266 @@
|
|||
package dolt
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/backend/conformance"
|
||||
"github.com/steveyegge/beads/internal/storage/issueops"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
publicops "github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// TestMoleculeContract runs the molecule contract (in-transaction auto-close on
|
||||
// Lifecycle.Close and BatchCloser.CloseBatch, and the MoleculeStepper) against
|
||||
// the server-backed store. One store, sequential subtests, ids namespaced by
|
||||
// the fixture prefix.
|
||||
func TestMoleculeContract(t *testing.T) {
|
||||
fixture, ctx, cleanup := newDoltMoleculeFixture(t, "mol")
|
||||
defer cleanup()
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
run func(*testing.T, context.Context, conformance.MoleculeFixture)
|
||||
}{
|
||||
{"CloseAutoClosesTheCompletedRoot", conformance.RunMoleculeCloseAutoClosesTheCompletedRoot},
|
||||
{"AutoCloseIsOptInAndRuleBound", conformance.RunMoleculeAutoCloseIsOptInAndRuleBound},
|
||||
{"RecloseHealsAStrandedRoot", conformance.RunMoleculeRecloseHealsAStrandedRoot},
|
||||
{"BatchCloseAutoClosesTheRootOnce", conformance.RunMoleculeBatchCloseAutoClosesTheRootOnce},
|
||||
{"RefusedRootKeepsTheStepClose", conformance.RunMoleculeRefusedRootKeepsTheStepClose},
|
||||
{"GuardedRootKeepsTheStepClose", conformance.RunMoleculeGuardedRootKeepsTheStepClose},
|
||||
{"StepperClaimsTheNextReadyStepForTheActor", conformance.RunMoleculeStepperClaimsTheNextReadyStepForTheActor},
|
||||
{"StepperNeverTakesAStepAnotherActorHolds", conformance.RunMoleculeStepperNeverTakesAStepAnotherActorHolds},
|
||||
{"StepperAnswersCompleteAndOutsideAMolecule", conformance.RunMoleculeStepperAnswersCompleteAndOutsideAMolecule},
|
||||
{"StepperClaimsAWispStep", conformance.RunMoleculeStepperClaimsAWispStep},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) { test.run(t, ctx, fixture) })
|
||||
}
|
||||
}
|
||||
|
||||
func newDoltMoleculeFixture(t *testing.T, prefix string) (conformance.MoleculeFixture, context.Context, func()) {
|
||||
t.Helper()
|
||||
store, storeCleanup := setupTestStore(t)
|
||||
ctx, cancel := testContext(t)
|
||||
cleanup := func() {
|
||||
cancel()
|
||||
storeCleanup()
|
||||
}
|
||||
lifecycle, err := store.IssueLifecycle()
|
||||
if err != nil {
|
||||
cleanup()
|
||||
t.Fatalf("IssueLifecycle(): %v", err)
|
||||
}
|
||||
closer, err := store.BatchCloser()
|
||||
if err != nil {
|
||||
cleanup()
|
||||
t.Fatalf("BatchCloser(): %v", err)
|
||||
}
|
||||
stepper, err := store.MoleculeStepper()
|
||||
if err != nil {
|
||||
cleanup()
|
||||
t.Fatalf("MoleculeStepper(): %v", err)
|
||||
}
|
||||
kit := newDoltRoleFixtureKit(store, prefix)
|
||||
return conformance.MoleculeFixture{
|
||||
IssuePrefix: kit.IssuePrefix,
|
||||
Lifecycle: lifecycle,
|
||||
BatchCloser: closer,
|
||||
Stepper: stepper,
|
||||
CreateIssue: kit.CreateIssue,
|
||||
CreateWisp: kit.CreateWisp,
|
||||
AddDependency: kit.AddDependency,
|
||||
QueryScalar: kit.QueryScalar,
|
||||
}, ctx, cleanup
|
||||
}
|
||||
|
||||
// seedRacingMolecule seeds an auto-closing molecule root with n open steps
|
||||
// and answers the steps.
|
||||
func seedRacingMolecule(t *testing.T, ctx context.Context, store *DoltStore, root string, n int) []string {
|
||||
t.Helper()
|
||||
if err := store.CreateIssue(ctx, &types.Issue{ID: root, Title: "molecule " + root, IssueType: types.TypeMolecule, Status: types.StatusOpen, Priority: 2}, "tester"); err != nil {
|
||||
t.Fatalf("create %s: %v", root, err)
|
||||
}
|
||||
steps := make([]string, n)
|
||||
for i := range steps {
|
||||
steps[i] = fmt.Sprintf("%s.%d", root, i+1)
|
||||
createPerm(t, ctx, store, steps[i])
|
||||
addDependency(t, ctx, store, steps[i], root, types.DepParentChild)
|
||||
}
|
||||
return steps
|
||||
}
|
||||
|
||||
// readStatus reads id's status from the issues table.
|
||||
func readStatus(t *testing.T, ctx context.Context, store *DoltStore, id string) string {
|
||||
t.Helper()
|
||||
var status string
|
||||
if err := store.db.QueryRowContext(ctx, "SELECT status FROM issues WHERE id = ?", id).Scan(&status); err != nil {
|
||||
t.Fatalf("read %s status: %v", id, err)
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
// closeTwoStepsInRacingTransactions closes steps[0] and steps[1], each with
|
||||
// the molecule auto-close, in two transactions that both begin before either
|
||||
// closes, so each reads the other's step open: the race's interleaving, made
|
||||
// deterministic. Neither may auto-close the root. It commits both and answers
|
||||
// the two commit errors.
|
||||
func closeTwoStepsInRacingTransactions(t *testing.T, ctx context.Context, store *DoltStore, steps []string) [2]error {
|
||||
t.Helper()
|
||||
var txs [2]*sql.Tx
|
||||
for i := range txs {
|
||||
tx, err := store.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("begin transaction %d: %v", i, err)
|
||||
}
|
||||
defer tx.Rollback() // no-op after Commit; preserves cleanup on early Fatal.
|
||||
txs[i] = tx
|
||||
}
|
||||
for i, tx := range txs {
|
||||
res, _, err := issueops.ExecuteClose(ctx, tx, publicops.CloseRequest{
|
||||
Actor: "tester", IssueID: steps[i], Reason: "done", AutoCloseMolecule: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("close %s: %v", steps[i], err)
|
||||
}
|
||||
if res.AutoClosedMolecule != nil {
|
||||
t.Fatalf("close %s auto-closed %s, but in its own transaction %s is still open", steps[i], res.AutoClosedMolecule.ID, steps[1-i])
|
||||
}
|
||||
}
|
||||
return [2]error{txs[0].Commit(), txs[1].Commit()}
|
||||
}
|
||||
|
||||
// TestMoleculeAutoCloseLastStepsCannotBothMissTheRoot is the controlled
|
||||
// two-transaction regression for CloseRequest.AutoCloseMolecule. The closes of
|
||||
// a molecule's last two open steps, in concurrent transactions, each read the
|
||||
// other step as still open, so neither closes the root, and their own writes
|
||||
// touch disjoint rows. If both commit, every step is closed and the root is
|
||||
// stranded open. The coordination cell both rewrite
|
||||
// (issueops.TouchMoleculeCoordinationInTx) must make one of them conflict
|
||||
// instead, so that its retry reads the other's close; the test below drives
|
||||
// that retry through the store.
|
||||
func TestMoleculeAutoCloseLastStepsCannotBothMissTheRoot(t *testing.T) {
|
||||
store, cleanup := setupConcurrentTestStore(t)
|
||||
defer cleanup()
|
||||
ctx, cancel := testContext(t)
|
||||
defer cancel()
|
||||
|
||||
const root = "mol-race"
|
||||
commitErrs := closeTwoStepsInRacingTransactions(t, ctx, store, seedRacingMolecule(t, ctx, store, root, 2))
|
||||
t.Logf("last-step commits: %v", commitErrs)
|
||||
if commitErrs[0] == nil && commitErrs[1] == nil {
|
||||
t.Fatalf("stranded molecule: both last-step closes committed and %s is %s with every step closed; one transaction must conflict",
|
||||
root, readStatus(t, ctx, store, root))
|
||||
}
|
||||
for i, err := range commitErrs {
|
||||
if err != nil && !isSerializationError(err) {
|
||||
t.Fatalf("commit %d error = %v, want a serialization conflict", i, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestMoleculeAutoCloseSiblingClosesConflictBeforeTheLastStep pins the cost
|
||||
// the coordination cell's docs state (issueops.TouchMoleculeCoordinationInTx,
|
||||
// CloseRequest.AutoCloseMolecule, the CHANGELOG): every close under an open
|
||||
// auto-closing root rewrites the cell, so two concurrent sibling closes
|
||||
// conflict even while a third step keeps the molecule from completing. If this
|
||||
// stops conflicting, those docs are stale.
|
||||
func TestMoleculeAutoCloseSiblingClosesConflictBeforeTheLastStep(t *testing.T) {
|
||||
store, cleanup := setupConcurrentTestStore(t)
|
||||
defer cleanup()
|
||||
ctx, cancel := testContext(t)
|
||||
defer cancel()
|
||||
|
||||
commitErrs := closeTwoStepsInRacingTransactions(t, ctx, store, seedRacingMolecule(t, ctx, store, "mol-siblings", 3))
|
||||
t.Logf("sibling commits: %v", commitErrs)
|
||||
if commitErrs[0] == nil && commitErrs[1] == nil {
|
||||
t.Fatal("two concurrent sibling closes under an open auto-closing root both committed; want one serialization conflict")
|
||||
}
|
||||
for i, err := range commitErrs {
|
||||
if err != nil && !isSerializationError(err) {
|
||||
t.Fatalf("commit %d error = %v, want a serialization conflict", i, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// raceMoleculeCloses seeds an auto-closing molecule of n steps under root and
|
||||
// closes every step at once through lifecycle, whose retry replays each close
|
||||
// that loses the coordination conflict. Every close must land, and the root
|
||||
// must end closed, reported by exactly one of them.
|
||||
func raceMoleculeCloses(t *testing.T, ctx context.Context, store *DoltStore, lifecycle publicops.Lifecycle, root string, n int) {
|
||||
t.Helper()
|
||||
steps := seedRacingMolecule(t, ctx, store, root, n)
|
||||
var (
|
||||
start = make(chan struct{})
|
||||
wg sync.WaitGroup
|
||||
results = make([]publicops.CloseResult, n)
|
||||
errs = make([]error, n)
|
||||
)
|
||||
for i, step := range steps {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
results[i], errs[i] = lifecycle.Close(ctx, publicops.CloseRequest{
|
||||
Actor: "tester", IssueID: step, Reason: "done", AutoCloseMolecule: true,
|
||||
})
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
|
||||
reported := 0
|
||||
for i, err := range errs {
|
||||
if err != nil {
|
||||
t.Fatalf("close %s: %v", steps[i], err)
|
||||
}
|
||||
if results[i].AutoClosedMolecule != nil {
|
||||
reported++
|
||||
}
|
||||
}
|
||||
if status := readStatus(t, ctx, store, root); status != string(types.StatusClosed) {
|
||||
t.Fatalf("%s is %s after all %d of its steps closed, want closed", root, status, n)
|
||||
}
|
||||
if reported != 1 {
|
||||
t.Errorf("%s was reported by %d closes, want exactly one", root, reported)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMoleculeAutoCloseConcurrentLastStepsCloseTheRoot races the closes of a
|
||||
// molecule's last two steps through the store's Lifecycle role, whose retry
|
||||
// replays the transaction that loses the coordination conflict: in every
|
||||
// round the root ends closed, reported by exactly one of the two closes.
|
||||
func TestMoleculeAutoCloseConcurrentLastStepsCloseTheRoot(t *testing.T) {
|
||||
store, cleanup := setupConcurrentTestStore(t)
|
||||
defer cleanup()
|
||||
ctx, cancel := testContext(t)
|
||||
defer cancel()
|
||||
lifecycle, err := store.IssueLifecycle()
|
||||
if err != nil {
|
||||
t.Fatalf("IssueLifecycle(): %v", err)
|
||||
}
|
||||
|
||||
const rounds = 8
|
||||
for round := range rounds {
|
||||
raceMoleculeCloses(t, ctx, store, lifecycle, fmt.Sprintf("mol-race-%d", round), 2)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMoleculeAutoCloseSiblingFanOutClosesTheRoot closes all the steps of one
|
||||
// molecule at once. They serialize on the root's coordination cell, and the
|
||||
// store's retry carries every one of them to a commit: the fan-out costs
|
||||
// retries, not closes, and the root is closed exactly once.
|
||||
func TestMoleculeAutoCloseSiblingFanOutClosesTheRoot(t *testing.T) {
|
||||
store, cleanup := setupConcurrentTestStore(t)
|
||||
defer cleanup()
|
||||
ctx, cancel := testContext(t)
|
||||
defer cancel()
|
||||
lifecycle, err := store.IssueLifecycle()
|
||||
if err != nil {
|
||||
t.Fatalf("IssueLifecycle(): %v", err)
|
||||
}
|
||||
|
||||
raceMoleculeCloses(t, ctx, store, lifecycle, "mol-fanout", 6)
|
||||
}
|
||||
17
internal/storage/dolt/molecule_stepper.go
Normal file
17
internal/storage/dolt/molecule_stepper.go
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
package dolt
|
||||
|
||||
import (
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// MoleculeStepper returns the advance-a-molecule surface for this store:
|
||||
// issueops.NewMoleculeStepper composed over this store's own BatchGetter,
|
||||
// Relations, EdgeReader, Claimer and Lifecycle, so the advance reads and
|
||||
// claims exactly as those roles do and no second copy of the rule exists.
|
||||
func (s *DoltStore) MoleculeStepper() (issueops.MoleculeStepper, error) {
|
||||
roles, err := issueops.MoleculeStepperRolesOf(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return issueops.NewMoleculeStepper(roles), nil
|
||||
}
|
||||
|
|
@ -42,6 +42,7 @@ go_library(
|
|||
"memories.go",
|
||||
"merge_slot.go",
|
||||
"metadata_cas.go",
|
||||
"molecule_stepper.go",
|
||||
"open.go",
|
||||
"open_stub.go",
|
||||
"querier.go",
|
||||
|
|
@ -193,6 +194,7 @@ go_test(
|
|||
"migrate_selfheal_test.go",
|
||||
"migrate_temp_intermediates_test.go",
|
||||
"migrate_wisp_dep_forward_repair_test.go",
|
||||
"molecule_contract_test.go",
|
||||
"new_methods_test.go",
|
||||
"open_test.go",
|
||||
"post_sql_commit_test.go",
|
||||
|
|
|
|||
63
internal/storage/embeddeddolt/molecule_contract_test.go
Normal file
63
internal/storage/embeddeddolt/molecule_contract_test.go
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
//go:build cgo
|
||||
|
||||
package embeddeddolt_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/backend/conformance"
|
||||
)
|
||||
|
||||
// TestMoleculeContract runs the molecule contract against the embedded store.
|
||||
func TestMoleculeContract(t *testing.T) {
|
||||
skipUnlessEmbeddedDolt(t)
|
||||
te := newTestEnv(t, "mol")
|
||||
ctx := t.Context()
|
||||
fixture := newEmbeddedMoleculeFixture(t, te, "mol")
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
run func(*testing.T, context.Context, conformance.MoleculeFixture)
|
||||
}{
|
||||
{"CloseAutoClosesTheCompletedRoot", conformance.RunMoleculeCloseAutoClosesTheCompletedRoot},
|
||||
{"AutoCloseIsOptInAndRuleBound", conformance.RunMoleculeAutoCloseIsOptInAndRuleBound},
|
||||
{"RecloseHealsAStrandedRoot", conformance.RunMoleculeRecloseHealsAStrandedRoot},
|
||||
{"BatchCloseAutoClosesTheRootOnce", conformance.RunMoleculeBatchCloseAutoClosesTheRootOnce},
|
||||
{"RefusedRootKeepsTheStepClose", conformance.RunMoleculeRefusedRootKeepsTheStepClose},
|
||||
{"GuardedRootKeepsTheStepClose", conformance.RunMoleculeGuardedRootKeepsTheStepClose},
|
||||
{"StepperClaimsTheNextReadyStepForTheActor", conformance.RunMoleculeStepperClaimsTheNextReadyStepForTheActor},
|
||||
{"StepperNeverTakesAStepAnotherActorHolds", conformance.RunMoleculeStepperNeverTakesAStepAnotherActorHolds},
|
||||
{"StepperAnswersCompleteAndOutsideAMolecule", conformance.RunMoleculeStepperAnswersCompleteAndOutsideAMolecule},
|
||||
{"StepperClaimsAWispStep", conformance.RunMoleculeStepperClaimsAWispStep},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) { test.run(t, ctx, fixture) })
|
||||
}
|
||||
}
|
||||
|
||||
func newEmbeddedMoleculeFixture(t *testing.T, te *testEnv, prefix string) conformance.MoleculeFixture {
|
||||
t.Helper()
|
||||
lifecycle, err := te.store.IssueLifecycle()
|
||||
if err != nil {
|
||||
t.Fatalf("IssueLifecycle(): %v", err)
|
||||
}
|
||||
closer, err := te.store.BatchCloser()
|
||||
if err != nil {
|
||||
t.Fatalf("BatchCloser(): %v", err)
|
||||
}
|
||||
stepper, err := te.store.MoleculeStepper()
|
||||
if err != nil {
|
||||
t.Fatalf("MoleculeStepper(): %v", err)
|
||||
}
|
||||
kit := newEmbeddedRoleFixtureKit(te, prefix)
|
||||
return conformance.MoleculeFixture{
|
||||
IssuePrefix: kit.IssuePrefix,
|
||||
Lifecycle: lifecycle,
|
||||
BatchCloser: closer,
|
||||
Stepper: stepper,
|
||||
CreateIssue: kit.CreateIssue,
|
||||
CreateWisp: kit.CreateWisp,
|
||||
AddDependency: kit.AddDependency,
|
||||
QueryScalar: kit.QueryScalar,
|
||||
}
|
||||
}
|
||||
19
internal/storage/embeddeddolt/molecule_stepper.go
Normal file
19
internal/storage/embeddeddolt/molecule_stepper.go
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
//go:build cgo
|
||||
|
||||
package embeddeddolt
|
||||
|
||||
import (
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// MoleculeStepper returns the advance-a-molecule surface for this store:
|
||||
// issueops.NewMoleculeStepper composed over this store's own BatchGetter,
|
||||
// Relations, EdgeReader, Claimer and Lifecycle, so the advance reads and
|
||||
// claims exactly as those roles do and no second copy of the rule exists.
|
||||
func (s *EmbeddedDoltStore) MoleculeStepper() (issueops.MoleculeStepper, error) {
|
||||
roles, err := issueops.MoleculeStepperRolesOf(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return issueops.NewMoleculeStepper(roles), nil
|
||||
}
|
||||
|
|
@ -88,6 +88,12 @@ func (p *uowProvider) BlockingAnnotator() (publicops.BlockingAnnotator, error) {
|
|||
func (p *uowProvider) TreeWalker() (publicops.TreeWalker, error) { return uow.NewTreeWalker(p) }
|
||||
func (p *uowProvider) BatchGetter() (publicops.BatchGetter, error) { return uow.NewBatchGetter(p) }
|
||||
|
||||
// MoleculeStepper composes over this decorator's own roles, so the advance's
|
||||
// claim answers to the external-dependency policy the claimer applies.
|
||||
func (p *uowProvider) MoleculeStepper() (publicops.MoleculeStepper, error) {
|
||||
return uow.NewMoleculeStepper(p)
|
||||
}
|
||||
|
||||
func (p *uowProvider) GraphCounter() (publicops.GraphCounter, error) {
|
||||
return uow.NewGraphCounter(p)
|
||||
}
|
||||
|
|
@ -188,6 +194,7 @@ var (
|
|||
_ uow.IssueLifecycleSource = (*uowProvider)(nil)
|
||||
_ uow.IssueReaderSource = (*uowProvider)(nil)
|
||||
_ uow.IssueClaimerSource = (*uowProvider)(nil)
|
||||
_ uow.MoleculeStepperSource = (*uowProvider)(nil)
|
||||
_ uow.RelationsSource = (*uowProvider)(nil)
|
||||
_ uow.EdgeReaderSource = (*uowProvider)(nil)
|
||||
_ uow.BlockingAnnotatorSource = (*uowProvider)(nil)
|
||||
|
|
|
|||
|
|
@ -67,6 +67,9 @@ func (o *hookBatchCloser) CloseBatch(ctx context.Context, request issueops.Close
|
|||
if outcome.Changed {
|
||||
o.hooks.CompleteIssueOperationClose(outcome.Issue)
|
||||
}
|
||||
if outcome.AutoClosedMolecule != nil {
|
||||
o.hooks.CompleteIssueOperationClose(outcome.AutoClosedMolecule)
|
||||
}
|
||||
}
|
||||
if result.ClaimedNext != nil {
|
||||
o.hooks.CompleteIssueOperationUpdate(result.ClaimedNext.Issue)
|
||||
|
|
|
|||
|
|
@ -70,6 +70,11 @@ func (o *hookIssueOperations) Close(ctx context.Context, request issueops.CloseR
|
|||
result, err := o.inner.Close(ctx, request)
|
||||
if err == nil {
|
||||
o.hooks.CompleteIssueOperationClose(result.Issue)
|
||||
// A molecule root the close also closed in its transaction is a
|
||||
// close of its own, and announces as one.
|
||||
if result.AutoClosedMolecule != nil {
|
||||
o.hooks.CompleteIssueOperationClose(result.AutoClosedMolecule)
|
||||
}
|
||||
}
|
||||
return result, err
|
||||
}
|
||||
|
|
|
|||
31
internal/storage/hook_molecule_stepper.go
Normal file
31
internal/storage/hook_molecule_stepper.go
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// MoleculeStepper returns the inner store's advance surface, wrapped so a
|
||||
// claimed step fires on_update — the event every claim fires. An advance that
|
||||
// claimed nothing wrote nothing and fires nothing.
|
||||
func (h *HookFiringStore) MoleculeStepper() (issueops.MoleculeStepper, error) {
|
||||
inner, err := h.inner.MoleculeStepper()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &hookMoleculeStepper{inner: inner, hooks: h}, nil
|
||||
}
|
||||
|
||||
type hookMoleculeStepper struct {
|
||||
inner issueops.MoleculeStepper
|
||||
hooks *HookFiringStore
|
||||
}
|
||||
|
||||
func (s *hookMoleculeStepper) Advance(ctx context.Context, req issueops.AdvanceRequest) (issueops.AdvanceResult, error) {
|
||||
result, err := s.inner.Advance(ctx, req)
|
||||
if err == nil && result.Claimed && result.NextStep != nil {
|
||||
s.hooks.CompleteIssueOperationUpdate(result.NextStep)
|
||||
}
|
||||
return result, err
|
||||
}
|
||||
|
|
@ -59,8 +59,19 @@ func ValidateCloseBatchRequest(request publicops.CloseBatchRequest) error {
|
|||
func CloseBatchCommitMessage(result publicops.CloseBatchResult) string {
|
||||
ids := make([]string, 0, len(result.Outcomes))
|
||||
ephemeral := 0
|
||||
var autoClosed []string
|
||||
for _, outcome := range result.Outcomes {
|
||||
if outcome.Err != nil || !outcome.Changed {
|
||||
if outcome.Err != nil {
|
||||
continue
|
||||
}
|
||||
if root := outcome.AutoClosedMolecule; root != nil {
|
||||
if IsWisp(root) {
|
||||
ephemeral++
|
||||
} else {
|
||||
autoClosed = append(autoClosed, root.ID)
|
||||
}
|
||||
}
|
||||
if !outcome.Changed {
|
||||
continue
|
||||
}
|
||||
if closeOutcomeIsEphemeral(outcome) {
|
||||
|
|
@ -79,6 +90,9 @@ func CloseBatchCommitMessage(result publicops.CloseBatchResult) string {
|
|||
case ephemeral > 1:
|
||||
parts = append(parts, fmt.Sprintf("close %d ephemeral items", ephemeral))
|
||||
}
|
||||
if len(autoClosed) > 0 {
|
||||
parts = append(parts, "auto-close "+strings.Join(autoClosed, ", "))
|
||||
}
|
||||
if result.ClaimedNext != nil {
|
||||
parts = append(parts, "claim "+result.ClaimedNext.ID)
|
||||
}
|
||||
|
|
@ -162,6 +176,25 @@ func ExecuteCloseBatchWithPolicy(ctx context.Context, tx *sql.Tx, request public
|
|||
}
|
||||
}
|
||||
|
||||
if request.AutoCloseMolecule {
|
||||
closedAt := make([]int, 0, len(result.Outcomes))
|
||||
stepIDs := make([]string, 0, len(result.Outcomes))
|
||||
for i, outcome := range result.Outcomes {
|
||||
if outcome.Err == nil {
|
||||
closedAt = append(closedAt, i)
|
||||
stepIDs = append(stepIDs, outcome.IssueID)
|
||||
}
|
||||
}
|
||||
autos, autoTables, err := CloseCompletedMoleculesInTx(ctx, tx, stepIDs, request.Actor, request.Session)
|
||||
if err != nil {
|
||||
return publicops.CloseBatchResult{}, nil, err
|
||||
}
|
||||
tables.Merge(autoTables)
|
||||
for j, i := range closedAt {
|
||||
result.Outcomes[i].AutoClosedMolecule, result.Outcomes[i].MoleculeAutoCloseRefusal = autos[j].Root, autos[j].Refusal
|
||||
}
|
||||
}
|
||||
|
||||
if claimFilter != nil && landed > 0 {
|
||||
claim, claimTables, err := ExecuteClaimNext(ctx, tx, request.Actor, policy.FilterClaim(*claimFilter))
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package issueops
|
|||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
|
|
@ -53,3 +54,24 @@ func TestCheckClosable(t *testing.T) {
|
|||
t.Fatalf("held refusal = %#v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRefusedMoleculeAutoCloseReportsTheRefusalsOwnSentence pins
|
||||
// RefusedMoleculeAutoClose: whatever the layers between a root's refused close
|
||||
// and the auto-close wrapped around it (the unit of work's use case and
|
||||
// repository), Refusal is the sentence the refusing guard or policy wrote.
|
||||
func TestRefusedMoleculeAutoCloseReportsTheRefusalsOwnSentence(t *testing.T) {
|
||||
for _, refusal := range []error{
|
||||
publicops.NewCloseBlockedError("bd-1", []string{"bd-2"}),
|
||||
&publicops.CloseOpenChildrenError{IssueID: "bd-1", OpenChildren: 2},
|
||||
&publicops.TemplateReadOnlyError{IssueID: "bd-1"},
|
||||
&publicops.PinnedError{IssueID: "bd-1"},
|
||||
&publicops.CloseNotAssigneeError{IssueID: "bd-1", Assignee: "bob", Actor: "alice"},
|
||||
} {
|
||||
wrapped := fmt.Errorf("close bd-1: %w", fmt.Errorf("db: IssueSQLRepository.CloseChecked bd-1: %w", refusal))
|
||||
for _, err := range []error{refusal, wrapped} {
|
||||
if got := RefusedMoleculeAutoClose(err).Refusal; got != refusal.Error() {
|
||||
t.Errorf("RefusedMoleculeAutoClose(%q).Refusal = %q, want %q", err, got, refusal.Error())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -336,7 +336,16 @@ func ExecuteClose(ctx context.Context, tx *sql.Tx, request publicops.CloseReques
|
|||
if err != nil {
|
||||
return publicops.CloseResult{}, nil, err
|
||||
}
|
||||
return publicops.CloseResult{Issue: hydrated, Changed: changed, OpenChildren: closed.OpenChildren}, tables, nil
|
||||
result := publicops.CloseResult{Issue: hydrated, Changed: changed, OpenChildren: closed.OpenChildren}
|
||||
if attempt.AutoCloseMolecule {
|
||||
auto, autoTables, err := CloseCompletedMoleculeInTx(ctx, tx, attempt.IssueID, attempt.Actor, attempt.Session)
|
||||
if err != nil {
|
||||
return publicops.CloseResult{}, nil, err
|
||||
}
|
||||
tables.Merge(autoTables)
|
||||
result.AutoClosedMolecule, result.MoleculeAutoCloseRefusal = auto.Root, auto.Refusal
|
||||
}
|
||||
return result, tables, nil
|
||||
}
|
||||
|
||||
// ExecuteReopen applies a guarded reopen in tx and reports durable tables changed.
|
||||
|
|
|
|||
|
|
@ -3,10 +3,13 @@ package issueops
|
|||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
publicops "github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// GetMoleculeProgressInTx returns progress stats for a molecule within an
|
||||
|
|
@ -111,3 +114,191 @@ func GetMoleculeProgressInTx(ctx context.Context, tx *sql.Tx, moleculeID string)
|
|||
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
// TxMoleculeReader binds the molecule rules (issueops.MoleculeReader) to a
|
||||
// caller's transaction: it runs the SAME BatchGetter, Relations and EdgeReader
|
||||
// bodies the store-backed roles run, against tx, so a close that decides
|
||||
// whether it completed a molecule reads the state its own writes produced.
|
||||
type TxMoleculeReader struct{ Tx DBTX }
|
||||
|
||||
var _ = publicops.MoleculeReaderOver(TxMoleculeReader{})
|
||||
|
||||
// GetMany is the BatchGetter body (ExecuteGetMany) in the bound transaction.
|
||||
func (r TxMoleculeReader) GetMany(ctx context.Context, request publicops.GetManyRequest) (publicops.GetManyResult, error) {
|
||||
return ExecuteGetMany(ctx, r.Tx, request)
|
||||
}
|
||||
|
||||
// Related is the Relations body (ExecuteRelated) in the bound transaction.
|
||||
func (r TxMoleculeReader) Related(ctx context.Context, request publicops.RelatedRequest) ([]*publicops.RelatedIssue, error) {
|
||||
if err := ValidateRelatedRequest(request); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ExecuteRelated(ctx, r.Tx, request)
|
||||
}
|
||||
|
||||
// ReadEdges is the EdgeReader body (ExecuteEdgeRead) in the bound transaction.
|
||||
func (r TxMoleculeReader) ReadEdges(ctx context.Context, request publicops.EdgeReadRequest) (publicops.EdgeReadResult, error) {
|
||||
if err := ValidateEdgeReadRequest(request); err != nil {
|
||||
return publicops.EdgeReadResult{}, err
|
||||
}
|
||||
return ExecuteEdgeRead(ctx, r.Tx, request)
|
||||
}
|
||||
|
||||
// MoleculeAutoClose is what one molecule auto-close did.
|
||||
type MoleculeAutoClose struct {
|
||||
// Root is the post-close snapshot of the root it closed, or nil.
|
||||
Root *types.Issue
|
||||
// Refusal is why a completed root stayed open (its close policy or a
|
||||
// close guard refused it), or "": the refusal's own sentence
|
||||
// (RefusedMoleculeAutoClose).
|
||||
Refusal string
|
||||
}
|
||||
|
||||
// RefusedMoleculeAutoClose is the MoleculeAutoClose for a root whose close
|
||||
// failed with err, a refusal (issueops.IsMoleculeAutoCloseRefusal). Its
|
||||
// Refusal is the sentence the refusing guard or close policy wrote, the same
|
||||
// on every backend. ExecuteClose returns a refusal as it was minted, while the
|
||||
// unit of work's use case and repository wrap it on the way out ("close <id>:
|
||||
// db: IssueSQLRepository.CloseChecked <id>: …"); the sentence already names
|
||||
// the root, so the wrap would only leak a repository type into an
|
||||
// operator-facing field (bd close --json's molecule_auto_close_refusal).
|
||||
func RefusedMoleculeAutoClose(err error) MoleculeAutoClose {
|
||||
var (
|
||||
blocked *publicops.BlockedError
|
||||
openChildren *publicops.CloseOpenChildrenError
|
||||
template *publicops.TemplateReadOnlyError
|
||||
pinned *publicops.PinnedError
|
||||
notAssignee *publicops.CloseNotAssigneeError
|
||||
)
|
||||
switch {
|
||||
case errors.As(err, &blocked):
|
||||
err = blocked
|
||||
case errors.As(err, &openChildren):
|
||||
err = openChildren
|
||||
case errors.As(err, &template):
|
||||
err = template
|
||||
case errors.As(err, &pinned):
|
||||
err = pinned
|
||||
case errors.As(err, ¬Assignee):
|
||||
err = notAssignee
|
||||
}
|
||||
return MoleculeAutoClose{Refusal: err.Error()}
|
||||
}
|
||||
|
||||
// moleculeCoordinationKeyPrefix names the local_metadata cells an auto-close
|
||||
// rewrites (TouchMoleculeCoordinationInTx).
|
||||
const moleculeCoordinationKeyPrefix = "molecule-coordination/v1/"
|
||||
|
||||
// MoleculeCoordinationKey is the local_metadata cell a molecule auto-close
|
||||
// rewrites before it decides rootID. It shares the dependency coordination
|
||||
// cells' sharding (4096 rows): the same root always resolves to the same
|
||||
// cell, and a hash collision between two roots only adds a safe
|
||||
// serialization conflict.
|
||||
func MoleculeCoordinationKey(rootID string) string {
|
||||
return fmt.Sprintf("%s%03x", moleculeCoordinationKeyPrefix, dependencyCoordinationShard(rootID))
|
||||
}
|
||||
|
||||
// TouchMoleculeCoordinationInTx rewrites rootID's molecule coordination cell
|
||||
// with a fresh value, the dependency coordination idiom
|
||||
// (TouchDependencyCoordinationTableInTx) applied to a molecule's completion.
|
||||
//
|
||||
// Two closes that finish a molecule's last two steps in concurrent
|
||||
// transactions each read the other's step as still open, so neither closes the
|
||||
// root, and their writes touch disjoint rows: both commit and the complete
|
||||
// molecule's root is stranded open. Every auto-close that decides a root
|
||||
// rewrites this one cell first, so two transactions deciding the same root
|
||||
// conflict at commit instead; the loser's retry reads the winner's close and
|
||||
// closes the root.
|
||||
//
|
||||
// The cost is that sibling closes serialize. The cell is rewritten before the
|
||||
// steps are read, by every close under the open root and not only the one that
|
||||
// completes it, so any two concurrent closes of steps under the same root
|
||||
// conflict and one of them retries. Under heavy fan-out a close can spend its
|
||||
// whole retry budget conflicting and then fails with the serialization error.
|
||||
func TouchMoleculeCoordinationInTx(ctx context.Context, tx DBTX, rootID string) error {
|
||||
if rootID == "" {
|
||||
return fmt.Errorf("touch molecule coordination: root ID must not be empty")
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
"REPLACE INTO local_metadata (`key`, value) VALUES (?, ?)", MoleculeCoordinationKey(rootID), strconv.FormatInt(FreshRowLock(), 10)); err != nil {
|
||||
return fmt.Errorf("touch molecule coordination for %s: %w", rootID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CloseCompletedMoleculeInTx is CloseRequest.AutoCloseMolecule's body for the
|
||||
// store-backed backends: CloseCompletedMoleculesInTx for one step.
|
||||
func CloseCompletedMoleculeInTx(ctx context.Context, tx *sql.Tx, stepID, actor, session string) (MoleculeAutoClose, ChangedTables, error) {
|
||||
autos, tables, err := CloseCompletedMoleculesInTx(ctx, tx, []string{stepID}, actor, session)
|
||||
if err != nil {
|
||||
return MoleculeAutoClose{}, nil, err
|
||||
}
|
||||
return autos[0], tables, nil
|
||||
}
|
||||
|
||||
// CloseCompletedMoleculesInTx is CloseBatchRequest.AutoCloseMolecule's body
|
||||
// for the store-backed backends, and through CloseCompletedMoleculeInTx
|
||||
// CloseRequest.AutoCloseMolecule's. For every auto-closing molecule root a
|
||||
// close of stepIDs could have completed (issueops.AutoClosingMoleculeRoots,
|
||||
// read in tx), it rewrites the root's coordination cell
|
||||
// (TouchMoleculeCoordinationInTx), and when every step under the root is now
|
||||
// closed (issueops.MoleculeStepsClosed) it closes the root in tx through
|
||||
// ExecuteClose — issueops.MoleculeRootClose: unforced, guarded on the root
|
||||
// revision read in the same transaction, recording
|
||||
// issueops.MoleculeAutoCloseReason and session.
|
||||
//
|
||||
// It answers one MoleculeAutoClose per step id, in order. Each root is decided
|
||||
// once, and what happened to it is reported on the first step under it; every
|
||||
// other step under that root answers the zero value.
|
||||
//
|
||||
// A refusal of the root (issueops.IsMoleculeAutoCloseRefusal) is answered as
|
||||
// MoleculeAutoClose.Refusal and writes nothing; the caller's own closes stand.
|
||||
// Any other failure is returned and fails the caller's transaction.
|
||||
func CloseCompletedMoleculesInTx(ctx context.Context, tx *sql.Tx, stepIDs []string, actor, session string) ([]MoleculeAutoClose, ChangedTables, error) {
|
||||
reader := publicops.MoleculeReaderOver(TxMoleculeReader{Tx: tx})
|
||||
roots, err := publicops.AutoClosingMoleculeRoots(ctx, reader, stepIDs)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
autos := make([]MoleculeAutoClose, len(stepIDs))
|
||||
tables := ChangedTables{}
|
||||
decided := make(map[string]bool, len(roots))
|
||||
for i, stepID := range stepIDs {
|
||||
root := roots[stepID]
|
||||
if root == nil || decided[root.ID] {
|
||||
continue
|
||||
}
|
||||
decided[root.ID] = true
|
||||
auto, rootTables, err := closeCompletedMoleculeRootInTx(ctx, tx, reader, root, actor, session)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
tables.Merge(rootTables)
|
||||
autos[i] = auto
|
||||
}
|
||||
return autos, tables, nil
|
||||
}
|
||||
|
||||
func closeCompletedMoleculeRootInTx(ctx context.Context, tx *sql.Tx, reader publicops.MoleculeReader, root *types.Issue, actor, session string) (MoleculeAutoClose, ChangedTables, error) {
|
||||
if err := TouchMoleculeCoordinationInTx(ctx, tx, root.ID); err != nil {
|
||||
return MoleculeAutoClose{}, nil, err
|
||||
}
|
||||
complete, err := publicops.MoleculeStepsClosed(ctx, reader, root.ID)
|
||||
if err != nil || !complete {
|
||||
return MoleculeAutoClose{}, nil, err
|
||||
}
|
||||
closed, tables, err := ExecuteClose(ctx, tx, publicops.MoleculeRootClose(root, actor, session))
|
||||
if publicops.IsMoleculeAutoCloseRefusal(err) {
|
||||
return RefusedMoleculeAutoClose(err), nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
// Not a refusal, such as a storage error. Returned, it fails the
|
||||
// caller's transaction, so the step's own close rolls back with it
|
||||
// (CloseRequest.AutoCloseMolecule).
|
||||
return MoleculeAutoClose{}, nil, fmt.Errorf("auto-closing molecule %s: %w", root.ID, err)
|
||||
}
|
||||
if !closed.Changed {
|
||||
return MoleculeAutoClose{}, tables, nil
|
||||
}
|
||||
return MoleculeAutoClose{Root: closed.Issue}, tables, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -388,6 +388,16 @@ type Storage interface {
|
|||
// event Releaser fires. See hook_lease_reclaimer.go.
|
||||
LeaseReclaimer() (issueops.LeaseReclaimer, error)
|
||||
|
||||
// MoleculeStepper returns the advance-a-molecule surface for this store:
|
||||
// find a molecule's next ready step after one closed and, on request,
|
||||
// claim it — the operation behind `bd close --continue`. Every local
|
||||
// backend answers issueops.NewMoleculeStepper composed over its own
|
||||
// roles; a remote backend serves it over its wire.
|
||||
//
|
||||
// It is a WRITE role and its hook decorator WRAPS: a claimed step fires
|
||||
// on_update, as every claim does.
|
||||
MoleculeStepper() (issueops.MoleculeStepper, error)
|
||||
|
||||
// Issue CRUD
|
||||
CreateIssue(ctx context.Context, issue *types.Issue, actor string) error
|
||||
CreateIssues(ctx context.Context, issues []*types.Issue, actor string) error
|
||||
|
|
@ -1082,6 +1092,62 @@ type ExternalDependencyPolicyProber interface {
|
|||
ServerEnforcesExternalDependencyPolicy(ctx context.Context) (bool, error)
|
||||
}
|
||||
|
||||
// MoleculeAutoCloseProber is implemented by a DoltStorage whose closes may not
|
||||
// accept issueops.CloseRequest.AutoCloseMolecule — today exactly
|
||||
// httpclient.Store, whose server advertises it with
|
||||
// issues.close.autoCloseMolecule. Every local backend runs the auto-close in
|
||||
// the close's own transaction and does not implement this.
|
||||
//
|
||||
// A server that does not advertise it (an older bd serve, or a server whose
|
||||
// orchestrator owns the molecule lifecycle, as gc does) is answered false, and
|
||||
// the caller closes WITHOUT the flag: asking for it there is refused before
|
||||
// dialing, and the molecule's auto-close is that server's to run.
|
||||
type MoleculeAutoCloseProber interface {
|
||||
ServesMoleculeAutoClose(ctx context.Context) (bool, error)
|
||||
}
|
||||
|
||||
// ServesMoleculeAutoClose reports whether closes through s may set
|
||||
// issueops.CloseRequest.AutoCloseMolecule (MoleculeAutoCloseProber, looked up
|
||||
// through every decorator). A store that does not implement the prober runs
|
||||
// the auto-close itself and is answered true. A probe that fails is answered
|
||||
// true as well: the close dials the same handshake and reports its failure,
|
||||
// so nothing is hidden by asking for the auto-close.
|
||||
func ServesMoleculeAutoClose(ctx context.Context, s DoltStorage) bool {
|
||||
prober, ok := UnwrapStore(s).(MoleculeAutoCloseProber)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
served, err := prober.ServesMoleculeAutoClose(ctx)
|
||||
return err != nil || served
|
||||
}
|
||||
|
||||
// MoleculeAdvanceProber is implemented by a DoltStorage whose MoleculeStepper
|
||||
// may not be served — today exactly httpclient.Store, whose server advertises
|
||||
// it with issues.advanceMolecule. Every local backend composes the stepper
|
||||
// over its own roles and does not implement this.
|
||||
type MoleculeAdvanceProber interface {
|
||||
ServesMoleculeAdvance(ctx context.Context) (bool, error)
|
||||
}
|
||||
|
||||
// ServesMoleculeAdvance reports whether s's MoleculeStepper can run
|
||||
// (MoleculeAdvanceProber, looked up through every decorator). A store that
|
||||
// does not implement the prober runs the advance itself and is answered true.
|
||||
// A probe that fails returns its error.
|
||||
//
|
||||
// `bd close --continue` asks BEFORE it closes: the advance is a second
|
||||
// operation after the close commits, so refusing it only then would leave
|
||||
// the step closed and the next step unclaimed. That is also why a failed
|
||||
// probe is not answered true, as ServesMoleculeAutoClose answers it: the
|
||||
// close would commit and only the advance, dialing the same handshake, would
|
||||
// fail — the half-done state the question exists to avoid.
|
||||
func ServesMoleculeAdvance(ctx context.Context, s DoltStorage) (bool, error) {
|
||||
prober, ok := UnwrapStore(s).(MoleculeAdvanceProber)
|
||||
if !ok {
|
||||
return true, nil
|
||||
}
|
||||
return prober.ServesMoleculeAdvance(ctx)
|
||||
}
|
||||
|
||||
// ExcludeIDsUnsupportedStore is implemented by a DoltStorage whose ready-work
|
||||
// reads cannot express types.WorkFilter.ExcludeIDs over their own transport.
|
||||
// Today that is exactly httpclient.Store: the v0 wire's listReadyWork and
|
||||
|
|
|
|||
|
|
@ -35,6 +35,7 @@ go_library(
|
|||
"maintenance.go",
|
||||
"memories.go",
|
||||
"metadata_cas.go",
|
||||
"molecule.go",
|
||||
"notifying.go",
|
||||
"pool.go",
|
||||
"querier.go",
|
||||
|
|
@ -141,6 +142,7 @@ go_test(
|
|||
"memories_contract_test.go",
|
||||
"metadata_cas_contract_test.go",
|
||||
"metadata_patch_dolt_test.go",
|
||||
"molecule_contract_test.go",
|
||||
"notifying_integration_test.go",
|
||||
"notifying_parity_test.go",
|
||||
"notifying_test.go",
|
||||
|
|
|
|||
|
|
@ -73,6 +73,24 @@ func (o *batchCloser) CloseBatch(ctx context.Context, request publicops.CloseBat
|
|||
}
|
||||
}
|
||||
|
||||
if request.AutoCloseMolecule {
|
||||
closedAt := make([]int, 0, len(result.Outcomes))
|
||||
stepIDs := make([]string, 0, len(result.Outcomes))
|
||||
for i, outcome := range result.Outcomes {
|
||||
if outcome.Err == nil {
|
||||
closedAt = append(closedAt, i)
|
||||
stepIDs = append(stepIDs, outcome.IssueID)
|
||||
}
|
||||
}
|
||||
autos, err := CloseCompletedMoleculesInUOW(ctx, uw, stepIDs, request.Actor, request.Session)
|
||||
if err != nil {
|
||||
return publicops.CloseBatchResult{}, "", err
|
||||
}
|
||||
for j, i := range closedAt {
|
||||
result.Outcomes[i].AutoClosedMolecule, result.Outcomes[i].MoleculeAutoCloseRefusal = autos[j].Root, autos[j].Refusal
|
||||
}
|
||||
}
|
||||
|
||||
if claimFilter != nil && landed > 0 {
|
||||
claimed, err := ClaimNextInUOW(ctx, uw, request.Actor, *claimFilter)
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -39,6 +39,11 @@ var _ publicops.BatchGetter = (*batchGetter)(nil)
|
|||
// body (issueops.ExecuteGetMany), so this leg does no pre-check of its own.
|
||||
func (c *batchGetter) GetMany(ctx context.Context, request publicops.GetManyRequest) (publicops.GetManyResult, error) {
|
||||
return RunTxRead(ctx, c.provider, func(ctx context.Context, uw UnitOfWork) (publicops.GetManyResult, error) {
|
||||
return uw.IssueUseCase().GetMany(ctx, request)
|
||||
return GetManyInUOW(ctx, uw, request)
|
||||
})
|
||||
}
|
||||
|
||||
// GetManyInUOW is the BatchGetter body, run inside the caller's unit of work.
|
||||
func GetManyInUOW(ctx context.Context, uw UnitOfWork, request publicops.GetManyRequest) (publicops.GetManyResult, error) {
|
||||
return uw.IssueUseCase().GetMany(ctx, request)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import (
|
|||
"fmt"
|
||||
|
||||
storageissueops "github.com/steveyegge/beads/internal/storage/issueops"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
publicops "github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
|
|
@ -51,33 +52,49 @@ func (r *edgeReader) ReadEdges(ctx context.Context, request publicops.EdgeReadRe
|
|||
return publicops.EdgeReadResult{Anchors: []publicops.AnchorEdges{}}, nil
|
||||
}
|
||||
return RunTxRead(ctx, r.provider, func(ctx context.Context, uw UnitOfWork) (publicops.EdgeReadResult, error) {
|
||||
present := make(map[string]struct{}, len(anchors))
|
||||
issues, err := uw.IssueUseCase().GetIssuesByIDs(ctx, anchors)
|
||||
if err != nil {
|
||||
return publicops.EdgeReadResult{}, err
|
||||
}
|
||||
for _, issue := range issues {
|
||||
if issue != nil {
|
||||
present[issue.ID] = struct{}{}
|
||||
}
|
||||
}
|
||||
wisps, err := uw.IssueUseCase().GetWispsByIDs(ctx, anchors)
|
||||
if err != nil {
|
||||
return publicops.EdgeReadResult{}, err
|
||||
}
|
||||
for _, wisp := range wisps {
|
||||
if wisp != nil {
|
||||
present[wisp.ID] = struct{}{}
|
||||
}
|
||||
}
|
||||
edges, err := uw.DependencyUseCase().GetIssueDependencyRecords(ctx, anchors)
|
||||
if err != nil {
|
||||
return publicops.EdgeReadResult{}, err
|
||||
}
|
||||
// The type filter and the order run HERE rather than in the reads
|
||||
// above, so both implementations narrow and order through one function;
|
||||
// a filter pushed into one side's query would put the narrowing in SQL
|
||||
// on one backend and in Go on the other.
|
||||
return storageissueops.FinishEdgeRead(anchors, present, edges, request.Types), nil
|
||||
return readEdgesInUOW(ctx, uw, anchors, request.Types)
|
||||
})
|
||||
}
|
||||
|
||||
// ReadEdgesInUOW is the EdgeReader body, run inside the caller's unit of work.
|
||||
func ReadEdgesInUOW(ctx context.Context, uw UnitOfWork, request publicops.EdgeReadRequest) (publicops.EdgeReadResult, error) {
|
||||
if err := storageissueops.ValidateEdgeReadRequest(request); err != nil {
|
||||
return publicops.EdgeReadResult{}, err
|
||||
}
|
||||
anchors := storageissueops.EdgeReadAnchors(request.IDs)
|
||||
if len(anchors) == 0 {
|
||||
return publicops.EdgeReadResult{Anchors: []publicops.AnchorEdges{}}, nil
|
||||
}
|
||||
return readEdgesInUOW(ctx, uw, anchors, request.Types)
|
||||
}
|
||||
|
||||
func readEdgesInUOW(ctx context.Context, uw UnitOfWork, anchors []string, depTypes []types.DependencyType) (publicops.EdgeReadResult, error) {
|
||||
present := make(map[string]struct{}, len(anchors))
|
||||
issues, err := uw.IssueUseCase().GetIssuesByIDs(ctx, anchors)
|
||||
if err != nil {
|
||||
return publicops.EdgeReadResult{}, err
|
||||
}
|
||||
for _, issue := range issues {
|
||||
if issue != nil {
|
||||
present[issue.ID] = struct{}{}
|
||||
}
|
||||
}
|
||||
wisps, err := uw.IssueUseCase().GetWispsByIDs(ctx, anchors)
|
||||
if err != nil {
|
||||
return publicops.EdgeReadResult{}, err
|
||||
}
|
||||
for _, wisp := range wisps {
|
||||
if wisp != nil {
|
||||
present[wisp.ID] = struct{}{}
|
||||
}
|
||||
}
|
||||
edges, err := uw.DependencyUseCase().GetIssueDependencyRecords(ctx, anchors)
|
||||
if err != nil {
|
||||
return publicops.EdgeReadResult{}, err
|
||||
}
|
||||
// The type filter and the order run HERE rather than in the reads
|
||||
// above, so both implementations narrow and order through one function;
|
||||
// a filter pushed into one side's query would put the narrowing in SQL
|
||||
// on one backend and in Go on the other.
|
||||
return storageissueops.FinishEdgeRead(anchors, present, edges, depTypes), nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -440,8 +440,15 @@ func (o *issueOperations) Close(ctx context.Context, request publicops.CloseRequ
|
|||
if err != nil {
|
||||
return publicops.CloseResult{}, "", err
|
||||
}
|
||||
return publicops.CloseResult{Issue: hydrated, Changed: !semanticIssueEqual(before, hydrated), OpenChildren: closed.OpenChildren},
|
||||
"close issue", nil
|
||||
result := publicops.CloseResult{Issue: hydrated, Changed: !semanticIssueEqual(before, hydrated), OpenChildren: closed.OpenChildren}
|
||||
if attempt.AutoCloseMolecule {
|
||||
auto, err := CloseCompletedMoleculeInUOW(ctx, uw, attempt.IssueID, attempt.Actor, attempt.Session)
|
||||
if err != nil {
|
||||
return publicops.CloseResult{}, "", err
|
||||
}
|
||||
result.AutoClosedMolecule, result.MoleculeAutoCloseRefusal = auto.Root, auto.Refusal
|
||||
}
|
||||
return result, "close issue", nil
|
||||
})
|
||||
}
|
||||
|
||||
|
|
|
|||
182
internal/storage/uow/molecule.go
Normal file
182
internal/storage/uow/molecule.go
Normal file
|
|
@ -0,0 +1,182 @@
|
|||
package uow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
storageissueops "github.com/steveyegge/beads/internal/storage/issueops"
|
||||
publicops "github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// MoleculeReaderInUOW binds the molecule rules (issueops.MoleculeReader) to a
|
||||
// caller's unit of work: the SAME BatchGetter, Relations and EdgeReader bodies
|
||||
// this backend's roles run (GetManyInUOW, RelatedInUOW, ReadEdgesInUOW),
|
||||
// against uw, so a close that decides whether it completed a molecule reads
|
||||
// the state its own writes produced. It is this backend's twin of
|
||||
// internal/storage/issueops.TxMoleculeReader.
|
||||
func MoleculeReaderInUOW(uw UnitOfWork) publicops.MoleculeReader {
|
||||
return publicops.MoleculeReaderOver(uowMoleculeReader{uw: uw})
|
||||
}
|
||||
|
||||
type uowMoleculeReader struct{ uw UnitOfWork }
|
||||
|
||||
func (r uowMoleculeReader) GetMany(ctx context.Context, request publicops.GetManyRequest) (publicops.GetManyResult, error) {
|
||||
return GetManyInUOW(ctx, r.uw, request)
|
||||
}
|
||||
|
||||
func (r uowMoleculeReader) Related(ctx context.Context, request publicops.RelatedRequest) ([]*publicops.RelatedIssue, error) {
|
||||
if err := storageissueops.ValidateRelatedRequest(request); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return RelatedInUOW(ctx, r.uw, request)
|
||||
}
|
||||
|
||||
func (r uowMoleculeReader) ReadEdges(ctx context.Context, request publicops.EdgeReadRequest) (publicops.EdgeReadResult, error) {
|
||||
return ReadEdgesInUOW(ctx, r.uw, request)
|
||||
}
|
||||
|
||||
// CloseCompletedMoleculeInUOW is CloseRequest.AutoCloseMolecule's body for
|
||||
// this backend: CloseCompletedMoleculesInUOW for one step.
|
||||
func CloseCompletedMoleculeInUOW(ctx context.Context, uw UnitOfWork, stepID, actor, session string) (storageissueops.MoleculeAutoClose, error) {
|
||||
autos, err := CloseCompletedMoleculesInUOW(ctx, uw, []string{stepID}, actor, session)
|
||||
if err != nil {
|
||||
return storageissueops.MoleculeAutoClose{}, err
|
||||
}
|
||||
return autos[0], nil
|
||||
}
|
||||
|
||||
// CloseCompletedMoleculesInUOW is CloseBatchRequest.AutoCloseMolecule's body
|
||||
// for this backend, the twin of storageissueops.CloseCompletedMoleculesInTx:
|
||||
// for every auto-closing molecule root a close of stepIDs could have completed
|
||||
// (issueops.AutoClosingMoleculeRoots read in uw), it rewrites the root's
|
||||
// coordination cell (storageissueops.MoleculeCoordinationKey, so two units of
|
||||
// work deciding the same root conflict at commit and the retry reads the
|
||||
// other's close; the cost, serialized sibling closes, is
|
||||
// storageissueops.TouchMoleculeCoordinationInTx's), and when every step under
|
||||
// the root is now closed (issueops.MoleculeStepsClosed) it closes the root in
|
||||
// uw — unforced, guarded on the root revision read in the same unit of work,
|
||||
// recording issueops.MoleculeAutoCloseReason and session.
|
||||
//
|
||||
// It answers one MoleculeAutoClose per step id, in order: each root is decided
|
||||
// once and reported on the first step under it. A refusal of the root
|
||||
// (issueops.IsMoleculeAutoCloseRefusal) is answered as the Refusal and leaves
|
||||
// the root untouched; the caller's own closes stand. Any other failure is
|
||||
// returned and fails the caller's unit of work.
|
||||
func CloseCompletedMoleculesInUOW(ctx context.Context, uw UnitOfWork, stepIDs []string, actor, session string) ([]storageissueops.MoleculeAutoClose, error) {
|
||||
reader := MoleculeReaderInUOW(uw)
|
||||
roots, err := publicops.AutoClosingMoleculeRoots(ctx, reader, stepIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
autos := make([]storageissueops.MoleculeAutoClose, len(stepIDs))
|
||||
decided := make(map[string]bool, len(roots))
|
||||
for i, stepID := range stepIDs {
|
||||
root := roots[stepID]
|
||||
if root == nil || decided[root.ID] {
|
||||
continue
|
||||
}
|
||||
decided[root.ID] = true
|
||||
auto, err := closeCompletedMoleculeRootInUOW(ctx, uw, reader, root, actor, session)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
autos[i] = auto
|
||||
}
|
||||
return autos, nil
|
||||
}
|
||||
|
||||
func closeCompletedMoleculeRootInUOW(ctx context.Context, uw UnitOfWork, reader publicops.MoleculeReader, root *publicops.Issue, actor, session string) (storageissueops.MoleculeAutoClose, error) {
|
||||
// storageissueops.TouchMoleculeCoordinationInTx, through this unit of work.
|
||||
touch := strconv.FormatInt(storageissueops.FreshRowLock(), 10)
|
||||
if err := uw.ConfigUseCase().SetLocalMetadata(ctx, storageissueops.MoleculeCoordinationKey(root.ID), touch); err != nil {
|
||||
return storageissueops.MoleculeAutoClose{}, fmt.Errorf("touch molecule coordination for %s: %w", root.ID, err)
|
||||
}
|
||||
complete, err := publicops.MoleculeStepsClosed(ctx, reader, root.ID)
|
||||
if err != nil || !complete {
|
||||
return storageissueops.MoleculeAutoClose{}, err
|
||||
}
|
||||
req := publicops.MoleculeRootClose(root, actor, session)
|
||||
// A probe, not a write: an UpdateSpec with no Fields applies nothing. It
|
||||
// only checks the root's revision against req.ExpectedVersion, the guard
|
||||
// the close below does not take itself.
|
||||
if _, err := uw.IssueUseCase().ApplyUpdate(ctx, req.IssueID, domain.UpdateSpec{ExpectedVersion: req.ExpectedVersion}, req.Actor); err != nil {
|
||||
if publicops.IsMoleculeAutoCloseRefusal(err) {
|
||||
return storageissueops.RefusedMoleculeAutoClose(err), nil
|
||||
}
|
||||
return storageissueops.MoleculeAutoClose{}, fmt.Errorf("auto-closing molecule %s: %w", root.ID, err)
|
||||
}
|
||||
params := domain.CloseIssueParams{Reason: req.Reason, Session: req.Session}
|
||||
var closed domain.CloseIssueResult
|
||||
if storageissueops.IsWisp(root) {
|
||||
closed, err = uw.IssueUseCase().CloseWispChecked(ctx, req.IssueID, params, req.Actor, req.Force)
|
||||
} else {
|
||||
closed, err = uw.IssueUseCase().CloseIssueChecked(ctx, req.IssueID, params, req.Actor, req.Force)
|
||||
}
|
||||
if publicops.IsMoleculeAutoCloseRefusal(err) {
|
||||
return storageissueops.RefusedMoleculeAutoClose(err), nil
|
||||
}
|
||||
if err != nil {
|
||||
return storageissueops.MoleculeAutoClose{}, fmt.Errorf("auto-closing molecule %s: %w", root.ID, err)
|
||||
}
|
||||
if !closed.Closed {
|
||||
return storageissueops.MoleculeAutoClose{}, nil
|
||||
}
|
||||
current := root
|
||||
if closed.Issue != nil {
|
||||
current = closed.Issue
|
||||
}
|
||||
hydrated, err := hydrateIssueOperation(ctx, uw, current, false, false)
|
||||
if err != nil {
|
||||
return storageissueops.MoleculeAutoClose{}, err
|
||||
}
|
||||
return storageissueops.MoleculeAutoClose{Root: hydrated}, nil
|
||||
}
|
||||
|
||||
// MoleculeStepperSource is the capability accessor a unit-of-work provider
|
||||
// offers for the advance-a-molecule role.
|
||||
type MoleculeStepperSource interface {
|
||||
MoleculeStepper() (publicops.MoleculeStepper, error)
|
||||
}
|
||||
|
||||
// MoleculeStepper returns the advance-a-molecule surface for this provider.
|
||||
func (p *doltSQLProvider) MoleculeStepper() (publicops.MoleculeStepper, error) {
|
||||
return NewMoleculeStepper(p)
|
||||
}
|
||||
|
||||
// NewMoleculeStepper is issueops.NewMoleculeStepper composed over the roles
|
||||
// THIS provider builds (its batch getter, relations, edge reader, claimer and
|
||||
// lifecycle), so a wrapper that builds its roles over itself — the notifying
|
||||
// provider, a policy decorator, the server's timed provider — gets an advance
|
||||
// whose every read and claim goes through its own layer.
|
||||
func NewMoleculeStepper(provider UnitOfWorkProvider) (publicops.MoleculeStepper, error) {
|
||||
if isNilUnitOfWorkProvider(provider) {
|
||||
return nil, fmt.Errorf("new molecule stepper: unit-of-work provider must not be nil")
|
||||
}
|
||||
getter, err := NewBatchGetter(provider)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
relations, err := NewIssueRelations(provider)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
edges, err := NewEdgeReader(provider)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
claimer, err := NewIssueClaimer(provider)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
lifecycle, err := NewIssueOperations(provider)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return publicops.NewMoleculeStepper(publicops.MoleculeStepperRoles{
|
||||
Reader: publicops.MoleculeReader{BatchGetter: getter, Relations: relations, EdgeReader: edges},
|
||||
Claimer: claimer,
|
||||
Lifecycle: lifecycle,
|
||||
}), nil
|
||||
}
|
||||
257
internal/storage/uow/molecule_contract_test.go
Normal file
257
internal/storage/uow/molecule_contract_test.go
Normal file
|
|
@ -0,0 +1,257 @@
|
|||
package uow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/backend/conformance"
|
||||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
publicops "github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// TestMoleculeContract runs the molecule contract against the unit-of-work
|
||||
// backend, whose auto-close body (CloseCompletedMoleculeInUOW) is its own and
|
||||
// whose stepper is composed over this provider's roles. One provider for the
|
||||
// suite; sequential subtests namespaced by prefix.
|
||||
func TestMoleculeContract(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
provider := newUOWRoleFixtureProvider(t, ctx, "mol")
|
||||
fixture := newUOWMoleculeFixture(t, provider, "mol")
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
run func(*testing.T, context.Context, conformance.MoleculeFixture)
|
||||
}{
|
||||
{"CloseAutoClosesTheCompletedRoot", conformance.RunMoleculeCloseAutoClosesTheCompletedRoot},
|
||||
{"AutoCloseIsOptInAndRuleBound", conformance.RunMoleculeAutoCloseIsOptInAndRuleBound},
|
||||
{"RecloseHealsAStrandedRoot", conformance.RunMoleculeRecloseHealsAStrandedRoot},
|
||||
{"BatchCloseAutoClosesTheRootOnce", conformance.RunMoleculeBatchCloseAutoClosesTheRootOnce},
|
||||
{"RefusedRootKeepsTheStepClose", conformance.RunMoleculeRefusedRootKeepsTheStepClose},
|
||||
{"GuardedRootKeepsTheStepClose", conformance.RunMoleculeGuardedRootKeepsTheStepClose},
|
||||
{"StepperClaimsTheNextReadyStepForTheActor", conformance.RunMoleculeStepperClaimsTheNextReadyStepForTheActor},
|
||||
{"StepperNeverTakesAStepAnotherActorHolds", conformance.RunMoleculeStepperNeverTakesAStepAnotherActorHolds},
|
||||
{"StepperAnswersCompleteAndOutsideAMolecule", conformance.RunMoleculeStepperAnswersCompleteAndOutsideAMolecule},
|
||||
{"StepperClaimsAWispStep", conformance.RunMoleculeStepperClaimsAWispStep},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) { test.run(t, ctx, fixture) })
|
||||
}
|
||||
}
|
||||
|
||||
func newUOWMoleculeFixture(t *testing.T, provider UnitOfWorkProvider, prefix string) conformance.MoleculeFixture {
|
||||
t.Helper()
|
||||
lifecycle, err := NewIssueOperations(provider)
|
||||
if err != nil {
|
||||
t.Fatalf("NewIssueOperations: %v", err)
|
||||
}
|
||||
closer, err := NewBatchCloser(provider)
|
||||
if err != nil {
|
||||
t.Fatalf("NewBatchCloser: %v", err)
|
||||
}
|
||||
source, ok := provider.(MoleculeStepperSource)
|
||||
if !ok {
|
||||
t.Fatalf("provider %T does not offer the MoleculeStepper accessor", provider)
|
||||
}
|
||||
stepper, err := source.MoleculeStepper()
|
||||
if err != nil {
|
||||
t.Fatalf("MoleculeStepper(): %v", err)
|
||||
}
|
||||
kit := newUOWRoleFixtureKit(provider, prefix)
|
||||
return conformance.MoleculeFixture{
|
||||
IssuePrefix: kit.IssuePrefix,
|
||||
Lifecycle: lifecycle,
|
||||
BatchCloser: closer,
|
||||
Stepper: stepper,
|
||||
CreateIssue: kit.CreateIssue,
|
||||
CreateWisp: kit.CreateWisp,
|
||||
AddDependency: kit.AddDependency,
|
||||
QueryScalar: kit.QueryScalar,
|
||||
}
|
||||
}
|
||||
|
||||
// seedRacingMoleculeInUOW seeds an auto-closing molecule root with n open
|
||||
// steps through kit and answers the steps.
|
||||
func seedRacingMoleculeInUOW(t *testing.T, ctx context.Context, kit roleFixtureKit, root string, n int) []string {
|
||||
t.Helper()
|
||||
if err := kit.CreateIssue(ctx, &types.Issue{ID: root, Title: "molecule " + root, IssueType: types.TypeMolecule, Status: types.StatusOpen, Priority: 2}, "tester"); err != nil {
|
||||
t.Fatalf("seed %s: %v", root, err)
|
||||
}
|
||||
steps := make([]string, n)
|
||||
for i := range steps {
|
||||
steps[i] = fmt.Sprintf("%s.%d", root, i+1)
|
||||
if err := kit.CreateIssue(ctx, &types.Issue{ID: steps[i], Title: "step " + steps[i], IssueType: types.TypeTask, Status: types.StatusOpen, Priority: 2}, "tester"); err != nil {
|
||||
t.Fatalf("seed %s: %v", steps[i], err)
|
||||
}
|
||||
if err := kit.AddDependency(ctx, &types.Dependency{IssueID: steps[i], DependsOnID: root, Type: types.DepParentChild}, "tester"); err != nil {
|
||||
t.Fatalf("seed edge %s -> %s: %v", steps[i], root, err)
|
||||
}
|
||||
}
|
||||
return steps
|
||||
}
|
||||
|
||||
func readStatusInUOW(t *testing.T, ctx context.Context, kit roleFixtureKit, id string) string {
|
||||
t.Helper()
|
||||
var status string
|
||||
if err := kit.QueryScalar(ctx, "SELECT status FROM issues WHERE id = ?", []any{id}, &status); err != nil {
|
||||
t.Fatalf("read %s status: %v", id, err)
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
// closeTwoStepsInRacingUOWs closes steps[0] and steps[1], each followed by
|
||||
// this backend's auto-close body (CloseCompletedMoleculeInUOW), in two units
|
||||
// of work that both decide before either commits, so each reads the other's
|
||||
// step open: the race's interleaving, made deterministic. Neither may
|
||||
// auto-close the root. It commits both and answers the two commit errors.
|
||||
func closeTwoStepsInRacingUOWs(t *testing.T, ctx context.Context, provider UnitOfWorkProvider, steps []string) [2]error {
|
||||
t.Helper()
|
||||
var uws [2]UnitOfWork
|
||||
for i := range uws {
|
||||
uw, err := provider.NewUOW(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("open unit of work %d: %v", i, err)
|
||||
}
|
||||
defer uw.Close(ctx) // no-op after Commit; preserves cleanup on early Fatal.
|
||||
uws[i] = uw
|
||||
}
|
||||
for i, uw := range uws {
|
||||
if _, err := uw.IssueUseCase().CloseIssueChecked(ctx, steps[i], domain.CloseIssueParams{Reason: "done"}, "tester", false); err != nil {
|
||||
t.Fatalf("close %s: %v", steps[i], err)
|
||||
}
|
||||
auto, err := CloseCompletedMoleculeInUOW(ctx, uw, steps[i], "tester", "")
|
||||
if err != nil {
|
||||
t.Fatalf("auto-close after %s: %v", steps[i], err)
|
||||
}
|
||||
if auto.Root != nil {
|
||||
t.Fatalf("close %s auto-closed %s, but in its own unit of work %s is still open", steps[i], auto.Root.ID, steps[1-i])
|
||||
}
|
||||
}
|
||||
return [2]error{uws[0].Commit(ctx, "close "+steps[0]), uws[1].Commit(ctx, "close "+steps[1])}
|
||||
}
|
||||
|
||||
// TestMoleculeAutoCloseLastStepsCannotBothMissTheRootInUOW is the unit-of-work
|
||||
// twin of the dolt store's two-transaction regression: two units of work that
|
||||
// each close one of a molecule's last two open steps and run this backend's
|
||||
// auto-close body (CloseCompletedMoleculeInUOW) each read the other's step
|
||||
// open, so neither closes the root. The coordination cell both rewrite must
|
||||
// make one commit conflict, or the complete molecule's root is stranded open.
|
||||
func TestMoleculeAutoCloseLastStepsCannotBothMissTheRootInUOW(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
provider := newUOWRoleFixtureProvider(t, ctx, "molrace")
|
||||
kit := newUOWRoleFixtureKit(provider, "molrace")
|
||||
root := kit.IssuePrefix + "-race"
|
||||
|
||||
commitErrs := closeTwoStepsInRacingUOWs(t, ctx, provider, seedRacingMoleculeInUOW(t, ctx, kit, root, 2))
|
||||
t.Logf("last-step commits: %v", commitErrs)
|
||||
if commitErrs[0] == nil && commitErrs[1] == nil {
|
||||
t.Fatalf("stranded molecule: both last-step closes committed and %s is %s with every step closed; one unit of work must conflict",
|
||||
root, readStatusInUOW(t, ctx, kit, root))
|
||||
}
|
||||
for i, err := range commitErrs {
|
||||
if err != nil && !isSerializationError(err) {
|
||||
t.Fatalf("commit %d error = %v, want a serialization conflict", i, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestMoleculeAutoCloseSiblingClosesConflictBeforeTheLastStepInUOW is the
|
||||
// unit-of-work twin of the dolt store's pin on the coordination cell's cost:
|
||||
// two concurrent sibling closes under an open auto-closing root conflict even
|
||||
// while a third step keeps the molecule from completing. If this stops
|
||||
// conflicting, the docs that state the cost are stale.
|
||||
func TestMoleculeAutoCloseSiblingClosesConflictBeforeTheLastStepInUOW(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
provider := newUOWRoleFixtureProvider(t, ctx, "molsib")
|
||||
kit := newUOWRoleFixtureKit(provider, "molsib")
|
||||
|
||||
commitErrs := closeTwoStepsInRacingUOWs(t, ctx, provider, seedRacingMoleculeInUOW(t, ctx, kit, kit.IssuePrefix+"-siblings", 3))
|
||||
t.Logf("sibling commits: %v", commitErrs)
|
||||
if commitErrs[0] == nil && commitErrs[1] == nil {
|
||||
t.Fatal("two concurrent sibling closes under an open auto-closing root both committed; want one serialization conflict")
|
||||
}
|
||||
for i, err := range commitErrs {
|
||||
if err != nil && !isSerializationError(err) {
|
||||
t.Fatalf("commit %d error = %v, want a serialization conflict", i, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// raceMoleculeClosesInUOW seeds an auto-closing molecule of n steps under
|
||||
// root and closes every step at once through lifecycle, whose RunTxResult
|
||||
// replays each unit of work that loses the coordination conflict. Every close
|
||||
// must land, and the root must end closed, reported by exactly one of them.
|
||||
func raceMoleculeClosesInUOW(t *testing.T, ctx context.Context, kit roleFixtureKit, lifecycle publicops.Lifecycle, root string, n int) {
|
||||
t.Helper()
|
||||
steps := seedRacingMoleculeInUOW(t, ctx, kit, root, n)
|
||||
var (
|
||||
start = make(chan struct{})
|
||||
wg sync.WaitGroup
|
||||
results = make([]publicops.CloseResult, n)
|
||||
errs = make([]error, n)
|
||||
)
|
||||
for i, step := range steps {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
results[i], errs[i] = lifecycle.Close(ctx, publicops.CloseRequest{
|
||||
Actor: "tester", IssueID: step, Reason: "done", AutoCloseMolecule: true,
|
||||
})
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
|
||||
reported := 0
|
||||
for i, err := range errs {
|
||||
if err != nil {
|
||||
t.Fatalf("close %s: %v", steps[i], err)
|
||||
}
|
||||
if results[i].AutoClosedMolecule != nil {
|
||||
reported++
|
||||
}
|
||||
}
|
||||
if status := readStatusInUOW(t, ctx, kit, root); status != string(types.StatusClosed) {
|
||||
t.Fatalf("%s is %s after all %d of its steps closed, want closed", root, status, n)
|
||||
}
|
||||
if reported != 1 {
|
||||
t.Errorf("%s was reported by %d closes, want exactly one", root, reported)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMoleculeAutoCloseConcurrentLastStepsCloseTheRootInUOW races the closes
|
||||
// of a molecule's last two steps through this backend's Lifecycle role, whose
|
||||
// RunTxResult replays the unit of work that loses the coordination conflict:
|
||||
// in every round the root ends closed, reported by exactly one of the closes.
|
||||
func TestMoleculeAutoCloseConcurrentLastStepsCloseTheRootInUOW(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
provider := newUOWRoleFixtureProvider(t, ctx, "molagg")
|
||||
kit := newUOWRoleFixtureKit(provider, "molagg")
|
||||
lifecycle, err := NewIssueOperations(provider)
|
||||
if err != nil {
|
||||
t.Fatalf("NewIssueOperations: %v", err)
|
||||
}
|
||||
|
||||
const rounds = 8
|
||||
for round := range rounds {
|
||||
raceMoleculeClosesInUOW(t, ctx, kit, lifecycle, fmt.Sprintf("%s-race-%d", kit.IssuePrefix, round), 2)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMoleculeAutoCloseSiblingFanOutClosesTheRootInUOW is the unit-of-work
|
||||
// twin of the dolt store's fan-out: all the steps of one molecule closed at
|
||||
// once serialize on the root's coordination cell, and RunTxResult carries
|
||||
// every one of them to a commit, closing the root exactly once.
|
||||
func TestMoleculeAutoCloseSiblingFanOutClosesTheRootInUOW(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
provider := newUOWRoleFixtureProvider(t, ctx, "molfan")
|
||||
kit := newUOWRoleFixtureKit(provider, "molfan")
|
||||
lifecycle, err := NewIssueOperations(provider)
|
||||
if err != nil {
|
||||
t.Fatalf("NewIssueOperations: %v", err)
|
||||
}
|
||||
|
||||
raceMoleculeClosesInUOW(t, ctx, kit, lifecycle, kit.IssuePrefix+"-fanout", 6)
|
||||
}
|
||||
|
|
@ -242,6 +242,10 @@ func (p *notifyingProvider) BatchGetter() (publicops.BatchGetter, error) {
|
|||
return NewBatchGetter(p)
|
||||
}
|
||||
|
||||
func (p *notifyingProvider) MoleculeStepper() (publicops.MoleculeStepper, error) {
|
||||
return NewMoleculeStepper(p)
|
||||
}
|
||||
|
||||
func (p *notifyingProvider) Counter() (publicops.Counter, error) { return NewCounter(p) }
|
||||
|
||||
func (p *notifyingProvider) ReadyCounter() (publicops.ReadyCounter, error) {
|
||||
|
|
@ -409,6 +413,7 @@ var (
|
|||
_ TreeWalkerSource = (*notifyingProvider)(nil)
|
||||
_ GraphCounterSource = (*notifyingProvider)(nil)
|
||||
_ BatchGetterSource = (*notifyingProvider)(nil)
|
||||
_ MoleculeStepperSource = (*notifyingProvider)(nil)
|
||||
_ CounterSource = (*notifyingProvider)(nil)
|
||||
_ ReadyCounterSource = (*notifyingProvider)(nil)
|
||||
_ ReadyClaimerSource = (*notifyingProvider)(nil)
|
||||
|
|
|
|||
|
|
@ -48,29 +48,35 @@ func (r *issueRelations) Related(ctx context.Context, request publicops.RelatedR
|
|||
if err := storageissueops.ValidateRelatedRequest(request); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return RunTxRead(ctx, r.provider, func(ctx context.Context, uw UnitOfWork) ([]*publicops.RelatedIssue, error) {
|
||||
return RelatedInUOW(ctx, uw, request)
|
||||
})
|
||||
}
|
||||
|
||||
// RelatedInUOW is the Relations body, run inside the caller's unit of work.
|
||||
// The request must already be validated.
|
||||
func RelatedInUOW(ctx context.Context, uw UnitOfWork, request publicops.RelatedRequest) ([]*publicops.RelatedIssue, error) {
|
||||
direction := domain.DepDirectionOut
|
||||
if request.Direction == publicops.RelationIn {
|
||||
direction = domain.DepDirectionIn
|
||||
}
|
||||
return RunTxRead(ctx, r.provider, func(ctx context.Context, uw UnitOfWork) ([]*publicops.RelatedIssue, error) {
|
||||
issue, isWisp, err := workapi.GetIssueOrWisp(ctx, workapi.NewUOWDetailSource(uw), request.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
filter := domain.DepListFilter{Direction: direction}
|
||||
var items []*publicops.RelatedIssue
|
||||
if isWisp {
|
||||
items, err = uw.DependencyUseCase().ListWispWithIssueMetadata(ctx, issue.ID, filter)
|
||||
} else {
|
||||
items, err = uw.DependencyUseCase().ListWithIssueMetadata(ctx, issue.ID, filter)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// The filter runs HERE rather than in the use-case call above so both
|
||||
// implementations narrow and order through one function; passing
|
||||
// filter.Types down would put the narrowing in the query on one side
|
||||
// and in Go on the other.
|
||||
return storageissueops.FinishRelatedPage(items, request.Types), nil
|
||||
})
|
||||
issue, isWisp, err := workapi.GetIssueOrWisp(ctx, workapi.NewUOWDetailSource(uw), request.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
filter := domain.DepListFilter{Direction: direction}
|
||||
var items []*publicops.RelatedIssue
|
||||
if isWisp {
|
||||
items, err = uw.DependencyUseCase().ListWispWithIssueMetadata(ctx, issue.ID, filter)
|
||||
} else {
|
||||
items, err = uw.DependencyUseCase().ListWithIssueMetadata(ctx, issue.ID, filter)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// The filter runs HERE rather than in the use-case call above so both
|
||||
// implementations narrow and order through one function; passing
|
||||
// filter.Types down would put the narrowing in the query on one side
|
||||
// and in Go on the other.
|
||||
return storageissueops.FinishRelatedPage(items, request.Types), nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ go_library(
|
|||
"lease_reclaimer.go",
|
||||
"memories.go",
|
||||
"metadata_cas.go",
|
||||
"molecule_stepper.go",
|
||||
"querier.go",
|
||||
"ready_claimer.go",
|
||||
"ready_counter.go",
|
||||
|
|
|
|||
35
internal/telemetry/molecule_stepper.go
Normal file
35
internal/telemetry/molecule_stepper.go
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// MoleculeStepper returns the inner store's advance surface wrapped in this
|
||||
// layer's instrumentation.
|
||||
func (s *InstrumentedStorage) MoleculeStepper() (issueops.MoleculeStepper, error) {
|
||||
inner, err := s.Unwrap().MoleculeStepper()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.WrapMoleculeStepper(inner), nil
|
||||
}
|
||||
|
||||
// WrapMoleculeStepper instruments molecule advances with this storage layer's
|
||||
// existing telemetry meter and tracer.
|
||||
func (s *InstrumentedStorage) WrapMoleculeStepper(inner issueops.MoleculeStepper) issueops.MoleculeStepper {
|
||||
return &instrumentedMoleculeStepper{storage: s, inner: inner}
|
||||
}
|
||||
|
||||
type instrumentedMoleculeStepper struct {
|
||||
storage *InstrumentedStorage
|
||||
inner issueops.MoleculeStepper
|
||||
}
|
||||
|
||||
func (m *instrumentedMoleculeStepper) Advance(ctx context.Context, req issueops.AdvanceRequest) (result issueops.AdvanceResult, err error) {
|
||||
ctx, span, started := m.storage.op(ctx, "MoleculeStepper.Advance")
|
||||
result, err = m.inner.Advance(ctx, req)
|
||||
m.storage.done(ctx, span, started, err)
|
||||
return result, err
|
||||
}
|
||||
|
|
@ -24,6 +24,9 @@ go_library(
|
|||
"issueops.go",
|
||||
"leasereclaimer.go",
|
||||
"metadatacas.go",
|
||||
"molecule.go",
|
||||
"molecule_active.go",
|
||||
"moleculestepper.go",
|
||||
"querier.go",
|
||||
"reader.go",
|
||||
"reader_ready_scope.go",
|
||||
|
|
@ -51,10 +54,13 @@ go_test(
|
|||
srcs = [
|
||||
"claimer_external_test.go",
|
||||
"issueops_external_test.go",
|
||||
"molecule_internal_test.go",
|
||||
"molecule_test.go",
|
||||
],
|
||||
embed = [":issueops"],
|
||||
deps = [
|
||||
":issueops",
|
||||
"//:beads",
|
||||
"//internal/types",
|
||||
],
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -69,6 +69,15 @@ type CloseBatchRequest struct {
|
|||
// rule, the same nil-means-nothing-eligible outcome. Restating them here
|
||||
// is how the two would come apart.
|
||||
ClaimNext *ReadyRequest
|
||||
// AutoCloseMolecule is CloseRequest.AutoCloseMolecule for every item
|
||||
// that closed or was already closed. It runs after all the closes and
|
||||
// before ClaimNext, inside the same transaction, so a batch that closes
|
||||
// several steps of one molecule decides its root once, after every close:
|
||||
// the root it closed, or its refusal, is reported on the outcome of the
|
||||
// first item under that root whose Err is nil. An auto-closed root is a
|
||||
// landing: it is named in the batch's history entry. It does not earn
|
||||
// ClaimNext's claim on its own.
|
||||
AutoCloseMolecule bool
|
||||
}
|
||||
|
||||
// CloseOutcome is what happened to ONE requested item.
|
||||
|
|
@ -85,6 +94,10 @@ type CloseOutcome struct {
|
|||
// OpenChildren is the number of open children observed by a forced close
|
||||
// of this item. It is reported even for an idempotent re-close.
|
||||
OpenChildren int
|
||||
// AutoClosedMolecule and MoleculeAutoCloseRefusal are
|
||||
// CloseResult's, for this item, under CloseBatchRequest.AutoCloseMolecule.
|
||||
AutoClosedMolecule *Issue
|
||||
MoleculeAutoCloseRefusal string
|
||||
// Err is this item's refusal, and NEVER aborts the rest of the batch. It
|
||||
// carries the same typed close vocabulary Lifecycle.Close returns —
|
||||
// ErrNotFound, ErrCloseBlocked, *CloseOpenChildrenError,
|
||||
|
|
|
|||
|
|
@ -395,6 +395,47 @@ type CloseRequest struct {
|
|||
// a miss refuses with ErrVersionMismatch having written nothing. Force
|
||||
// bypasses close policy and never this guard.
|
||||
ExpectedVersion *int64
|
||||
// AutoCloseMolecule closes the issue's molecule root IN THE SAME
|
||||
// TRANSACTION when this close completed it: the root closes itself when
|
||||
// complete (AutoClosesWhenComplete), it is open, and every step under it
|
||||
// is now closed (CompletedMolecule). The root close is unforced, guarded
|
||||
// on the root revision read inside that transaction, and records
|
||||
// MoleculeAutoCloseReason and this request's Session.
|
||||
//
|
||||
// It runs for an idempotent re-close too: the rule is state-derived, so a
|
||||
// replayed close of the last step heals a root a crash left open.
|
||||
//
|
||||
// IT IS OPT-IN because an orchestrator may run its own molecule
|
||||
// lifecycle (gc closes molecule roots itself); the zero value never
|
||||
// touches a root. A root close its close policy refuses (a live blocker
|
||||
// on the root, open children) or a close guard refuses (a template root, a
|
||||
// pinned root, a root assigned to someone other than Actor — the root
|
||||
// close is unforced, so each guard holds as it does for a direct close)
|
||||
// leaves the root open and is reported on
|
||||
// CloseResult.MoleculeAutoCloseRefusal (IsMoleculeAutoCloseRefusal); it
|
||||
// never fails the step close.
|
||||
//
|
||||
// ANY OTHER FAILURE OF THE ROOT CLOSE FAILS THE STEP'S CLOSE. A storage
|
||||
// error is returned and rolls the step's close back with it, so a retry
|
||||
// re-runs both. (The CLI used to close the root after the step's close had
|
||||
// committed and only warned when that failed, leaving a complete
|
||||
// molecule's root open.) A write to the root that races this close is not
|
||||
// such a failure: the two conflict at commit, and the backend's retry
|
||||
// decides the root again (MoleculeRootClose).
|
||||
//
|
||||
// Two closes that finish a molecule's last steps concurrently do not
|
||||
// strand its root: each close that decides a root first rewrites one
|
||||
// coordination cell for it, so their transactions conflict at commit and
|
||||
// the one that retries reads the other's close and closes the root.
|
||||
//
|
||||
// THE CELL SERIALIZES SIBLING CLOSES. Every close under an open
|
||||
// auto-closing root rewrites it, whether or not that close completes the
|
||||
// molecule, so any two concurrent closes of steps under the same root
|
||||
// conflict and one of them retries. Under heavy fan-out a close can spend
|
||||
// its whole retry budget conflicting and then fails with the
|
||||
// serialization error. Closes under different roots contend only when
|
||||
// their roots hash to the same cell.
|
||||
AutoCloseMolecule bool
|
||||
}
|
||||
|
||||
// ReopenRequest describes an issue reopening.
|
||||
|
|
@ -457,6 +498,15 @@ type CloseResult struct {
|
|||
// OpenChildren is the number of open children observed by a forced close.
|
||||
// It is reported even for an idempotent re-close.
|
||||
OpenChildren int
|
||||
// AutoClosedMolecule is the molecule root CloseRequest.AutoCloseMolecule
|
||||
// closed in this close's transaction, as a post-close snapshot with
|
||||
// labels. Nil when nothing was auto-closed.
|
||||
AutoClosedMolecule *Issue
|
||||
// MoleculeAutoCloseRefusal says why a completed molecule's root stayed
|
||||
// open: its close policy or a close guard refused it
|
||||
// (IsMoleculeAutoCloseRefusal), in that refusal's own message, the same on
|
||||
// every backend. Empty otherwise.
|
||||
MoleculeAutoCloseRefusal string
|
||||
}
|
||||
|
||||
// ReopenResult reports the post-reopen issue as a detached post-state snapshot
|
||||
|
|
|
|||
869
issueops/molecule.go
Normal file
869
issueops/molecule.go
Normal file
|
|
@ -0,0 +1,869 @@
|
|||
package issueops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
// MoleculeTemplateLabel is the label that marks an epic as a template-driven
|
||||
// molecule root. `bd mol distill` writes it; a poured molecule's root is
|
||||
// TypeMolecule instead and carries no label.
|
||||
const MoleculeTemplateLabel = "template"
|
||||
|
||||
// MoleculeReader is the read surface every molecule operation in this file is
|
||||
// composed over: three roles every backend serves.
|
||||
//
|
||||
// - BatchGetter answers the molecule root and the parent walk's candidate
|
||||
// roots, labeled, in either plane.
|
||||
// - Relations answers a node's inbound parent-child steps as FULL rows, in
|
||||
// either plane.
|
||||
// - EdgeReader answers the parent walk (a step's outgoing parent-child edge)
|
||||
// and the blocking edges between a molecule's steps.
|
||||
//
|
||||
// THE MOLECULE RULES HAVE ONE IMPLEMENTATION, and it is the functions below.
|
||||
// A caller that reads committed state binds them to the roles
|
||||
// (NewMoleculeReader). A close that must decide inside its own
|
||||
// transaction binds them to the same three role BODIES running against that
|
||||
// transaction (internal/storage/issueops.TxMoleculeReader, and the unit-of-work
|
||||
// backend's MoleculeReaderInUOW), so a molecule's membership, completion and
|
||||
// readiness mean one thing on every backend and every route.
|
||||
//
|
||||
// Membership is the parent-child EDGE. A child whose id merely looks
|
||||
// hierarchical (<root>.<n>) but carries no edge is not a step: no role can
|
||||
// express an id-pattern scan, and a rule only some routes could apply would
|
||||
// make the same molecule answer differently per route.
|
||||
type MoleculeReader struct {
|
||||
BatchGetter
|
||||
Relations
|
||||
EdgeReader
|
||||
}
|
||||
|
||||
// MoleculeReaderOver binds one value that answers all three role reads — an
|
||||
// in-transaction binding, a test double — as a MoleculeReader.
|
||||
func MoleculeReaderOver(r interface {
|
||||
BatchGetter
|
||||
Relations
|
||||
EdgeReader
|
||||
}) MoleculeReader {
|
||||
return MoleculeReader{BatchGetter: r, Relations: r, EdgeReader: r}
|
||||
}
|
||||
|
||||
func (r MoleculeReader) usable() bool {
|
||||
return r.BatchGetter != nil && r.Relations != nil && r.EdgeReader != nil
|
||||
}
|
||||
|
||||
// moleculeRoleSource is the accessor set a store or a unit-of-work provider
|
||||
// offers for the three roles a MoleculeReader composes.
|
||||
type moleculeRoleSource interface {
|
||||
BatchGetter() (BatchGetter, error)
|
||||
IssueRelations() (Relations, error)
|
||||
EdgeReader() (EdgeReader, error)
|
||||
}
|
||||
|
||||
// NewMoleculeReader binds a MoleculeReader to src's own role accessors, so
|
||||
// every decorator src wears (hooks, telemetry, policy) stays in the path. src
|
||||
// is a storage.DoltStorage or a unit-of-work provider.
|
||||
func NewMoleculeReader(src moleculeRoleSource) (MoleculeReader, error) {
|
||||
if src == nil {
|
||||
return MoleculeReader{}, fmt.Errorf("%w: molecule reader needs a role source", ErrValidation)
|
||||
}
|
||||
getter, err := src.BatchGetter()
|
||||
if err != nil {
|
||||
return MoleculeReader{}, err
|
||||
}
|
||||
relations, err := src.IssueRelations()
|
||||
if err != nil {
|
||||
return MoleculeReader{}, err
|
||||
}
|
||||
edges, err := src.EdgeReader()
|
||||
if err != nil {
|
||||
return MoleculeReader{}, err
|
||||
}
|
||||
return MoleculeReader{BatchGetter: getter, Relations: relations, EdgeReader: edges}, nil
|
||||
}
|
||||
|
||||
// IsMoleculeRoot reports whether issue is the root of a molecule: an epic, a
|
||||
// TypeMolecule root (`bd mol pour`), or anything carrying the template label.
|
||||
func IsMoleculeRoot(issue *Issue) bool {
|
||||
if issue == nil {
|
||||
return false
|
||||
}
|
||||
if issue.IssueType == types.TypeEpic || issue.IssueType == types.TypeMolecule {
|
||||
return true
|
||||
}
|
||||
return hasLabel(issue, MoleculeTemplateLabel)
|
||||
}
|
||||
|
||||
// AutoClosesWhenComplete reports whether a molecule root closes itself when
|
||||
// its last step closes. Molecule-typed and ephemeral roots do, and so does a
|
||||
// template-driven epic; an ordinary epic stays open so it becomes explicit,
|
||||
// close-eligible work instead of closing as a side effect.
|
||||
func AutoClosesWhenComplete(root *Issue) bool {
|
||||
if root == nil {
|
||||
return false
|
||||
}
|
||||
if root.IssueType == types.TypeMolecule || root.Ephemeral {
|
||||
return true
|
||||
}
|
||||
return root.IssueType == types.TypeEpic && hasLabel(root, MoleculeTemplateLabel)
|
||||
}
|
||||
|
||||
func hasLabel(issue *Issue, label string) bool {
|
||||
for _, l := range issue.Labels {
|
||||
if l == label {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// maxMoleculeDepth bounds the parent walk, so a parent-child cycle ends.
|
||||
const maxMoleculeDepth = 50
|
||||
|
||||
// MoleculeRoots walks parent-child edges up from every id and answers, for
|
||||
// each id that belongs to a molecule, the id of its molecule root. An id whose
|
||||
// topmost ancestor is not a molecule root (IsMoleculeRoot) is omitted, and so
|
||||
// is an id that names nothing. A root that is itself a molecule root answers
|
||||
// itself.
|
||||
//
|
||||
// The walk is level by level, one edge read per level for every chain at
|
||||
// once, so its cost is the depth of the deepest chain, not the number of ids.
|
||||
// A read the backend fails or refuses is RETURNED: answering "not in a
|
||||
// molecule" for a read that never happened is how a molecule root gets
|
||||
// stranded open.
|
||||
func MoleculeRoots(ctx context.Context, r MoleculeReader, ids []string) (map[string]string, error) {
|
||||
rows, err := moleculeRootRows(ctx, r, ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make(map[string]string, len(rows))
|
||||
for start, root := range rows {
|
||||
out[start] = root.ID
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// moleculeRootRows is MoleculeRoots answering each id's molecule root ROW, as
|
||||
// the walk read it.
|
||||
func moleculeRootRows(ctx context.Context, r MoleculeReader, ids []string) (map[string]*Issue, error) {
|
||||
out := map[string]*Issue{}
|
||||
if len(ids) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
if !r.usable() {
|
||||
return nil, fmt.Errorf("%w: molecule reads need a reader", ErrValidation)
|
||||
}
|
||||
topOf := make(map[string]string, len(ids))
|
||||
current := make(map[string]string, len(ids))
|
||||
for _, id := range ids {
|
||||
current[id] = id
|
||||
}
|
||||
for depth := 0; depth < maxMoleculeDepth && len(current) > 0; depth++ {
|
||||
level := distinctValues(current)
|
||||
parentOf, err := parentChildParents(ctx, r, level)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
next := make(map[string]string, len(current))
|
||||
for start, at := range current {
|
||||
if parent, ok := parentOf[at]; ok {
|
||||
next[start] = parent
|
||||
} else {
|
||||
topOf[start] = at
|
||||
}
|
||||
}
|
||||
current = next
|
||||
}
|
||||
for start, at := range current {
|
||||
topOf[start] = at
|
||||
}
|
||||
|
||||
tops, err := getIssues(ctx, r, distinctValues(topOf))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("loading molecule roots: %w", err)
|
||||
}
|
||||
for start, top := range topOf {
|
||||
if root := tops[top]; IsMoleculeRoot(root) {
|
||||
out[start] = root
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// MoleculeRoot is MoleculeRoots for one id: the id's molecule root, or "" when
|
||||
// it belongs to no molecule.
|
||||
func MoleculeRoot(ctx context.Context, r MoleculeReader, id string) (string, error) {
|
||||
roots, err := MoleculeRoots(ctx, r, []string{id})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return roots[id], nil
|
||||
}
|
||||
|
||||
// parentChildParents answers each id's first outgoing parent-child target.
|
||||
func parentChildParents(ctx context.Context, r MoleculeReader, ids []string) (map[string]string, error) {
|
||||
res, err := r.ReadEdges(ctx, EdgeReadRequest{IDs: ids, Types: []types.DependencyType{types.DepParentChild}})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("walking parent-child edges: %w", err)
|
||||
}
|
||||
parentOf := make(map[string]string, len(res.Anchors))
|
||||
for _, anchor := range res.Anchors {
|
||||
for _, edge := range anchor.Edges {
|
||||
if edge != nil && edge.Type == types.DepParentChild {
|
||||
parentOf[anchor.ID] = edge.DependsOnID
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return parentOf, nil
|
||||
}
|
||||
|
||||
// getIssues reads ids through the BatchGetter in batches the role accepts and
|
||||
// answers them by id. Missing ids are absent.
|
||||
func getIssues(ctx context.Context, r MoleculeReader, ids []string) (map[string]*Issue, error) {
|
||||
out := make(map[string]*Issue, len(ids))
|
||||
for start := 0; start < len(ids); start += MaxGetManyIDs {
|
||||
end := min(start+MaxGetManyIDs, len(ids))
|
||||
res, err := r.GetMany(ctx, GetManyRequest{IDs: ids[start:end]})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, issue := range res.Issues {
|
||||
if issue != nil {
|
||||
out[issue.ID] = issue
|
||||
}
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func distinctValues(m map[string]string) []string {
|
||||
seen := make(map[string]bool, len(m))
|
||||
out := make([]string, 0, len(m))
|
||||
for _, v := range m {
|
||||
if !seen[v] {
|
||||
seen[v] = true
|
||||
out = append(out, v)
|
||||
}
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// MoleculeGraph is a molecule root, every step under it and the edges between
|
||||
// them.
|
||||
type MoleculeGraph struct {
|
||||
// Root is the molecule root, labeled.
|
||||
Root *Issue
|
||||
// Issues holds the root first, then every descendant in depth-first
|
||||
// pre-order of the parent-child edges.
|
||||
Issues []*Issue
|
||||
// Dependencies holds every stored edge whose two ends are both in Issues.
|
||||
Dependencies []*Dependency
|
||||
// IssueMap indexes Issues by id.
|
||||
IssueMap map[string]*Issue
|
||||
}
|
||||
|
||||
// LoadMolecule reads the molecule rooted at rootID: the root, every
|
||||
// parent-child descendant as a full row, and the edges between them. A root
|
||||
// that names nothing is ErrNotFound. A parent-child cycle terminates.
|
||||
func LoadMolecule(ctx context.Context, r MoleculeReader, rootID string) (*MoleculeGraph, error) {
|
||||
if !r.usable() {
|
||||
return nil, fmt.Errorf("%w: molecule reads need a reader", ErrValidation)
|
||||
}
|
||||
roots, err := getIssues(ctx, r, []string{rootID})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("loading molecule %s: %w", rootID, err)
|
||||
}
|
||||
root := roots[rootID]
|
||||
if root == nil {
|
||||
return nil, fmt.Errorf("%w: molecule %s", ErrNotFound, rootID)
|
||||
}
|
||||
g := &MoleculeGraph{Root: root, Issues: []*Issue{root}, IssueMap: map[string]*Issue{root.ID: root}}
|
||||
if err := loadMoleculeChildren(ctx, r, g, root.ID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ids := make([]string, len(g.Issues))
|
||||
for i, issue := range g.Issues {
|
||||
ids[i] = issue.ID
|
||||
}
|
||||
edges, err := r.ReadEdges(ctx, EdgeReadRequest{IDs: ids})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reading molecule %s edges: %w", rootID, err)
|
||||
}
|
||||
for _, anchor := range edges.Anchors {
|
||||
for _, edge := range anchor.Edges {
|
||||
if edge == nil {
|
||||
continue
|
||||
}
|
||||
if _, ok := g.IssueMap[edge.DependsOnID]; ok {
|
||||
g.Dependencies = append(g.Dependencies, edge)
|
||||
}
|
||||
}
|
||||
}
|
||||
return g, nil
|
||||
}
|
||||
|
||||
func loadMoleculeChildren(ctx context.Context, r MoleculeReader, g *MoleculeGraph, parentID string) error {
|
||||
children, err := r.Related(ctx, RelatedRequest{
|
||||
ID: parentID,
|
||||
Direction: RelationIn,
|
||||
Types: []types.DependencyType{types.DepParentChild},
|
||||
})
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("reading the steps of %s: %w", parentID, err)
|
||||
}
|
||||
for _, child := range children {
|
||||
if child == nil || child.DependencyType != types.DepParentChild {
|
||||
continue
|
||||
}
|
||||
if _, seen := g.IssueMap[child.ID]; seen {
|
||||
continue
|
||||
}
|
||||
issue := child.Issue
|
||||
g.Issues = append(g.Issues, &issue)
|
||||
g.IssueMap[issue.ID] = &issue
|
||||
if err := loadMoleculeChildren(ctx, r, g, issue.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MoleculeStepInfo is one node's readiness inside its molecule.
|
||||
type MoleculeStepInfo struct {
|
||||
StepID string `json:"step_id"`
|
||||
Status string `json:"status"`
|
||||
IsReady bool `json:"is_ready"` // Can start now (no open blocker)
|
||||
ParallelGroup string `json:"parallel_group"` // Steps sharing a group can run concurrently
|
||||
BlockedBy []string `json:"blocked_by"` // Open steps blocking this one
|
||||
Blocks []string `json:"blocks"` // Steps this one blocks
|
||||
CanParallel []string `json:"can_parallel"` // Steps that can run in parallel with this one
|
||||
}
|
||||
|
||||
// MoleculeAnalysis is the readiness and parallelism of every node of a
|
||||
// molecule, root included.
|
||||
type MoleculeAnalysis struct {
|
||||
MoleculeID string `json:"molecule_id"`
|
||||
TotalSteps int `json:"total_steps"`
|
||||
ReadySteps int `json:"ready_steps"`
|
||||
ParallelGroups map[string][]string `json:"parallel_groups"` // group id -> step ids
|
||||
Steps map[string]*MoleculeStepInfo `json:"steps"`
|
||||
}
|
||||
|
||||
// AnalyzeMolecule computes readiness from the edges inside the molecule
|
||||
// rather than from the workspace ready query, which excludes ephemeral rows (a
|
||||
// wisp molecule's steps are ephemeral by definition). A node is ready when it
|
||||
// is open or in progress and no open node blocks it through a blocks,
|
||||
// conditional-blocks or waits-for edge. Nodes at the same blocking depth that
|
||||
// do not block each other share a parallel group.
|
||||
func AnalyzeMolecule(g *MoleculeGraph) *MoleculeAnalysis {
|
||||
analysis := &MoleculeAnalysis{
|
||||
MoleculeID: g.Root.ID,
|
||||
TotalSteps: len(g.Issues),
|
||||
ParallelGroups: make(map[string][]string),
|
||||
Steps: make(map[string]*MoleculeStepInfo),
|
||||
}
|
||||
|
||||
blockedBy := make(map[string]map[string]bool)
|
||||
blocks := make(map[string]map[string]bool)
|
||||
parentChildren := make(map[string][]string)
|
||||
for _, issue := range g.Issues {
|
||||
blockedBy[issue.ID] = make(map[string]bool)
|
||||
blocks[issue.ID] = make(map[string]bool)
|
||||
}
|
||||
for _, dep := range g.Dependencies {
|
||||
if dep.Type == types.DepParentChild {
|
||||
parentChildren[dep.DependsOnID] = append(parentChildren[dep.DependsOnID], dep.IssueID)
|
||||
}
|
||||
}
|
||||
for _, dep := range g.Dependencies {
|
||||
switch dep.Type {
|
||||
case types.DepBlocks, types.DepConditionalBlocks:
|
||||
if _, ok := blockedBy[dep.IssueID]; ok {
|
||||
blockedBy[dep.IssueID][dep.DependsOnID] = true
|
||||
}
|
||||
if _, ok := blocks[dep.DependsOnID]; ok {
|
||||
blocks[dep.DependsOnID][dep.IssueID] = true
|
||||
}
|
||||
case types.DepWaitsFor:
|
||||
children := parentChildren[dep.DependsOnID]
|
||||
if len(children) == 0 {
|
||||
continue
|
||||
}
|
||||
if types.ParseWaitsForGateMetadata(dep.Metadata) == types.WaitsForAnyChildren && anyClosed(g, children) {
|
||||
continue
|
||||
}
|
||||
// For all-children (and unresolved any-children) every open child
|
||||
// blocks the gate.
|
||||
for _, childID := range children {
|
||||
child := g.IssueMap[childID]
|
||||
if child == nil || child.Status == types.StatusClosed {
|
||||
continue
|
||||
}
|
||||
if _, ok := blockedBy[dep.IssueID]; ok {
|
||||
blockedBy[dep.IssueID][childID] = true
|
||||
}
|
||||
if _, ok := blocks[childID]; ok {
|
||||
blocks[childID][dep.IssueID] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, issue := range g.Issues {
|
||||
info := &MoleculeStepInfo{StepID: issue.ID, Status: string(issue.Status), BlockedBy: []string{}, Blocks: []string{}}
|
||||
for blockerID := range blockedBy[issue.ID] {
|
||||
if blocker := g.IssueMap[blockerID]; blocker != nil && blocker.Status != types.StatusClosed {
|
||||
info.BlockedBy = append(info.BlockedBy, blockerID)
|
||||
}
|
||||
}
|
||||
for blockedID := range blocks[issue.ID] {
|
||||
info.Blocks = append(info.Blocks, blockedID)
|
||||
}
|
||||
info.IsReady = (issue.Status == types.StatusOpen || issue.Status == types.StatusInProgress) && len(info.BlockedBy) == 0
|
||||
if info.IsReady {
|
||||
analysis.ReadySteps++
|
||||
}
|
||||
sort.Strings(info.BlockedBy)
|
||||
sort.Strings(info.Blocks)
|
||||
analysis.Steps[issue.ID] = info
|
||||
}
|
||||
|
||||
depths := blockingDepths(g, blockedBy)
|
||||
depthGroups := make(map[int][]string)
|
||||
for _, issue := range g.Issues {
|
||||
depthGroups[depths[issue.ID]] = append(depthGroups[depths[issue.ID]], issue.ID)
|
||||
}
|
||||
groupCounter := 0
|
||||
for depth := 0; depth <= len(g.Issues); depth++ {
|
||||
groupCounter = groupParallelSteps(analysis, depthGroups[depth], blocks, blockedBy, groupCounter)
|
||||
}
|
||||
return analysis
|
||||
}
|
||||
|
||||
func anyClosed(g *MoleculeGraph, ids []string) bool {
|
||||
for _, id := range ids {
|
||||
if child := g.IssueMap[id]; child != nil && child.Status == types.StatusClosed {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// groupParallelSteps unions the steps at one blocking depth that do not block
|
||||
// each other and names every group of two or more. It answers the updated
|
||||
// group counter.
|
||||
func groupParallelSteps(analysis *MoleculeAnalysis, steps []string, blocks, blockedBy map[string]map[string]bool, counter int) int {
|
||||
if len(steps) == 0 {
|
||||
return counter
|
||||
}
|
||||
parent := make(map[string]string, len(steps))
|
||||
for _, id := range steps {
|
||||
parent[id] = id
|
||||
}
|
||||
find := func(x string) string {
|
||||
for parent[x] != x {
|
||||
parent[x] = parent[parent[x]]
|
||||
x = parent[x]
|
||||
}
|
||||
return x
|
||||
}
|
||||
for i, a := range steps {
|
||||
for _, b := range steps[i+1:] {
|
||||
if !blocks[a][b] && !blocks[b][a] && !blockedBy[a][b] && !blockedBy[b][a] {
|
||||
if pa, pb := find(a), find(b); pa != pb {
|
||||
parent[pa] = pb
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
groups := make(map[string][]string)
|
||||
var order []string
|
||||
for _, id := range steps {
|
||||
root := find(id)
|
||||
if _, ok := groups[root]; !ok {
|
||||
order = append(order, root)
|
||||
}
|
||||
groups[root] = append(groups[root], id)
|
||||
}
|
||||
for _, root := range order {
|
||||
members := groups[root]
|
||||
if len(members) < 2 {
|
||||
continue
|
||||
}
|
||||
counter++
|
||||
name := fmt.Sprintf("group-%d", counter)
|
||||
analysis.ParallelGroups[name] = members
|
||||
for _, id := range members {
|
||||
info := analysis.Steps[id]
|
||||
info.ParallelGroup = name
|
||||
for _, other := range members {
|
||||
if other != id {
|
||||
info.CanParallel = append(info.CanParallel, other)
|
||||
}
|
||||
}
|
||||
sort.Strings(info.CanParallel)
|
||||
}
|
||||
}
|
||||
return counter
|
||||
}
|
||||
|
||||
// blockingDepths answers each node's blocking depth: 0 with no open blocker,
|
||||
// one more than its deepest open blocker otherwise. A cycle counts as 0.
|
||||
func blockingDepths(g *MoleculeGraph, blockedBy map[string]map[string]bool) map[string]int {
|
||||
depths := make(map[string]int)
|
||||
visiting := make(map[string]bool)
|
||||
var depthOf func(id string) int
|
||||
depthOf = func(id string) int {
|
||||
if d, ok := depths[id]; ok {
|
||||
return d
|
||||
}
|
||||
if visiting[id] {
|
||||
return 0
|
||||
}
|
||||
visiting[id] = true
|
||||
deepest := -1
|
||||
for blockerID := range blockedBy[id] {
|
||||
if blocker := g.IssueMap[blockerID]; blocker != nil && blocker.Status != types.StatusClosed {
|
||||
deepest = max(deepest, depthOf(blockerID))
|
||||
}
|
||||
}
|
||||
depths[id] = deepest + 1
|
||||
return depths[id]
|
||||
}
|
||||
for _, issue := range g.Issues {
|
||||
depthOf(issue.ID)
|
||||
}
|
||||
return depths
|
||||
}
|
||||
|
||||
// Molecule step states, as MoleculeStep.State spells them.
|
||||
const (
|
||||
MoleculeStepDone = "done"
|
||||
MoleculeStepCurrent = "current"
|
||||
MoleculeStepReady = "ready"
|
||||
MoleculeStepBlocked = "blocked"
|
||||
MoleculeStepPending = "pending"
|
||||
)
|
||||
|
||||
// MoleculeStep is one step of a MoleculeView.
|
||||
type MoleculeStep struct {
|
||||
Issue *Issue
|
||||
// State is one of the MoleculeStep* constants: done (closed), current (in
|
||||
// progress), blocked (status blocked), ready (open, no open blocker inside
|
||||
// the molecule) or pending.
|
||||
State string
|
||||
IsCurrent bool
|
||||
}
|
||||
|
||||
// MoleculeView is where a molecule stands: every step's state, the progress
|
||||
// counts, the step in progress and the next ready one.
|
||||
type MoleculeView struct {
|
||||
Graph *MoleculeGraph
|
||||
Analysis *MoleculeAnalysis
|
||||
// Steps holds every step (the root excluded) ordered by how many blocking
|
||||
// edges inside the molecule each one waits on, fewest first, stable over
|
||||
// the graph's own order.
|
||||
Steps []*MoleculeStep
|
||||
// Completed counts the closed steps and Total every step.
|
||||
Completed int
|
||||
Total int
|
||||
// CurrentStep is the step in progress (the last one in graph order when
|
||||
// several are); NextStep the first ready step.
|
||||
CurrentStep *Issue
|
||||
NextStep *Issue
|
||||
// Ready holds every node the analysis marks ready (open or in progress
|
||||
// with no open blocker inside the molecule), root included, in graph
|
||||
// order: `bd ready --mol`'s list, hydrated rows (assignee and all).
|
||||
Ready []*Issue
|
||||
}
|
||||
|
||||
// Complete reports whether every step of the molecule is closed.
|
||||
func (v *MoleculeView) Complete() bool { return v.Completed >= v.Total }
|
||||
|
||||
// ViewMolecule loads the molecule rooted at rootID and derives its view.
|
||||
func ViewMolecule(ctx context.Context, r MoleculeReader, rootID string) (*MoleculeView, error) {
|
||||
g, err := LoadMolecule(ctx, r, rootID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return MoleculeViewOf(g), nil
|
||||
}
|
||||
|
||||
// MoleculeViewOf derives the view of an already loaded graph.
|
||||
func MoleculeViewOf(g *MoleculeGraph) *MoleculeView {
|
||||
analysis := AnalyzeMolecule(g)
|
||||
view := &MoleculeView{Graph: g, Analysis: analysis, Total: len(g.Issues) - 1}
|
||||
for _, issue := range g.Issues {
|
||||
if info := analysis.Steps[issue.ID]; info != nil && info.IsReady {
|
||||
view.Ready = append(view.Ready, issue)
|
||||
}
|
||||
if issue.ID == g.Root.ID {
|
||||
continue
|
||||
}
|
||||
step := &MoleculeStep{Issue: issue}
|
||||
switch issue.Status {
|
||||
case types.StatusClosed:
|
||||
step.State = MoleculeStepDone
|
||||
view.Completed++
|
||||
case types.StatusInProgress:
|
||||
step.State = MoleculeStepCurrent
|
||||
step.IsCurrent = true
|
||||
view.CurrentStep = issue
|
||||
case types.StatusBlocked:
|
||||
step.State = MoleculeStepBlocked
|
||||
default:
|
||||
if info := analysis.Steps[issue.ID]; info != nil && info.IsReady {
|
||||
step.State = MoleculeStepReady
|
||||
if view.NextStep == nil {
|
||||
view.NextStep = issue
|
||||
}
|
||||
} else {
|
||||
step.State = MoleculeStepPending
|
||||
}
|
||||
}
|
||||
view.Steps = append(view.Steps, step)
|
||||
}
|
||||
sortStepsByBlockers(view.Steps, g)
|
||||
return view
|
||||
}
|
||||
|
||||
// ReadySteps answers the steps whose state is ready, in view order.
|
||||
func (v *MoleculeView) ReadySteps() []*Issue {
|
||||
var out []*Issue
|
||||
for _, step := range v.Steps {
|
||||
if step.State == MoleculeStepReady {
|
||||
out = append(out, step.Issue)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func sortStepsByBlockers(steps []*MoleculeStep, g *MoleculeGraph) {
|
||||
inSteps := make(map[string]bool, len(steps))
|
||||
for _, step := range steps {
|
||||
inSteps[step.Issue.ID] = true
|
||||
}
|
||||
waits := make(map[string]int, len(steps))
|
||||
for _, dep := range g.Dependencies {
|
||||
if dep.Type == types.DepBlocks && inSteps[dep.IssueID] && inSteps[dep.DependsOnID] {
|
||||
waits[dep.IssueID]++
|
||||
}
|
||||
}
|
||||
sort.SliceStable(steps, func(i, j int) bool {
|
||||
return waits[steps[i].Issue.ID] < waits[steps[j].Issue.ID]
|
||||
})
|
||||
}
|
||||
|
||||
// MoleculeProgress is a molecule's progress counts over its DIRECT
|
||||
// parent-child steps.
|
||||
type MoleculeProgress = types.MoleculeProgressStats
|
||||
|
||||
// ReadMoleculeProgress counts the direct steps of the molecule rooted at
|
||||
// rootID without loading the whole graph. A root that names nothing is
|
||||
// ErrNotFound.
|
||||
func ReadMoleculeProgress(ctx context.Context, r MoleculeReader, rootID string) (*MoleculeProgress, error) {
|
||||
if !r.usable() {
|
||||
return nil, fmt.Errorf("%w: molecule reads need a reader", ErrValidation)
|
||||
}
|
||||
roots, err := getIssues(ctx, r, []string{rootID})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("loading molecule %s: %w", rootID, err)
|
||||
}
|
||||
root := roots[rootID]
|
||||
if root == nil {
|
||||
return nil, fmt.Errorf("%w: molecule %s", ErrNotFound, rootID)
|
||||
}
|
||||
children, err := r.Related(ctx, RelatedRequest{
|
||||
ID: rootID,
|
||||
Direction: RelationIn,
|
||||
Types: []types.DependencyType{types.DepParentChild},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reading the steps of %s: %w", rootID, err)
|
||||
}
|
||||
return MoleculeProgressOf(root, children), nil
|
||||
}
|
||||
|
||||
// MoleculeProgressOf folds a root's inbound parent-child neighbors into its
|
||||
// progress counts. CurrentStepID is the first in-progress step in the order
|
||||
// given.
|
||||
func MoleculeProgressOf(root *Issue, children []*RelatedIssue) *MoleculeProgress {
|
||||
stats := &MoleculeProgress{}
|
||||
if root != nil {
|
||||
stats.MoleculeID, stats.MoleculeTitle = root.ID, root.Title
|
||||
}
|
||||
for _, child := range children {
|
||||
if child == nil || child.DependencyType != types.DepParentChild {
|
||||
continue
|
||||
}
|
||||
stats.Total++
|
||||
switch child.Status {
|
||||
case types.StatusClosed:
|
||||
stats.Completed++
|
||||
case types.StatusInProgress:
|
||||
stats.InProgress++
|
||||
if stats.CurrentStepID == "" {
|
||||
stats.CurrentStepID = child.ID
|
||||
}
|
||||
}
|
||||
}
|
||||
return stats
|
||||
}
|
||||
|
||||
// CompletedMolecule answers the molecule root that closing stepID completed
|
||||
// and that closes itself when complete (AutoClosesWhenComplete): the root is
|
||||
// open and every step under it is closed. It answers nil when stepID belongs
|
||||
// to no molecule, when the root is already closed or does not auto-close, or
|
||||
// when a step is still open. It writes nothing; the caller closes the root,
|
||||
// guarded on the RowVersion of the root it answers.
|
||||
//
|
||||
// It is AutoClosingMoleculeRoots then MoleculeStepsClosed, so a step under an
|
||||
// ordinary epic, or under a root already closed, never reads the steps.
|
||||
func CompletedMolecule(ctx context.Context, r MoleculeReader, stepID string) (*Issue, error) {
|
||||
roots, err := AutoClosingMoleculeRoots(ctx, r, []string{stepID})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
root := roots[stepID]
|
||||
if root == nil {
|
||||
return nil, nil
|
||||
}
|
||||
complete, err := MoleculeStepsClosed(ctx, r, root.ID)
|
||||
if err != nil || !complete {
|
||||
return nil, err
|
||||
}
|
||||
return root, nil
|
||||
}
|
||||
|
||||
// AutoClosingMoleculeRoots answers, for each id whose molecule root is open
|
||||
// and closes itself when complete (AutoClosesWhenComplete), that root's row:
|
||||
// the roots a close of ids could complete. It is the parent walk and the root
|
||||
// rows MoleculeRoots reads, and nothing more — it never reads a molecule's
|
||||
// steps — so a caller deciding several closes reads each root once and walks
|
||||
// only the molecules that could auto-close.
|
||||
func AutoClosingMoleculeRoots(ctx context.Context, r MoleculeReader, ids []string) (map[string]*Issue, error) {
|
||||
rows, err := moleculeRootRows(ctx, r, ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for id, root := range rows {
|
||||
if root.Status == types.StatusClosed || !AutoClosesWhenComplete(root) {
|
||||
delete(rows, id)
|
||||
}
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// MoleculeStepsClosed reports whether every parent-child descendant of rootID
|
||||
// is closed — the steps LoadMolecule would load. It reads one level of steps
|
||||
// at a time and answers false at the first step that is not closed, so an
|
||||
// incomplete molecule costs the reads up to its first open step, not a load of
|
||||
// the whole tree. A root with no steps answers true; a parent-child cycle
|
||||
// terminates.
|
||||
func MoleculeStepsClosed(ctx context.Context, r MoleculeReader, rootID string) (bool, error) {
|
||||
if !r.usable() {
|
||||
return false, fmt.Errorf("%w: molecule reads need a reader", ErrValidation)
|
||||
}
|
||||
seen := map[string]bool{rootID: true}
|
||||
pending := []string{rootID}
|
||||
for len(pending) > 0 {
|
||||
parentID := pending[len(pending)-1]
|
||||
pending = pending[:len(pending)-1]
|
||||
children, err := r.Related(ctx, RelatedRequest{
|
||||
ID: parentID,
|
||||
Direction: RelationIn,
|
||||
Types: []types.DependencyType{types.DepParentChild},
|
||||
})
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("reading the steps of %s: %w", parentID, err)
|
||||
}
|
||||
for _, child := range children {
|
||||
if child == nil || child.DependencyType != types.DepParentChild || seen[child.ID] {
|
||||
continue
|
||||
}
|
||||
if child.Status != types.StatusClosed {
|
||||
return false, nil
|
||||
}
|
||||
seen[child.ID] = true
|
||||
pending = append(pending, child.ID)
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// MoleculeAutoCloseReason is the close reason a molecule root's auto-close
|
||||
// records.
|
||||
const MoleculeAutoCloseReason = "all steps complete"
|
||||
|
||||
// IsMoleculeAutoCloseRefusal reports whether err is a refusal of a completed
|
||||
// molecule's root close — an outcome that leaves the root open without failing
|
||||
// the step close that completed it: the close policy (a live blocker,
|
||||
// ErrCloseBlocked; open children, *CloseOpenChildrenError) or a close guard (a
|
||||
// template root, *TemplateReadOnlyError; a pinned root, *PinnedError; a root
|
||||
// assigned to someone else, *CloseNotAssigneeError). The root close is
|
||||
// unforced (MoleculeRootClose), so every guard holds for it exactly as it does
|
||||
// for a direct close of the root. A guard only reads, before the close writes
|
||||
// anything, and a policy refusal rolls back to the close's savepoint, so a
|
||||
// refusal leaves the step close's transaction as it found it.
|
||||
//
|
||||
// ErrVersionMismatch on the root is NOT a refusal: should a backend's check
|
||||
// ever see a revision its read did not, it fails the step's close
|
||||
// (CloseRequest.AutoCloseMolecule). A write to the root that races the close
|
||||
// does not produce it (MoleculeRootClose).
|
||||
func IsMoleculeAutoCloseRefusal(err error) bool {
|
||||
var (
|
||||
openChildren *CloseOpenChildrenError
|
||||
template *TemplateReadOnlyError
|
||||
pinned *PinnedError
|
||||
notAssignee *CloseNotAssigneeError
|
||||
)
|
||||
return errors.Is(err, ErrCloseBlocked) ||
|
||||
errors.As(err, &openChildren) ||
|
||||
errors.As(err, &template) ||
|
||||
errors.As(err, &pinned) ||
|
||||
errors.As(err, ¬Assignee)
|
||||
}
|
||||
|
||||
// MoleculeRootClose is the ONE close request a molecule auto-close sends for a
|
||||
// root it found complete (AutoClosingMoleculeRoots, then MoleculeStepsClosed,
|
||||
// read in the transaction that closes it): unforced, recording
|
||||
// MoleculeAutoCloseReason and the step close's session, and guarded on the
|
||||
// RowVersion of root as that read answered it. Every backend's
|
||||
// in-transaction auto-close (CloseRequest.AutoCloseMolecule) builds its root
|
||||
// close from it.
|
||||
//
|
||||
// The guard covers the root row's lifecycle state and nothing else (the
|
||||
// version family's rule: it guards a row's lifecycle state, not its graph).
|
||||
// Every backend reads the root and checks its revision in one transaction
|
||||
// snapshot, so a status, assignee or started_at write that another
|
||||
// transaction commits to the root after the read does not trip the guard. It
|
||||
// conflicts with the root close at commit instead, and the backend's retry
|
||||
// re-reads the root and decides again (a root another actor now holds is a
|
||||
// refusal, and the step's close stands); only a close still conflicting when
|
||||
// its retry budget runs out fails, with the serialization error. The guard
|
||||
// does not cover the steps: reopening a step writes no root row, so a reopen
|
||||
// that races the auto-close is not detected, and the root can close over the
|
||||
// reopened step.
|
||||
func MoleculeRootClose(root *Issue, actor, session string) CloseRequest {
|
||||
version := root.RowVersion
|
||||
return CloseRequest{
|
||||
Actor: actor,
|
||||
IssueID: root.ID,
|
||||
Reason: MoleculeAutoCloseReason,
|
||||
Session: session,
|
||||
ExpectedVersion: &version,
|
||||
}
|
||||
}
|
||||
141
issueops/molecule_active.go
Normal file
141
issueops/molecule_active.go
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
package issueops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
// InProgressMoleculeIDs answers the molecules with a step in progress for
|
||||
// agent (every agent when agent is empty), each once, in the order the
|
||||
// listing first reached a step of it.
|
||||
//
|
||||
// The listing is Reader.List over every plane and class a step can live in —
|
||||
// templates, gates, infra and ephemeral rows, the four knobs rather than
|
||||
// IncludeAllTypes, because the v0 wire publishes each knob and refuses the
|
||||
// union. A read the backend refuses is returned, never answered as "none".
|
||||
func InProgressMoleculeIDs(ctx context.Context, reader Reader, r MoleculeReader, agent string) ([]string, error) {
|
||||
steps, err := listMoleculeCandidates(ctx, reader, types.StatusInProgress, agent)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(steps) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
ids := make([]string, len(steps))
|
||||
for i, step := range steps {
|
||||
ids[i] = step.ID
|
||||
}
|
||||
roots, err := MoleculeRoots(ctx, r, ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
var out []string
|
||||
for _, id := range ids {
|
||||
if root := roots[id]; root != "" && !seen[root] {
|
||||
seen[root] = true
|
||||
out = append(out, root)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ActiveMoleculeIDs answers the molecules agent is working on, sorted: the
|
||||
// ones with a step in progress or, when there are none, the ones its HOOKED
|
||||
// work is attached to — a hooked epic itself, or an epic or template the
|
||||
// hooked issue is blocked by.
|
||||
func ActiveMoleculeIDs(ctx context.Context, reader Reader, r MoleculeReader, agent string) ([]string, error) {
|
||||
ids, err := InProgressMoleculeIDs(ctx, reader, r, agent)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("finding molecules in progress: %w", err)
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
ids, err = hookedMoleculeIDs(ctx, reader, r, agent)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("finding hooked molecules: %w", err)
|
||||
}
|
||||
}
|
||||
sort.Strings(ids)
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
func hookedMoleculeIDs(ctx context.Context, reader Reader, r MoleculeReader, agent string) ([]string, error) {
|
||||
hooked, err := listMoleculeCandidates(ctx, reader, types.StatusHooked, agent)
|
||||
if err != nil || len(hooked) == 0 {
|
||||
return nil, err
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
var out []string
|
||||
add := func(id string) {
|
||||
if !seen[id] {
|
||||
seen[id] = true
|
||||
out = append(out, id)
|
||||
}
|
||||
}
|
||||
var attached []string
|
||||
for _, issue := range hooked {
|
||||
// A hooked epic IS the molecule (a patrol wisp hooked without a
|
||||
// separate handoff bead).
|
||||
if issue.IssueType == types.TypeEpic {
|
||||
add(issue.ID)
|
||||
continue
|
||||
}
|
||||
attached = append(attached, issue.ID)
|
||||
}
|
||||
if len(attached) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
edges, err := r.ReadEdges(ctx, EdgeReadRequest{IDs: attached, Types: []types.DependencyType{types.DepBlocks}})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reading the blockers of hooked work: %w", err)
|
||||
}
|
||||
var blockers []string
|
||||
for _, anchor := range edges.Anchors {
|
||||
for _, edge := range anchor.Edges {
|
||||
if edge != nil && edge.Type == types.DepBlocks {
|
||||
blockers = append(blockers, edge.DependsOnID)
|
||||
}
|
||||
}
|
||||
}
|
||||
candidates, err := getIssues(ctx, r, blockers)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, id := range blockers {
|
||||
// An external or dangling blocker names nothing to load.
|
||||
if candidate := candidates[id]; candidate != nil &&
|
||||
(candidate.IssueType == types.TypeEpic || hasLabel(candidate, MoleculeTemplateLabel)) {
|
||||
add(id)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func listMoleculeCandidates(ctx context.Context, reader Reader, status types.Status, agent string) ([]*Issue, error) {
|
||||
if reader == nil {
|
||||
return nil, fmt.Errorf("%w: listing molecule work needs a reader", ErrValidation)
|
||||
}
|
||||
unlimited := 0
|
||||
page, err := reader.List(ctx, ListRequest{
|
||||
Status: string(status),
|
||||
Assignee: agent,
|
||||
IncludeTemplates: true,
|
||||
IncludeGates: true,
|
||||
IncludeInfra: true,
|
||||
IncludeEphemeral: true,
|
||||
Limit: &unlimited,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]*Issue, 0, len(page.Items))
|
||||
for _, row := range page.Items {
|
||||
if row != nil && row.Issue != nil {
|
||||
out = append(out, row.Issue)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
40
issueops/molecule_internal_test.go
Normal file
40
issueops/molecule_internal_test.go
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
package issueops
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
// TestBlockingDepths pins the depth rule the parallel grouping keys on: 0 with
|
||||
// no open blocker, one more than the deepest open blocker otherwise.
|
||||
func TestBlockingDepths(t *testing.T) {
|
||||
root := &types.Issue{ID: "root", Status: types.StatusOpen}
|
||||
step1 := &types.Issue{ID: "step1", Status: types.StatusOpen}
|
||||
step2 := &types.Issue{ID: "step2", Status: types.StatusOpen}
|
||||
step3 := &types.Issue{ID: "step3", Status: types.StatusOpen}
|
||||
g := &MoleculeGraph{
|
||||
Root: root,
|
||||
Issues: []*types.Issue{root, step1, step2, step3},
|
||||
IssueMap: map[string]*types.Issue{"root": root, "step1": step1, "step2": step2, "step3": step3},
|
||||
}
|
||||
blockedBy := map[string]map[string]bool{
|
||||
"root": {},
|
||||
"step1": {"root": true},
|
||||
"step2": {"step1": true},
|
||||
"step3": {"step2": true},
|
||||
}
|
||||
depths := blockingDepths(g, blockedBy)
|
||||
for id, want := range map[string]int{"root": 0, "step1": 1, "step2": 2, "step3": 3} {
|
||||
if depths[id] != want {
|
||||
t.Errorf("%s depth = %d, want %d", id, depths[id], want)
|
||||
}
|
||||
}
|
||||
|
||||
// A closed blocker no longer deepens what it blocked.
|
||||
step1.Status = types.StatusClosed
|
||||
depths = blockingDepths(g, blockedBy)
|
||||
if depths["step2"] != 0 {
|
||||
t.Errorf("step2 depth with its blocker closed = %d, want 0", depths["step2"])
|
||||
}
|
||||
}
|
||||
595
issueops/molecule_test.go
Normal file
595
issueops/molecule_test.go
Normal file
|
|
@ -0,0 +1,595 @@
|
|||
package issueops_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"sort"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// fakeMolecules is an in-memory MoleculeReader, Reader (List), Claimer and
|
||||
// Lifecycle (Update with Claim, Close) — just enough store for the molecule
|
||||
// rules, so each rule is pinned without a database.
|
||||
type fakeMolecules struct {
|
||||
issueops.Reader
|
||||
issueops.Lifecycle
|
||||
issues map[string]*types.Issue
|
||||
deps []*types.Dependency
|
||||
|
||||
edgeErr error
|
||||
listErr error
|
||||
relatedErr error
|
||||
// related records every Related read, by id, in order.
|
||||
related []string
|
||||
// claimErrs answers a claim of the keyed id with that error.
|
||||
claimErrs map[string]error
|
||||
claimed []string
|
||||
updated []string
|
||||
closes []issueops.CloseRequest
|
||||
closeErr error
|
||||
}
|
||||
|
||||
func newFakeMolecules() *fakeMolecules {
|
||||
return &fakeMolecules{issues: map[string]*types.Issue{}, claimErrs: map[string]error{}}
|
||||
}
|
||||
|
||||
func (f *fakeMolecules) add(id string, typ types.IssueType, status types.Status, labels ...string) *types.Issue {
|
||||
issue := &types.Issue{ID: id, Title: "title " + id, IssueType: typ, Status: status, Labels: labels, RowVersion: int64(len(id) * 7)}
|
||||
f.issues[id] = issue
|
||||
return issue
|
||||
}
|
||||
|
||||
func (f *fakeMolecules) edge(from, to string, typ types.DependencyType) {
|
||||
f.deps = append(f.deps, &types.Dependency{IssueID: from, DependsOnID: to, Type: typ})
|
||||
}
|
||||
|
||||
func (f *fakeMolecules) GetMany(_ context.Context, req issueops.GetManyRequest) (issueops.GetManyResult, error) {
|
||||
out := issueops.GetManyResult{Issues: []*issueops.Issue{}, Missing: []string{}}
|
||||
for _, id := range req.IDs {
|
||||
if issue := f.issues[id]; issue != nil {
|
||||
clone := *issue
|
||||
out.Issues = append(out.Issues, &clone)
|
||||
} else {
|
||||
out.Missing = append(out.Missing, id)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (f *fakeMolecules) Related(_ context.Context, req issueops.RelatedRequest) ([]*issueops.RelatedIssue, error) {
|
||||
f.related = append(f.related, req.ID)
|
||||
if f.relatedErr != nil {
|
||||
return nil, f.relatedErr
|
||||
}
|
||||
if f.issues[req.ID] == nil {
|
||||
return nil, fmt.Errorf("%w: %s", issueops.ErrNotFound, req.ID)
|
||||
}
|
||||
var out []*issueops.RelatedIssue
|
||||
for _, dep := range f.deps {
|
||||
if dep.DependsOnID != req.ID || (len(req.Types) > 0 && !slices.Contains(req.Types, dep.Type)) {
|
||||
continue
|
||||
}
|
||||
if issue := f.issues[dep.IssueID]; issue != nil {
|
||||
out = append(out, &issueops.RelatedIssue{Issue: *issue, DependencyType: dep.Type})
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (f *fakeMolecules) ReadEdges(_ context.Context, req issueops.EdgeReadRequest) (issueops.EdgeReadResult, error) {
|
||||
if f.edgeErr != nil {
|
||||
return issueops.EdgeReadResult{}, f.edgeErr
|
||||
}
|
||||
var out issueops.EdgeReadResult
|
||||
for _, id := range req.IDs {
|
||||
anchor := issueops.AnchorEdges{ID: id, Missing: f.issues[id] == nil}
|
||||
for _, dep := range f.deps {
|
||||
if dep.IssueID == id && (len(req.Types) == 0 || slices.Contains(req.Types, dep.Type)) {
|
||||
anchor.Edges = append(anchor.Edges, dep)
|
||||
}
|
||||
}
|
||||
out.Anchors = append(out.Anchors, anchor)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (f *fakeMolecules) List(_ context.Context, req issueops.ListRequest) (issueops.IssuePage, error) {
|
||||
if f.listErr != nil {
|
||||
return issueops.IssuePage{}, f.listErr
|
||||
}
|
||||
var page issueops.IssuePage
|
||||
for _, issue := range f.issues {
|
||||
if string(issue.Status) == req.Status && (req.Assignee == "" || issue.Assignee == req.Assignee) {
|
||||
page.Items = append(page.Items, &types.IssueWithCounts{Issue: issue})
|
||||
}
|
||||
}
|
||||
sort.Slice(page.Items, func(i, j int) bool { return page.Items[i].ID < page.Items[j].ID })
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func (f *fakeMolecules) take(id, actor string) (*types.Issue, error) {
|
||||
if err := f.claimErrs[id]; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
issue := f.issues[id]
|
||||
issue.Status, issue.Assignee = types.StatusInProgress, actor
|
||||
clone := *issue
|
||||
clone.Labels = nil
|
||||
return &clone, nil
|
||||
}
|
||||
|
||||
func (f *fakeMolecules) Claim(_ context.Context, req issueops.ClaimRequest) (issueops.ClaimResult, error) {
|
||||
issue, err := f.take(req.IssueID, req.Actor)
|
||||
if err != nil {
|
||||
return issueops.ClaimResult{}, err
|
||||
}
|
||||
f.claimed = append(f.claimed, req.IssueID)
|
||||
return issueops.ClaimResult{Issue: issue, Changed: true}, nil
|
||||
}
|
||||
|
||||
func (f *fakeMolecules) Update(_ context.Context, req issueops.UpdateRequest) (issueops.UpdateResult, error) {
|
||||
if !req.Claim {
|
||||
return issueops.UpdateResult{}, errors.New("fake: only claims")
|
||||
}
|
||||
issue, err := f.take(req.IssueID, req.Actor)
|
||||
if err != nil {
|
||||
return issueops.UpdateResult{}, err
|
||||
}
|
||||
f.updated = append(f.updated, req.IssueID)
|
||||
return issueops.UpdateResult{Issue: issue, Changed: true}, nil
|
||||
}
|
||||
|
||||
func (f *fakeMolecules) Close(_ context.Context, req issueops.CloseRequest) (issueops.CloseResult, error) {
|
||||
f.closes = append(f.closes, req)
|
||||
if f.closeErr != nil {
|
||||
return issueops.CloseResult{}, f.closeErr
|
||||
}
|
||||
issue := f.issues[req.IssueID]
|
||||
if req.ExpectedVersion != nil && *req.ExpectedVersion != issue.RowVersion {
|
||||
return issueops.CloseResult{}, issueops.ErrVersionMismatch
|
||||
}
|
||||
issue.Status = types.StatusClosed
|
||||
clone := *issue
|
||||
return issueops.CloseResult{Issue: &clone, Changed: true}, nil
|
||||
}
|
||||
|
||||
func (f *fakeMolecules) reader() issueops.MoleculeReader { return issueops.MoleculeReaderOver(f) }
|
||||
|
||||
func (f *fakeMolecules) stepper() issueops.MoleculeStepper {
|
||||
return issueops.NewMoleculeStepper(issueops.MoleculeStepperRoles{Reader: f.reader(), Claimer: f, Lifecycle: f})
|
||||
}
|
||||
|
||||
// A molecule: root (molecule type) <- a, b, c; c blocked by b; b blocked by a.
|
||||
func seedChain(f *fakeMolecules) {
|
||||
f.add("m", types.TypeMolecule, types.StatusOpen)
|
||||
f.add("m.a", types.TypeTask, types.StatusClosed)
|
||||
f.add("m.b", types.TypeTask, types.StatusOpen)
|
||||
f.add("m.c", types.TypeTask, types.StatusOpen)
|
||||
for _, id := range []string{"m.a", "m.b", "m.c"} {
|
||||
f.edge(id, "m", types.DepParentChild)
|
||||
}
|
||||
f.edge("m.b", "m.a", types.DepBlocks)
|
||||
f.edge("m.c", "m.b", types.DepBlocks)
|
||||
}
|
||||
|
||||
func TestMoleculeRootsWalksToTheTopmostMoleculeRoot(t *testing.T) {
|
||||
f := newFakeMolecules()
|
||||
f.add("root", types.TypeEpic, types.StatusOpen)
|
||||
f.add("child", types.TypeTask, types.StatusOpen)
|
||||
f.add("grandchild", types.TypeTask, types.StatusOpen)
|
||||
f.add("orphan", types.TypeTask, types.StatusOpen)
|
||||
f.add("plain", types.TypeTask, types.StatusOpen)
|
||||
f.add("plainkid", types.TypeTask, types.StatusOpen)
|
||||
f.add("tmpl", types.TypeTask, types.StatusOpen, issueops.MoleculeTemplateLabel)
|
||||
f.add("tmplkid", types.TypeTask, types.StatusOpen)
|
||||
f.edge("child", "root", types.DepParentChild)
|
||||
f.edge("grandchild", "child", types.DepParentChild)
|
||||
f.edge("plainkid", "plain", types.DepParentChild)
|
||||
f.edge("tmplkid", "tmpl", types.DepParentChild)
|
||||
|
||||
roots, err := issueops.MoleculeRoots(context.Background(), f.reader(), []string{"grandchild", "child", "root", "orphan", "plainkid", "tmplkid", "absent"})
|
||||
if err != nil {
|
||||
t.Fatalf("MoleculeRoots: %v", err)
|
||||
}
|
||||
want := map[string]string{"grandchild": "root", "child": "root", "root": "root", "tmplkid": "tmpl"}
|
||||
if len(roots) != len(want) {
|
||||
t.Fatalf("MoleculeRoots = %v, want %v", roots, want)
|
||||
}
|
||||
for id, root := range want {
|
||||
if roots[id] != root {
|
||||
t.Errorf("MoleculeRoots[%s] = %q, want %q", id, roots[id], root)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Every read the rules make RETURNS a refusal. Answering "not in a molecule"
|
||||
// or "no molecules" for a read that never happened is how `bd mol current`
|
||||
// went silently empty and a molecule root was stranded open.
|
||||
func TestMoleculeReadsReturnRefusals(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
refusal := errors.New("refused")
|
||||
|
||||
f := newFakeMolecules()
|
||||
seedChain(f)
|
||||
f.edgeErr = refusal
|
||||
if _, err := issueops.MoleculeRoots(ctx, f.reader(), []string{"m.b"}); !errors.Is(err, refusal) {
|
||||
t.Errorf("MoleculeRoots with a refused edge read = %v, want the refusal", err)
|
||||
}
|
||||
if _, err := issueops.CompletedMolecule(ctx, f.reader(), "m.b"); !errors.Is(err, refusal) {
|
||||
t.Errorf("CompletedMolecule with a refused edge read = %v, want the refusal", err)
|
||||
}
|
||||
|
||||
f = newFakeMolecules()
|
||||
seedChain(f)
|
||||
f.relatedErr = refusal
|
||||
if _, err := issueops.ViewMolecule(ctx, f.reader(), "m"); !errors.Is(err, refusal) {
|
||||
t.Errorf("ViewMolecule with a refused relations read = %v, want the refusal", err)
|
||||
}
|
||||
if _, err := issueops.ReadMoleculeProgress(ctx, f.reader(), "m"); !errors.Is(err, refusal) {
|
||||
t.Errorf("ReadMoleculeProgress with a refused relations read = %v, want the refusal", err)
|
||||
}
|
||||
|
||||
f = newFakeMolecules()
|
||||
f.listErr = refusal
|
||||
if _, err := issueops.ActiveMoleculeIDs(ctx, f, f.reader(), "alice"); !errors.Is(err, refusal) {
|
||||
t.Errorf("ActiveMoleculeIDs with a refused listing = %v, want the refusal", err)
|
||||
}
|
||||
if _, err := issueops.InProgressMoleculeIDs(ctx, f, f.reader(), "alice"); !errors.Is(err, refusal) {
|
||||
t.Errorf("InProgressMoleculeIDs with a refused listing = %v, want the refusal", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMoleculeViewDerivesStatesProgressAndTheNextStep(t *testing.T) {
|
||||
f := newFakeMolecules()
|
||||
seedChain(f)
|
||||
f.add("m.d", types.TypeTask, types.StatusInProgress)
|
||||
f.edge("m.d", "m", types.DepParentChild)
|
||||
f.issues["m.d"].Assignee = "alice"
|
||||
|
||||
view, err := issueops.ViewMolecule(context.Background(), f.reader(), "m")
|
||||
if err != nil {
|
||||
t.Fatalf("ViewMolecule: %v", err)
|
||||
}
|
||||
if view.Total != 4 || view.Completed != 1 || view.Complete() {
|
||||
t.Errorf("progress = %d/%d complete=%v, want 1/4 incomplete", view.Completed, view.Total, view.Complete())
|
||||
}
|
||||
states := map[string]string{}
|
||||
for _, step := range view.Steps {
|
||||
states[step.Issue.ID] = step.State
|
||||
}
|
||||
want := map[string]string{"m.a": "done", "m.b": "ready", "m.c": "pending", "m.d": "current"}
|
||||
for id, state := range want {
|
||||
if states[id] != state {
|
||||
t.Errorf("state[%s] = %q, want %q", id, states[id], state)
|
||||
}
|
||||
}
|
||||
if view.CurrentStep == nil || view.CurrentStep.ID != "m.d" || view.CurrentStep.Assignee != "alice" {
|
||||
t.Errorf("CurrentStep = %+v, want m.d assigned to alice (the full step row)", view.CurrentStep)
|
||||
}
|
||||
if view.NextStep == nil || view.NextStep.ID != "m.b" {
|
||||
t.Errorf("NextStep = %+v, want m.b", view.NextStep)
|
||||
}
|
||||
// Ready is ready --mol's list: every analysis-ready node, hydrated.
|
||||
ready := map[string]*issueops.Issue{}
|
||||
for _, issue := range view.Ready {
|
||||
ready[issue.ID] = issue
|
||||
}
|
||||
if ready["m.b"] == nil || ready["m.d"] == nil || ready["m.a"] != nil || ready["m.c"] != nil {
|
||||
t.Errorf("Ready = %v, want m.b and m.d, never the closed m.a or the blocked m.c", view.Ready)
|
||||
}
|
||||
if d := ready["m.d"]; d != nil && d.Assignee != "alice" {
|
||||
t.Errorf("Ready m.d assignee = %q, want alice (the full step row)", d.Assignee)
|
||||
}
|
||||
// Ordered by in-molecule blockers, fewest first: m.c waits on one step.
|
||||
if last := view.Steps[len(view.Steps)-1].Issue.ID; last != "m.c" && last != "m.b" {
|
||||
t.Errorf("last step = %s, want a step that waits on a blocker", last)
|
||||
}
|
||||
progress, err := issueops.ReadMoleculeProgress(context.Background(), f.reader(), "m")
|
||||
if err != nil {
|
||||
t.Fatalf("ReadMoleculeProgress: %v", err)
|
||||
}
|
||||
if progress.Total != 4 || progress.Completed != 1 || progress.InProgress != 1 || progress.CurrentStepID != "m.d" {
|
||||
t.Errorf("progress = %+v, want 4 total, 1 completed, 1 in progress (m.d)", progress)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompletedMoleculeAnswersOnlyAnOpenCompleteAutoClosingRoot(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
rootType types.IssueType
|
||||
labels []string
|
||||
closeAll bool
|
||||
want bool
|
||||
}{
|
||||
{"molecule root, all steps closed", types.TypeMolecule, nil, true, true},
|
||||
{"template epic, all steps closed", types.TypeEpic, []string{issueops.MoleculeTemplateLabel}, true, true},
|
||||
{"plain epic stays open for explicit close", types.TypeEpic, nil, true, false},
|
||||
{"a step still open", types.TypeMolecule, nil, false, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := newFakeMolecules()
|
||||
f.add("r", tc.rootType, types.StatusOpen, tc.labels...)
|
||||
f.add("r.1", types.TypeTask, types.StatusClosed)
|
||||
status := types.StatusOpen
|
||||
if tc.closeAll {
|
||||
status = types.StatusClosed
|
||||
}
|
||||
f.add("r.2", types.TypeTask, status)
|
||||
f.edge("r.1", "r", types.DepParentChild)
|
||||
f.edge("r.2", "r", types.DepParentChild)
|
||||
root, err := issueops.CompletedMolecule(ctx, f.reader(), "r.1")
|
||||
if err != nil {
|
||||
t.Fatalf("CompletedMolecule: %v", err)
|
||||
}
|
||||
if (root != nil) != tc.want {
|
||||
t.Fatalf("CompletedMolecule = %v, want completed=%v", root, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
f := newFakeMolecules()
|
||||
f.add("orphan", types.TypeTask, types.StatusClosed)
|
||||
if root, err := issueops.CompletedMolecule(ctx, f.reader(), "orphan"); err != nil || root != nil {
|
||||
t.Errorf("CompletedMolecule(orphan) = %v, %v, want nil, nil", root, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A close under a root that cannot auto-close — an ordinary epic, a root
|
||||
// already closed — reads no steps at all, and an eligible root's steps are read
|
||||
// only up to the first open one.
|
||||
func TestCompletedMoleculeReadsOnlyTheStepsItMust(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
rootType types.IssueType
|
||||
status types.Status
|
||||
}{
|
||||
{"ordinary epic", types.TypeEpic, types.StatusOpen},
|
||||
{"closed molecule root", types.TypeMolecule, types.StatusClosed},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := newFakeMolecules()
|
||||
f.add("r", tc.rootType, tc.status)
|
||||
for _, id := range []string{"r.1", "r.2"} {
|
||||
f.add(id, types.TypeTask, types.StatusClosed)
|
||||
f.edge(id, "r", types.DepParentChild)
|
||||
}
|
||||
root, err := issueops.CompletedMolecule(ctx, f.reader(), "r.1")
|
||||
if err != nil || root != nil {
|
||||
t.Fatalf("CompletedMolecule = %v, %v, want nil, nil", root, err)
|
||||
}
|
||||
if len(f.related) != 0 {
|
||||
t.Errorf("steps read %v, want none: this root never auto-closes", f.related)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// r.1 is open; r.2 and r.3 are closed and have steps of their own. The
|
||||
// walk answers at r.1 without reading below r.2 or r.3.
|
||||
f := newFakeMolecules()
|
||||
f.add("r", types.TypeMolecule, types.StatusOpen)
|
||||
f.add("r.1", types.TypeTask, types.StatusOpen)
|
||||
f.edge("r.1", "r", types.DepParentChild)
|
||||
for _, id := range []string{"r.2", "r.3"} {
|
||||
f.add(id, types.TypeTask, types.StatusClosed)
|
||||
f.edge(id, "r", types.DepParentChild)
|
||||
f.add(id+".1", types.TypeTask, types.StatusClosed)
|
||||
f.edge(id+".1", id, types.DepParentChild)
|
||||
}
|
||||
root, err := issueops.CompletedMolecule(ctx, f.reader(), "r.2")
|
||||
if err != nil || root != nil {
|
||||
t.Fatalf("CompletedMolecule = %v, %v, want nil, nil (r.1 is open)", root, err)
|
||||
}
|
||||
if !slices.Equal(f.related, []string{"r"}) {
|
||||
t.Errorf("steps read %v, want only r's: r.1 is open, so nothing below r is read", f.related)
|
||||
}
|
||||
}
|
||||
|
||||
// MoleculeStepsClosed covers every descendant, not just the direct steps, and a
|
||||
// parent-child cycle terminates.
|
||||
func TestMoleculeStepsClosedCoversEveryDescendant(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
f := newFakeMolecules()
|
||||
f.add("r", types.TypeMolecule, types.StatusOpen)
|
||||
f.add("r.1", types.TypeTask, types.StatusClosed)
|
||||
f.edge("r.1", "r", types.DepParentChild)
|
||||
f.add("r.1.1", types.TypeTask, types.StatusOpen)
|
||||
f.edge("r.1.1", "r.1", types.DepParentChild)
|
||||
if closed, err := issueops.MoleculeStepsClosed(ctx, f.reader(), "r"); err != nil || closed {
|
||||
t.Errorf("MoleculeStepsClosed with r.1.1 open = %v, %v, want false", closed, err)
|
||||
}
|
||||
|
||||
f.issues["r.1.1"].Status = types.StatusClosed
|
||||
f.edge("r", "r.1.1", types.DepParentChild) // a cycle back to the root
|
||||
f.related = nil
|
||||
if closed, err := issueops.MoleculeStepsClosed(ctx, f.reader(), "r"); err != nil || !closed {
|
||||
t.Errorf("MoleculeStepsClosed with every step closed = %v, %v, want true", closed, err)
|
||||
}
|
||||
if len(f.related) != 3 {
|
||||
t.Errorf("steps read %v, want r, r.1 and r.1.1 once each", f.related)
|
||||
}
|
||||
|
||||
f.relatedErr = errors.New("refused")
|
||||
if _, err := issueops.MoleculeStepsClosed(ctx, f.reader(), "r"); !errors.Is(err, f.relatedErr) {
|
||||
t.Errorf("MoleculeStepsClosed with a refused read = %v, want the refusal", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The root close's refusals that leave the step's close standing are the close
|
||||
// policy and the close guards; a lost race on the root's revision is not one.
|
||||
func TestIsMoleculeAutoCloseRefusalIsPolicyAndGuardsNeverAVersionRace(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
err error
|
||||
want bool
|
||||
}{
|
||||
{"live blocker", &issueops.BlockedError{IssueID: "r", Blockers: []issueops.Blocker{{ID: "b"}}, Err: issueops.ErrCloseBlocked}, true},
|
||||
{"open children", &issueops.CloseOpenChildrenError{IssueID: "r", OpenChildren: 1}, true},
|
||||
{"template root", &issueops.TemplateReadOnlyError{IssueID: "r"}, true},
|
||||
{"pinned root", &issueops.PinnedError{IssueID: "r"}, true},
|
||||
{"root assigned to someone else", &issueops.CloseNotAssigneeError{IssueID: "r", Assignee: "bob", Actor: "alice"}, true},
|
||||
{"wrapped guard", fmt.Errorf("close r: %w", &issueops.CloseNotAssigneeError{IssueID: "r", Assignee: "bob", Actor: "alice"}), true},
|
||||
{"lost race on the root revision", issueops.ErrVersionMismatch, false},
|
||||
{"typed lost race", &issueops.VersionMismatchError{Expected: 1, Current: 2}, false},
|
||||
{"wrapped lost race", fmt.Errorf("close r: %w", &issueops.VersionMismatchError{Expected: 1, Current: 2}), false},
|
||||
{"storage failure", errors.New("connection reset"), false},
|
||||
{"no error", nil, false},
|
||||
} {
|
||||
if got := issueops.IsMoleculeAutoCloseRefusal(tc.err); got != tc.want {
|
||||
t.Errorf("%s: IsMoleculeAutoCloseRefusal(%v) = %v, want %v", tc.name, tc.err, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMoleculeRootCloseIsUnforcedAndGuardedOnTheRootRevision(t *testing.T) {
|
||||
root := &issueops.Issue{ID: "r", RowVersion: 41}
|
||||
got := issueops.MoleculeRootClose(root, "alice", "sess")
|
||||
if got.ExpectedVersion == nil || *got.ExpectedVersion != 41 || got.Force {
|
||||
t.Errorf("root close = %+v, want unforced and guarded on the root revision 41", got)
|
||||
}
|
||||
if got.IssueID != "r" || got.Reason != issueops.MoleculeAutoCloseReason || got.Session != "sess" || got.Actor != "alice" {
|
||||
t.Errorf("root close = %+v, want root r, the auto-close reason, the session and the actor", got)
|
||||
}
|
||||
root.RowVersion = 42
|
||||
if *got.ExpectedVersion != 41 {
|
||||
t.Error("the guard aliases the root's revision; it must be the revision read")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMoleculeStepperClaimsTheNextReadyStepForTheActor(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
f := newFakeMolecules()
|
||||
seedChain(f)
|
||||
|
||||
// Without AutoClaim nothing is written.
|
||||
res, err := f.stepper().Advance(ctx, issueops.AdvanceRequest{Actor: "alice", ClosedStepID: "m.a"})
|
||||
if err != nil {
|
||||
t.Fatalf("Advance: %v", err)
|
||||
}
|
||||
if res.MoleculeID != "m" || res.Claimed || res.NextStep == nil || res.NextStep.ID != "m.b" || len(f.claimed) != 0 {
|
||||
t.Fatalf("Advance without a claim = %+v (claimed %v), want next m.b and no claim", res, f.claimed)
|
||||
}
|
||||
|
||||
res, err = f.stepper().Advance(ctx, issueops.AdvanceRequest{Actor: "alice", ClosedStepID: "m.a", AutoClaim: true})
|
||||
if err != nil {
|
||||
t.Fatalf("Advance: %v", err)
|
||||
}
|
||||
if !res.Claimed || res.NextStep == nil || res.NextStep.ID != "m.b" || res.NextStep.Assignee != "alice" ||
|
||||
res.NextStep.Status != types.StatusInProgress {
|
||||
t.Fatalf("Advance = %+v, want m.b claimed for alice", res)
|
||||
}
|
||||
if !slices.Equal(f.claimed, []string{"m.b"}) || len(f.updated) != 0 {
|
||||
t.Errorf("claims = %v / updates = %v, want one Claimer claim of m.b", f.claimed, f.updated)
|
||||
}
|
||||
}
|
||||
|
||||
// A ready step another actor holds is skipped, never taken; any other claim
|
||||
// failure is returned rather than read as a lost race.
|
||||
func TestMoleculeStepperSkipsAHeldStepAndReturnsOtherFailures(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
f := newFakeMolecules()
|
||||
f.add("m", types.TypeMolecule, types.StatusOpen)
|
||||
for _, id := range []string{"m.1", "m.2"} {
|
||||
f.add(id, types.TypeTask, types.StatusOpen)
|
||||
f.edge(id, "m", types.DepParentChild)
|
||||
}
|
||||
f.add("m.0", types.TypeTask, types.StatusClosed)
|
||||
f.edge("m.0", "m", types.DepParentChild)
|
||||
f.claimErrs["m.1"] = &issueops.ClaimConflictError{Err: issueops.ErrAlreadyClaimed}
|
||||
|
||||
res, err := f.stepper().Advance(ctx, issueops.AdvanceRequest{Actor: "alice", ClosedStepID: "m.0", AutoClaim: true})
|
||||
if err != nil {
|
||||
t.Fatalf("Advance: %v", err)
|
||||
}
|
||||
if !res.Claimed || res.NextStep.ID != "m.2" {
|
||||
t.Fatalf("Advance = %+v, want m.1 skipped (held) and m.2 claimed", res)
|
||||
}
|
||||
|
||||
f.issues["m.2"].Status, f.issues["m.2"].Assignee = types.StatusOpen, ""
|
||||
boom := errors.New("connection reset")
|
||||
f.claimErrs["m.1"] = boom
|
||||
if _, err := f.stepper().Advance(ctx, issueops.AdvanceRequest{Actor: "alice", ClosedStepID: "m.0", AutoClaim: true}); !errors.Is(err, boom) {
|
||||
t.Fatalf("Advance with a failed claim = %v, want the failure", err)
|
||||
}
|
||||
|
||||
f.claimErrs["m.1"] = issueops.ErrNotClaimable
|
||||
f.claimErrs["m.2"] = issueops.ErrAlreadyClaimed
|
||||
res, err = f.stepper().Advance(ctx, issueops.AdvanceRequest{Actor: "alice", ClosedStepID: "m.0", AutoClaim: true})
|
||||
if err != nil || res.Claimed || res.NextStep == nil || res.NextStep.ID != "m.1" {
|
||||
t.Fatalf("Advance with every ready step lost = %+v, %v; want no claim and the first ready step named", res, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMoleculeStepperClaimsAWispStepThroughLifecycle(t *testing.T) {
|
||||
f := newFakeMolecules()
|
||||
f.add("w", types.TypeMolecule, types.StatusOpen).Ephemeral = true
|
||||
f.add("w.1", types.TypeTask, types.StatusClosed).Ephemeral = true
|
||||
f.add("w.2", types.TypeTask, types.StatusOpen).Ephemeral = true
|
||||
f.edge("w.1", "w", types.DepParentChild)
|
||||
f.edge("w.2", "w", types.DepParentChild)
|
||||
res, err := f.stepper().Advance(context.Background(), issueops.AdvanceRequest{Actor: "alice", ClosedStepID: "w.1", AutoClaim: true})
|
||||
if err != nil {
|
||||
t.Fatalf("Advance: %v", err)
|
||||
}
|
||||
if !res.Claimed || !slices.Equal(f.updated, []string{"w.2"}) || len(f.claimed) != 0 {
|
||||
t.Fatalf("Advance over a wisp = %+v (updates %v, claims %v), want w.2 claimed through Lifecycle", res, f.updated, f.claimed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMoleculeStepperOutsideAMoleculeAndWhenComplete(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
f := newFakeMolecules()
|
||||
f.add("orphan", types.TypeTask, types.StatusClosed)
|
||||
res, err := f.stepper().Advance(ctx, issueops.AdvanceRequest{Actor: "alice", ClosedStepID: "orphan", AutoClaim: true})
|
||||
if err != nil || res.MoleculeID != "" || res.ClosedStep == nil || res.NextStep != nil {
|
||||
t.Fatalf("Advance outside a molecule = %+v, %v; want no molecule", res, err)
|
||||
}
|
||||
|
||||
f.add("m", types.TypeMolecule, types.StatusOpen)
|
||||
f.add("m.1", types.TypeTask, types.StatusClosed)
|
||||
f.edge("m.1", "m", types.DepParentChild)
|
||||
res, err = f.stepper().Advance(ctx, issueops.AdvanceRequest{Actor: "alice", ClosedStepID: "m.1", AutoClaim: true})
|
||||
if err != nil || !res.Complete || res.NextStep != nil {
|
||||
t.Fatalf("Advance on a complete molecule = %+v, %v; want complete", res, err)
|
||||
}
|
||||
|
||||
if _, err := f.stepper().Advance(ctx, issueops.AdvanceRequest{Actor: "alice", ClosedStepID: "absent"}); !errors.Is(err, issueops.ErrNotFound) {
|
||||
t.Errorf("Advance on an absent step = %v, want ErrNotFound", err)
|
||||
}
|
||||
for _, req := range []issueops.AdvanceRequest{{ClosedStepID: "m.1"}, {Actor: "alice"}} {
|
||||
if _, err := f.stepper().Advance(ctx, req); !errors.Is(err, issueops.ErrValidation) {
|
||||
t.Errorf("Advance(%+v) = %v, want ErrValidation", req, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestActiveMoleculeIDsFallsBackToHookedWork(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
f := newFakeMolecules()
|
||||
seedChain(f)
|
||||
f.issues["m.b"].Status, f.issues["m.b"].Assignee = types.StatusInProgress, "alice"
|
||||
ids, err := issueops.ActiveMoleculeIDs(ctx, f, f.reader(), "alice")
|
||||
if err != nil || !slices.Equal(ids, []string{"m"}) {
|
||||
t.Fatalf("ActiveMoleculeIDs = %v, %v, want [m]", ids, err)
|
||||
}
|
||||
|
||||
g := newFakeMolecules()
|
||||
g.add("epic", types.TypeEpic, types.StatusOpen)
|
||||
g.add("handoff", types.TypeTask, types.StatusHooked).Assignee = "bob"
|
||||
g.edge("handoff", "epic", types.DepBlocks)
|
||||
ids, err = issueops.ActiveMoleculeIDs(ctx, g, g.reader(), "bob")
|
||||
if err != nil || !slices.Equal(ids, []string{"epic"}) {
|
||||
t.Fatalf("ActiveMoleculeIDs (hooked) = %v, %v, want [epic]", ids, err)
|
||||
}
|
||||
ids, err = issueops.ActiveMoleculeIDs(ctx, g, g.reader(), "carol")
|
||||
if err != nil || len(ids) != 0 {
|
||||
t.Fatalf("ActiveMoleculeIDs (nobody's work) = %v, %v, want none", ids, err)
|
||||
}
|
||||
}
|
||||
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