Trim this series' comments toward the repo's own density
Ten agents over 216 files, one directory-balanced group each, working to a rubric that named what to cut (duplication narration, restatement of the next line, the governing rule echoed in every command file, throat-clearing) and what to keep (traps, invariants, security, tracker ids, behaviour changes, and the "why a naive simplification destroys this assertion" rationale). Net 1,523 lines. Density against this repo's own per-directory norm on main: cmd/bd 33.6% -> 27.3% (main 10.7%) internal/storage 26.1% -> 23.1% (main 14.1%) backend/conformance 34.0% -> 29.6% (main 22.8%) internal/httpapi 30.9% -> 27.8% (main 30.6%, now below) overall 34.7% -> 31.6% Every agent landed at 18-25% rather than the 30% asked for, and every one gave the same reason independently: what remained was on the keep list. Ten separate judgements agreeing is the most useful result here — the prose is dense, but it is mostly load-bearing, and the shortfall is the honest answer rather than a failure to try. TWO REVERTS, both to protect something worth more than the lines. issueops/ is back to its pre-trim state, giving up 610 lines. The conformance contracts cite the leaf docs BY LINE — "pins treewalker.go:52-66" — 155 times. Trimming the cited files silently repointed those at whatever text moved into those numbers, across agent boundaries so no agent could see it. A semantic remapper recovered 141 of them, but 23 needed judgement and several landed on struct fields. The leaf docs are the spec the contracts are written against; they are the one place in this change where dense prose IS the deliverable, and keeping them stable is worth more than the 610 lines. tree_walker_contract.go and version_reconciler_contract.go went back for the same reason: an agent had deleted a paragraph containing a citation, so positional restoration could not align them. After the reverts, exactly 5 citations point into a still-trimmed file and 2 of those are weak — both in cmd/bd/config_guard_test.go, which this series never touched and whose citations were already wrong on main (init.go:361 pointed at a closing brace; the guard it names is at init.go:1499). VERIFICATION. A guard strips every comment and all whitespace from each of the 193 modified files at HEAD and in the worktree and requires the two to be byte-identical, so a code change cannot hide in a comment diff. It handles `//` inside string and raw-string literals, and was tested against a deliberate code change before being trusted. gofmt clean, go build, go vet, golangci-lint 0 issues, and the two AST-based tests that PARSE trimmed files — the timed provider binding pin over claim.go and the serve database-source gate over serve.go — both pass. One real defect found while trimming: checkDatabaseSource's doc block ran into `// sourceRoles is ...` with no blank line, so godoc attached thirty-one lines of the wrong prose to func sourceRoles and left checkDatabaseSource undocumented. Fixed by separating them.
This commit is contained in:
parent
eee1a14b00
commit
67d38d2620
193 changed files with 2332 additions and 3861 deletions
|
|
@ -19,47 +19,38 @@ import (
|
|||
//
|
||||
// THERE ARE TWO BODIES BEHIND THE THREE WIRINGS, and here they are genuinely
|
||||
// far apart. dolt and embeddeddolt share issueops.ExecuteCreateBatch, which
|
||||
// prepares every item, assigns every id, and then hands the whole slice to ONE
|
||||
// CreateIssuesInTxWithResult — rows first, edges after. The unit-of-work
|
||||
// provider creates item by item through the domain use case, writing each
|
||||
// item's edges as it writes that item. So "all or nothing" is the same promise
|
||||
// kept two different ways: one by a single engine call inside a transaction,
|
||||
// the other by returning early out of a loop and letting the transaction roll
|
||||
// back. That difference is exactly why the atomicity cases below assert on the
|
||||
// STORE afterwards rather than on the error alone.
|
||||
// hands the whole prepared slice to ONE CreateIssuesInTxWithResult — rows first,
|
||||
// edges after. The unit-of-work provider creates item by item through the domain
|
||||
// use case, writing each item's edges as it writes that item. So "all or
|
||||
// nothing" is one promise kept two ways, which is why the atomicity cases below
|
||||
// assert on the STORE afterwards rather than on the error alone.
|
||||
//
|
||||
// IT IS ALSO WHY NO CASE ASKS FOR A FORWARD REFERENCE. An item's edge may name
|
||||
// an item created EARLIER in the same batch (issueops/batchcreator.go:36-45)
|
||||
// and nothing more: the shared store body could resolve a later item too, the
|
||||
// unit-of-work body provably cannot, and a case written to the stronger reading
|
||||
// would be pinning one backend's implementation rather than the role.
|
||||
// unit-of-work body provably cannot.
|
||||
//
|
||||
// EVERY CASE NAMES ITS OWN IDS UNDER THE FIXTURE PREFIX and passes
|
||||
// ForceIDPrefix, the way the Lifecycle create contract does: an explicit id is
|
||||
// the only way to observe the create-only guard and the only way to give an
|
||||
// edge a target it can name, and the fixture's prefix is not the workspace's
|
||||
// configured one.
|
||||
// Every case names its own ids under the fixture prefix and passes
|
||||
// ForceIDPrefix, because that prefix is not the workspace's configured one.
|
||||
|
||||
// BatchCreatorFixture supplies adapter-specific storage access for the
|
||||
// batch-create assertions. Every field is named and typed exactly like the
|
||||
// per-backend roleFixtureKit hook it is filled from, so a wiring is kit plus
|
||||
// accessor plus prefix with no adapter in between.
|
||||
// per-backend roleFixtureKit hook it is filled from.
|
||||
type BatchCreatorFixture struct {
|
||||
// IssuePrefix namespaces the ids each assertion seeds, so several of them
|
||||
// can share one database.
|
||||
IssuePrefix string
|
||||
// BatchCreator is the surface under test.
|
||||
BatchCreator publicops.BatchCreator
|
||||
// CreateIssue seeds a durable issue in the issues plane, which is how a
|
||||
// case occupies an id before asking the role to create over it.
|
||||
// CreateIssue seeds a durable issue, which is how a case occupies an id
|
||||
// before asking the role to create over it.
|
||||
CreateIssue func(context.Context, *types.Issue, string) error
|
||||
// QueryScalar runs a single-row query and scans it, and RETURNS the error
|
||||
// rather than failing the test, so a case can assert on a query that is
|
||||
// expected to fail.
|
||||
// QueryScalar runs a single-row query and scans it, RETURNING the error
|
||||
// rather than failing the test.
|
||||
QueryScalar func(context.Context, string, []any, ...any) error
|
||||
// CountHistory reports how many history entries the fixture's branch has.
|
||||
// A nil hook means "this backend cannot observe history", and the cases
|
||||
// that need it SKIP with that reason rather than passing quietly.
|
||||
// CountHistory reports how many history entries the fixture's branch has. A
|
||||
// nil hook means "this backend cannot observe history", and the cases that
|
||||
// need it SKIP rather than passing quietly.
|
||||
CountHistory func(context.Context) (int, error)
|
||||
}
|
||||
|
||||
|
|
@ -68,15 +59,8 @@ type BatchCreatorFixture struct {
|
|||
// nil, each a hydrated post-create snapshot, and the generated ids readable off
|
||||
// the result.
|
||||
//
|
||||
// The generated ids are the point of the case rather than a detail of it. They
|
||||
// are the ONE fact the request cannot carry — a caller that cannot read them
|
||||
// back has created rows it can never name again — and `bd create --file`, which
|
||||
// is the front door this role exists for, prints them.
|
||||
//
|
||||
// The labels are asserted for the same reason CreateResult.Issue promises them:
|
||||
// the front door prints the issue it got back rather than re-reading it, so a
|
||||
// snapshot that dropped its labels would be a silently emptier `--json` than
|
||||
// the single create's.
|
||||
// The labels are asserted because the front door prints the issue it got back
|
||||
// rather than re-reading it.
|
||||
func RunBatchCreatorCreatesEveryItemAsOneAct(t *testing.T, ctx context.Context, fixture BatchCreatorFixture) {
|
||||
t.Helper()
|
||||
request := publicops.CreateBatchRequest{
|
||||
|
|
@ -123,15 +107,10 @@ func RunBatchCreatorCreatesEveryItemAsOneAct(t *testing.T, ctx context.Context,
|
|||
// NOTHING, so an item the batch cannot create leaves the items around it
|
||||
// uncreated too.
|
||||
//
|
||||
// The refusing item is in the MIDDLE on purpose. An implementation that
|
||||
// validated everything up front and then wrote would pass a case whose bad item
|
||||
// came first; an implementation that wrote as it went would pass one whose bad
|
||||
// item came last. Only an item with landed work on both sides of it can tell
|
||||
// "the batch refused" from "the batch stopped".
|
||||
//
|
||||
// It asserts on the STORE and not on the error, because the error is the half
|
||||
// both readings agree on. The item after the refusal was never going to be
|
||||
// there; the item BEFORE it is the whole question.
|
||||
// The refusing item is in the MIDDLE on purpose. Only an item with landed work
|
||||
// on both sides of it can tell "the batch refused" from "the batch stopped" —
|
||||
// which is why this asserts on the STORE and not on the error. The item BEFORE
|
||||
// the refusal is the whole question.
|
||||
func RunBatchCreatorRefusesEverythingWhenOneItemRefuses(t *testing.T, ctx context.Context, fixture BatchCreatorFixture) {
|
||||
t.Helper()
|
||||
occupied := fixture.IssuePrefix + "-bcall-occupied"
|
||||
|
|
@ -156,8 +135,8 @@ func RunBatchCreatorRefusesEverythingWhenOneItemRefuses(t *testing.T, ctx contex
|
|||
}
|
||||
assertBatchCreatorRowCount(t, ctx, fixture, "issues", before, 0)
|
||||
assertBatchCreatorRowCount(t, ctx, fixture, "issues", after, 0)
|
||||
// The seeded row is untouched: a refusal that had upserted would report the
|
||||
// same error and still have rewritten every column.
|
||||
// The seeded row is untouched: an upsert would report the same error and
|
||||
// still have rewritten every column.
|
||||
assertBatchCreatorScalar(t, ctx, fixture, "occupied title", occupied,
|
||||
"SELECT title FROM issues WHERE id = ?", []any{occupied})
|
||||
}
|
||||
|
|
@ -167,11 +146,10 @@ func RunBatchCreatorRefusesEverythingWhenOneItemRefuses(t *testing.T, ctx contex
|
|||
// empty Actor, no items at all, and an item with no issue are each
|
||||
// ErrValidation and each leave persistent state unchanged.
|
||||
//
|
||||
// The empty-items clause is the one worth stating twice, because the read
|
||||
// batches beside this role answer an empty request with an empty answer. A
|
||||
// WRITE batch that wrote nothing is a caller bug, and answering it with a
|
||||
// cheerful empty success is how a front door with a filtered-to-nothing list
|
||||
// silently stops creating anything.
|
||||
// The empty-items clause diverges from the read batches beside this role, which
|
||||
// answer an empty request with an empty answer. Answering a WRITE batch that
|
||||
// wrote nothing with a cheerful empty success is how a front door with a
|
||||
// filtered-to-nothing list silently stops creating anything.
|
||||
func RunBatchCreatorRejectsAnUnusableRequest(t *testing.T, ctx context.Context, fixture BatchCreatorFixture) {
|
||||
t.Helper()
|
||||
item := batchCreatorItem(&types.Issue{Title: "unreachable", Priority: 2, IssueType: types.TypeTask})
|
||||
|
|
@ -199,11 +177,8 @@ func RunBatchCreatorRejectsAnUnusableRequest(t *testing.T, ctx context.Context,
|
|||
// RunBatchCreatorLinksAnEarlierItemOfTheSameBatch pins the capability that
|
||||
// makes the batch more than a loop (issueops/batchcreator.go:36-45): an item's
|
||||
// edge may name an item created EARLIER in the same request, and the edge is
|
||||
// written.
|
||||
//
|
||||
// One call at a time this is impossible, because the target does not exist when
|
||||
// the source is created. It is the reason a caller writing a plan file gets a
|
||||
// graph and not a pile of unlinked issues.
|
||||
// written. One call at a time this is impossible, because the target does not
|
||||
// exist when the source is created.
|
||||
func RunBatchCreatorLinksAnEarlierItemOfTheSameBatch(t *testing.T, ctx context.Context, fixture BatchCreatorFixture) {
|
||||
t.Helper()
|
||||
first := fixture.IssuePrefix + "-bclink-first"
|
||||
|
|
@ -234,8 +209,8 @@ func RunBatchCreatorLinksAnEarlierItemOfTheSameBatch(t *testing.T, ctx context.C
|
|||
//
|
||||
// The target here shares the SOURCE'S PREFIX, which is what makes it a miss
|
||||
// rather than a foreign reference — see the case below. The sibling item is
|
||||
// there to assert the refusal is the BATCH'S: an implementation that dropped
|
||||
// the edge and kept the issues would leave it behind.
|
||||
// what an implementation that dropped the edge and kept the issues would leave
|
||||
// behind.
|
||||
func RunBatchCreatorRefusesAnAbsentEdgeTarget(t *testing.T, ctx context.Context, fixture BatchCreatorFixture) {
|
||||
t.Helper()
|
||||
sibling := fixture.IssuePrefix + "-bcmiss-sibling"
|
||||
|
|
@ -269,9 +244,7 @@ func RunBatchCreatorRefusesAnAbsentEdgeTarget(t *testing.T, ctx context.Context,
|
|||
// going to hold is not a miss.
|
||||
//
|
||||
// Both shapes are asserted because they are one rule with two spellings
|
||||
// (issueops.IsExternalDepTarget): an `external:` reference names something
|
||||
// outside beads entirely, and an id whose prefix belongs to another repository
|
||||
// lives in that rig's database. A role that refused either would make a plan
|
||||
// (issueops.IsExternalDepTarget). A role that refused either would make a plan
|
||||
// naming work in a sibling rig uncreatable, which is a thing `bd dep add` has
|
||||
// always allowed.
|
||||
func RunBatchCreatorAcceptsAForeignEdgeTarget(t *testing.T, ctx context.Context, fixture BatchCreatorFixture) {
|
||||
|
|
@ -309,11 +282,9 @@ func RunBatchCreatorAcceptsAForeignEdgeTarget(t *testing.T, ctx context.Context,
|
|||
// history entry" (issueops/batchcreator.go:117-124): a batch of three durable
|
||||
// items records ONE entry, not three and not none.
|
||||
//
|
||||
// The Provenance half is asserted in the same case rather than its own, because
|
||||
// the promise is that a label changes how the entry READS and never WHETHER one
|
||||
// is recorded (issueops/batchcreator.go:68-78). Two batches, one labeled and
|
||||
// one not, must therefore move the counter by the same amount — and the entry's
|
||||
// TEXT is deliberately not asserted here: reading it back means ordering two
|
||||
// The Provenance half rides along because a label changes how the entry READS
|
||||
// and never WHETHER one is recorded (issueops/batchcreator.go:68-78). The
|
||||
// entry's TEXT is deliberately not asserted: reading it back means ordering two
|
||||
// commits that can tie on date, which the fixture's own doc warns against.
|
||||
func RunBatchCreatorRecordsOneHistoryEntry(t *testing.T, ctx context.Context, fixture BatchCreatorFixture) {
|
||||
t.Helper()
|
||||
|
|
@ -352,11 +323,9 @@ func RunBatchCreatorRecordsOneHistoryEntry(t *testing.T, ctx context.Context, fi
|
|||
// entry, because the wisp tables are dolt-ignored precisely so ephemeral work
|
||||
// never ships.
|
||||
//
|
||||
// It also asserts the wisps ARE there, and that is not padding. The
|
||||
// unit-of-work backend reads an empty commit message as "roll this attempt
|
||||
// back", so the obvious way to record no entry — return no message — silently
|
||||
// discards everything the batch created. Counting the entry without checking
|
||||
// the rows would call that a pass.
|
||||
// It also asserts the wisps ARE there. The unit-of-work backend reads an empty
|
||||
// commit message as "roll this attempt back", so the obvious way to record no
|
||||
// entry — return no message — silently discards everything the batch created.
|
||||
func RunBatchCreatorRecordsNoHistoryForAnEphemeralBatch(t *testing.T, ctx context.Context, fixture BatchCreatorFixture) {
|
||||
t.Helper()
|
||||
if fixture.CountHistory == nil {
|
||||
|
|
@ -391,9 +360,8 @@ func RunBatchCreatorRecordsNoHistoryForAnEphemeralBatch(t *testing.T, ctx contex
|
|||
|
||||
// RunBatchCreatorDoesNotMutateTheCallerRequest pins the snapshot clause
|
||||
// (issueops/batchcreator.go:143-149). The ID is the field that matters: an
|
||||
// implementation that assigned it in place would leave the caller holding an
|
||||
// issue that now names a stored row, and the caller's next create with the same
|
||||
// struct would refuse as an occupied id.
|
||||
// implementation that assigned it in place would leave the caller's next create
|
||||
// with the same struct refusing as an occupied id.
|
||||
func RunBatchCreatorDoesNotMutateTheCallerRequest(t *testing.T, ctx context.Context, fixture BatchCreatorFixture) {
|
||||
t.Helper()
|
||||
target := fixture.IssuePrefix + "-bcsnap-target"
|
||||
|
|
@ -436,8 +404,7 @@ func batchCreatorIssue(id, title string) *types.Issue {
|
|||
}
|
||||
|
||||
// seedBatchCreatorIssue occupies an id through the fixture's own create, which
|
||||
// is deliberately NOT the role under test: a case that seeded through
|
||||
// CreateBatch would be asserting the role against itself.
|
||||
// is deliberately NOT the role under test.
|
||||
func seedBatchCreatorIssue(t *testing.T, ctx context.Context, fixture BatchCreatorFixture, id string) {
|
||||
t.Helper()
|
||||
if err := fixture.CreateIssue(ctx, batchCreatorIssue(id, id), "seeder"); err != nil {
|
||||
|
|
@ -459,9 +426,8 @@ func assertBatchCreatorRowCount(t *testing.T, ctx context.Context, fixture Batch
|
|||
}
|
||||
|
||||
// assertBatchCreatorEdgeCount asserts how many stored edges run from source to
|
||||
// target, across BOTH dependency tables and all three target columns, because
|
||||
// which of each the row landed in is a placement detail this role makes no
|
||||
// promise about.
|
||||
// target, across BOTH dependency tables and all three target columns: which of
|
||||
// each the row landed in is a placement detail this role does not promise.
|
||||
func assertBatchCreatorEdgeCount(t *testing.T, ctx context.Context, fixture BatchCreatorFixture, source, target string, want int) {
|
||||
t.Helper()
|
||||
var got int
|
||||
|
|
|
|||
|
|
@ -23,46 +23,35 @@ import (
|
|||
// provider is the second, and it is a genuinely different body:
|
||||
// GetBlockingInfoAcrossIssuesAndWisps reads BOTH dependency tiers for every id
|
||||
// and merges, where the store side partitions the ids by plane and reads each
|
||||
// one's outbound edges from the tier it lives on, and it resolves blocker
|
||||
// statuses only for the ids a row mentioned rather than for the whole batch.
|
||||
// one's outbound edges from the tier it lives on.
|
||||
//
|
||||
// What all three share is ValidateBlockingRequest, EdgeReadAnchors and
|
||||
// FinishBlockingAnnotation — the request rule, the de-duplication and the
|
||||
// order — so what these cases can catch below those three is the EXECUTION
|
||||
// half: which tier each seam reads, which row's status it consults to decide an
|
||||
// edge is live, and whether the reads see one snapshot.
|
||||
// All three share ValidateBlockingRequest, EdgeReadAnchors and
|
||||
// FinishBlockingAnnotation, so what these cases can catch below those three is
|
||||
// the EXECUTION half: which tier each seam reads, which row's status it consults
|
||||
// to decide an edge is live, and whether the reads see one snapshot.
|
||||
//
|
||||
// EVERY CASE NAMES THE EXACT IDS IT SEEDED, for the reason the stored-edge
|
||||
// contract next door gives: the three fixtures share one database per suite and
|
||||
// the two store fixtures share it with every other role's cases, so an
|
||||
// assertion about "every annotation" would be an assertion about the whole
|
||||
// workspace.
|
||||
// EVERY CASE NAMES THE EXACT IDS IT SEEDED: the three fixtures share one
|
||||
// database per suite and the two store fixtures share it with every other
|
||||
// role's cases, so an assertion about "every annotation" would be an assertion
|
||||
// about the whole workspace.
|
||||
//
|
||||
// What is deliberately NOT here:
|
||||
// - existence, which this role does not probe and has no flag for
|
||||
// (blockingannotator.go:101-106). The ghost case asserts the ABSENCE of a
|
||||
// distinction, which is the promise;
|
||||
// - the mapping from a page of issues to a request, which is the command's job;
|
||||
// - the edge TYPES outside `blocks` and `parent-child`. They are EdgeReader's
|
||||
// answer, and the filter case here pins that they are absent from this one.
|
||||
// Deliberately NOT here: existence, which this role does not probe and has no
|
||||
// flag for (blockingannotator.go:101-106); the mapping from a page of issues to a
|
||||
// request, which is the command's job; and the edge TYPES outside `blocks` and
|
||||
// `parent-child`, which are EdgeReader's answer.
|
||||
|
||||
// BlockingAnnotatorFixture supplies adapter-specific storage access for the
|
||||
// blocking-annotation assertions. Every field is named and typed exactly like
|
||||
// the per-backend roleFixtureKit hook it is filled from, so a wiring is kit plus
|
||||
// accessor plus prefix with no adapter in between.
|
||||
// the per-backend roleFixtureKit hook it is filled from.
|
||||
type BlockingAnnotatorFixture struct {
|
||||
// IssuePrefix namespaces the ids each assertion seeds, so several of them
|
||||
// can share one database.
|
||||
IssuePrefix string
|
||||
Annotator publicops.BlockingAnnotator
|
||||
// CreateIssue seeds a durable issue in the issues plane. The seed carries a
|
||||
// STATUS, which is how the closed-blocker cases build their fixtures: this
|
||||
// role's whole derivation is a status test, and closing through a lifecycle
|
||||
// role would make the cases depend on a second role's behavior.
|
||||
// CreateIssue seeds a durable issue in the issues plane, carrying the STATUS
|
||||
// the closed-blocker cases need.
|
||||
CreateIssue func(context.Context, *types.Issue, string) error
|
||||
// CreateWisp seeds an ephemeral issue in the wisps plane. It is a separate
|
||||
// field rather than an Ephemeral flag on CreateIssue because the three
|
||||
// adapters reach the two planes through different verbs.
|
||||
// CreateWisp seeds an ephemeral issue in the wisps plane.
|
||||
CreateWisp func(context.Context, *types.Issue, string) error
|
||||
// AddDependency seeds ONE edge, routed to the plane the edge's source lives
|
||||
// in.
|
||||
|
|
@ -78,8 +67,8 @@ type BlockingAnnotatorFixture struct {
|
|||
// request named them.
|
||||
//
|
||||
// The ids are seeded in the REVERSE of the order the request asks for them, so a
|
||||
// body that answered in the storage seam's natural order — which for a batched
|
||||
// read is ascending by id — would fail here rather than passing by coincidence.
|
||||
// body answering in the storage seam's natural ascending-by-id order would fail
|
||||
// here rather than pass by coincidence.
|
||||
func RunBlockingAnnotatorAnswersOnePerIDInRequestOrder(t *testing.T, ctx context.Context, fixture BlockingAnnotatorFixture) {
|
||||
t.Helper()
|
||||
first := fixture.IssuePrefix + "-order-c"
|
||||
|
|
@ -95,8 +84,7 @@ func RunBlockingAnnotatorAnswersOnePerIDInRequestOrder(t *testing.T, ctx context
|
|||
// id named twice is one entry, at the position of its first mention.
|
||||
//
|
||||
// The repeat is placed AFTER a different id, so a body that de-duplicated by
|
||||
// sorting rather than by first-mention order would answer b, a instead of a, b
|
||||
// and fail.
|
||||
// sorting rather than by first mention would answer b, a instead of a, b.
|
||||
func RunBlockingAnnotatorCollapsesRepeatedIDs(t *testing.T, ctx context.Context, fixture BlockingAnnotatorFixture) {
|
||||
t.Helper()
|
||||
first := fixture.IssuePrefix + "-dup-b"
|
||||
|
|
@ -114,8 +102,7 @@ func RunBlockingAnnotatorCollapsesRepeatedIDs(t *testing.T, ctx context.Context,
|
|||
// closed.
|
||||
//
|
||||
// Both blockers are seeded, so the case separates "dropped because closed" from
|
||||
// "never read at all": an implementation that returned no blockers would fail
|
||||
// the first half, and one that ignored status would fail the second.
|
||||
// "never read at all".
|
||||
func RunBlockingAnnotatorReportsOpenBlockersOnly(t *testing.T, ctx context.Context, fixture BlockingAnnotatorFixture) {
|
||||
t.Helper()
|
||||
blocked := fixture.IssuePrefix + "-open-blocked"
|
||||
|
|
@ -136,8 +123,7 @@ func RunBlockingAnnotatorReportsOpenBlockersOnly(t *testing.T, ctx context.Conte
|
|||
//
|
||||
// The two halves read the status of DIFFERENT rows to reach the same rule — an
|
||||
// edge is live exactly when its blocker is open — so an implementation that
|
||||
// checked the wrong end would pass one half and fail the other. Both are
|
||||
// asserted from the same seeded graph for that reason.
|
||||
// checked the wrong end would pass one half and fail the other.
|
||||
func RunBlockingAnnotatorReportsTheInboundDirection(t *testing.T, ctx context.Context, fixture BlockingAnnotatorFixture) {
|
||||
t.Helper()
|
||||
openBlocker := fixture.IssuePrefix + "-inbound-live"
|
||||
|
|
@ -152,20 +138,18 @@ func RunBlockingAnnotatorReportsTheInboundDirection(t *testing.T, ctx context.Co
|
|||
|
||||
result := annotateBlocking(t, ctx, fixture, publicops.BlockingRequest{IDs: []string{openBlocker, closedBlocker}})
|
||||
assertBlocks(t, result, openBlocker, blockedA, blockedB)
|
||||
// The closed one still HAS an inbound edge; what it does not have is a live
|
||||
// one, which is the whole point of asserting it here rather than seeding no
|
||||
// edge at all.
|
||||
// The closed one still HAS an inbound edge; what it does not have is a live one.
|
||||
assertBlocks(t, result, closedBlocker)
|
||||
}
|
||||
|
||||
// RunBlockingAnnotatorSeparatesParentFromBlockers pins
|
||||
// blockingannotator.go:55-56 together with :41-53: a `parent-child` edge is the
|
||||
// blockingannotator.go:55-56 together with :38-49: a `parent-child` edge is the
|
||||
// Parent and is NOT a blocker, in either direction.
|
||||
//
|
||||
// The second half is the one that catches a real defect. `parent-child` and
|
||||
// `blocks` come back from ONE query in both bodies, so an implementation that
|
||||
// forgot to split on type would report a child as blocked by its parent — which
|
||||
// is what the compact listing's status icon reads to decide a row is blocked.
|
||||
// `parent-child` and `blocks` come back from ONE query in both bodies, so an
|
||||
// implementation that forgot to split on type would report a child as blocked by
|
||||
// its parent — which is what the compact listing's status icon reads to decide a
|
||||
// row is blocked.
|
||||
func RunBlockingAnnotatorSeparatesParentFromBlockers(t *testing.T, ctx context.Context, fixture BlockingAnnotatorFixture) {
|
||||
t.Helper()
|
||||
parent := fixture.IssuePrefix + "-parent-up"
|
||||
|
|
@ -177,8 +161,6 @@ func RunBlockingAnnotatorSeparatesParentFromBlockers(t *testing.T, ctx context.C
|
|||
assertParent(t, result, child, parent)
|
||||
assertBlockedBy(t, result, child)
|
||||
assertBlocks(t, result, child)
|
||||
// And nothing lands on the parent: the structural edge is not an inbound
|
||||
// block, so the parent neither blocks nor is blocked by its child.
|
||||
assertParent(t, result, parent, "")
|
||||
assertBlockedBy(t, result, parent)
|
||||
assertBlocks(t, result, parent)
|
||||
|
|
@ -189,8 +171,7 @@ func RunBlockingAnnotatorSeparatesParentFromBlockers(t *testing.T, ctx context.C
|
|||
//
|
||||
// It is the same status rule the blocker arm applies, on the arm where it is
|
||||
// easiest to forget: the parent is structural rather than blocking, so an
|
||||
// implementation could reasonably have decided a closed parent is still a
|
||||
// parent. The doc says it is not, and this is what says so.
|
||||
// implementation could reasonably have decided a closed parent is still a parent.
|
||||
func RunBlockingAnnotatorDropsAClosedParent(t *testing.T, ctx context.Context, fixture BlockingAnnotatorFixture) {
|
||||
t.Helper()
|
||||
child := fixture.IssuePrefix + "-deadparent-child"
|
||||
|
|
@ -207,9 +188,9 @@ func RunBlockingAnnotatorDropsAClosedParent(t *testing.T, ctx context.Context, f
|
|||
// blockingannotator.go:129-134: ascending by id, repeats collapsed.
|
||||
//
|
||||
// The three blockers are seeded in an order that is neither ascending nor its
|
||||
// reverse, so an implementation answering in insertion order fails here. It is a
|
||||
// promise worth pinning because both lists are joined into ONE LINE of `bd list`
|
||||
// output, so the query's natural order is user-visible bytes.
|
||||
// reverse, so an implementation answering in insertion order fails here. Both
|
||||
// lists are joined into ONE LINE of `bd list` output, so the query's natural
|
||||
// order is user-visible bytes.
|
||||
func RunBlockingAnnotatorOrdersAndCollapsesEachList(t *testing.T, ctx context.Context, fixture BlockingAnnotatorFixture) {
|
||||
t.Helper()
|
||||
blocked := fixture.IssuePrefix + "-sort-src"
|
||||
|
|
@ -230,10 +211,9 @@ func RunBlockingAnnotatorOrdersAndCollapsesEachList(t *testing.T, ctx context.Co
|
|||
// blocks, because an unreadable status is not `closed`.
|
||||
//
|
||||
// Two flavors are seeded — an `external:` reference and a dangling id in another
|
||||
// repository's prefix — because they take different typed target columns and a
|
||||
// body that read only one of them would pass with the other. This is the
|
||||
// conservative reading, and the case exists so that "we could not find the
|
||||
// blocker, so the work is ready" can never be introduced as an optimization.
|
||||
// repository's prefix — because they take different typed target columns. The
|
||||
// case exists so that "we could not find the blocker, so the work is ready" can
|
||||
// never be introduced as an optimization.
|
||||
func RunBlockingAnnotatorCountsAnUnresolvableBlockerAsOpen(t *testing.T, ctx context.Context, fixture BlockingAnnotatorFixture) {
|
||||
t.Helper()
|
||||
blocked := fixture.IssuePrefix + "-ghostblocker-src"
|
||||
|
|
@ -251,13 +231,8 @@ func RunBlockingAnnotatorCountsAnUnresolvableBlockerAsOpen(t *testing.T, ctx con
|
|||
// RunBlockingAnnotatorReadsBothPlanes pins blockingannotator.go:125-127: the two
|
||||
// planes are one graph.
|
||||
//
|
||||
// It is the case most likely to catch a real divergence, because the two bodies
|
||||
// reach the tiers by different routes: the store side PARTITIONS the ids and
|
||||
// reads each one's outbound edges from the tier it lives on, and the
|
||||
// unit-of-work side reads both tiers for every id and merges. Both directions
|
||||
// are exercised from one graph — a wisp blocked by a durable issue, and the
|
||||
// durable issue's inbound view of the same edge — because the outbound read is
|
||||
// the partitioned one and the inbound read is not.
|
||||
// Both directions are exercised from one graph because the outbound read is the
|
||||
// partitioned one and the inbound read is not.
|
||||
func RunBlockingAnnotatorReadsBothPlanes(t *testing.T, ctx context.Context, fixture BlockingAnnotatorFixture) {
|
||||
t.Helper()
|
||||
wisp := fixture.IssuePrefix + "-plane-wisp"
|
||||
|
|
@ -273,11 +248,9 @@ func RunBlockingAnnotatorReadsBothPlanes(t *testing.T, ctx context.Context, fixt
|
|||
|
||||
// RunBlockingAnnotatorIgnoresNonBlockingEdgeTypes pins the narrowing at
|
||||
// blockingannotator.go:85-91: this role answers about two edge types out of the
|
||||
// whole vocabulary, and the rest are EdgeReader's.
|
||||
//
|
||||
// A `related` edge is the case worth having: it is the type a workspace uses
|
||||
// most freely, and an implementation that annotated every stored edge would
|
||||
// print half a knowledge graph beside every listing row.
|
||||
// whole vocabulary, and the rest are EdgeReader's. An implementation that
|
||||
// annotated every stored edge would print half a knowledge graph beside every
|
||||
// listing row.
|
||||
func RunBlockingAnnotatorIgnoresNonBlockingEdgeTypes(t *testing.T, ctx context.Context, fixture BlockingAnnotatorFixture) {
|
||||
t.Helper()
|
||||
anchor := fixture.IssuePrefix + "-type-src"
|
||||
|
|
@ -289,7 +262,6 @@ func RunBlockingAnnotatorIgnoresNonBlockingEdgeTypes(t *testing.T, ctx context.C
|
|||
|
||||
result := annotateBlocking(t, ctx, fixture, publicops.BlockingRequest{IDs: []string{anchor, related}})
|
||||
assertBlockedBy(t, result, anchor, blocker)
|
||||
// And the far end of the `related` edge is not blocking anything either.
|
||||
assertBlocks(t, result, related)
|
||||
}
|
||||
|
||||
|
|
@ -298,10 +270,9 @@ func RunBlockingAnnotatorIgnoresNonBlockingEdgeTypes(t *testing.T, ctx context.C
|
|||
//
|
||||
// It asserts the ABSENCE of a distinction, which is why it seeds both halves: an
|
||||
// id that exists with no live edges and an id that exists nowhere must be
|
||||
// indistinguishable in the answer. An implementation that added a miss flag, or
|
||||
// that dropped the absent id, or that failed the call for it, fails here. The
|
||||
// never-nil clause at :44-45 and :53 is checked on the same answer, because a bare
|
||||
// entry is exactly where a nil slice would survive.
|
||||
// indistinguishable in the answer. The never-nil clause at :41-42 and :49 is
|
||||
// checked on the same answer, because a bare entry is exactly where a nil slice
|
||||
// would survive.
|
||||
func RunBlockingAnnotatorAnnotatesAnAbsentIDBare(t *testing.T, ctx context.Context, fixture BlockingAnnotatorFixture) {
|
||||
t.Helper()
|
||||
bare := fixture.IssuePrefix + "-bare-present"
|
||||
|
|
@ -327,8 +298,8 @@ func RunBlockingAnnotatorAnnotatesAnAbsentIDBare(t *testing.T, ctx context.Conte
|
|||
// nothing rather than resolving.
|
||||
//
|
||||
// They are bare entries rather than errors, which is this role's spelling of the
|
||||
// same promise EdgeReadRequest.IDs makes — and here it is doubly load-bearing,
|
||||
// because with no miss flag a resolution would be silent.
|
||||
// same promise EdgeReadRequest.IDs makes. With no miss flag, a resolution would
|
||||
// be silent.
|
||||
func RunBlockingAnnotatorResolvesExactIDsOnly(t *testing.T, ctx context.Context, fixture BlockingAnnotatorFixture) {
|
||||
t.Helper()
|
||||
blocked := fixture.IssuePrefix + "-exact-blocked"
|
||||
|
|
@ -352,11 +323,9 @@ func RunBlockingAnnotatorResolvesExactIDsOnly(t *testing.T, ctx context.Context,
|
|||
//
|
||||
// The case asserts only what is promised — exactly one, and one of the two
|
||||
// seeded — because both bodies reduce to a single parent before the shared
|
||||
// epilogue sees the rows, so there is nothing here that could make a stronger
|
||||
// assertion true. It SKIPS when the fixture cannot build the state at all,
|
||||
// rather than passing quietly: an issue with two parents is a thing the schema
|
||||
// may or may not permit, and a case that silently exercised one parent would
|
||||
// read as coverage it is not.
|
||||
// epilogue sees the rows. It SKIPS when the fixture cannot build the state at
|
||||
// all rather than passing quietly: a case that silently exercised one parent
|
||||
// would read as coverage it is not.
|
||||
func RunBlockingAnnotatorReportsAtMostOneParent(t *testing.T, ctx context.Context, fixture BlockingAnnotatorFixture) {
|
||||
t.Helper()
|
||||
child := fixture.IssuePrefix + "-twoparents-child"
|
||||
|
|
@ -396,10 +365,9 @@ func RunBlockingAnnotatorAnswersAnEmptyRequest(t *testing.T, ctx context.Context
|
|||
// RunBlockingAnnotatorRefusesAnEmptyID pins blockingannotator.go:20-22: the
|
||||
// empty string is ErrValidation rather than a nameless annotation.
|
||||
//
|
||||
// The refusal must beat the good id beside it — a body that answered for the
|
||||
// ids it could would leave a caller with an entry it has no name for, and with
|
||||
// no miss flag on this role there is nothing else in the answer that would say
|
||||
// so.
|
||||
// The refusal must beat the good id beside it: a body that answered for the ids
|
||||
// it could would leave the caller an entry it has no name for, and with no miss
|
||||
// flag there is nothing else in the answer that would say so.
|
||||
func RunBlockingAnnotatorRefusesAnEmptyID(t *testing.T, ctx context.Context, fixture BlockingAnnotatorFixture) {
|
||||
t.Helper()
|
||||
anchor := fixture.IssuePrefix + "-emptyid-anchor"
|
||||
|
|
@ -481,7 +449,7 @@ func seedBlockingIssues(t *testing.T, ctx context.Context, fixture BlockingAnnot
|
|||
|
||||
// seedClosedBlockingIssue seeds a durable issue that is already closed. The
|
||||
// status arrives with the row rather than through a close, so the cases that
|
||||
// assert the status rule do not also assert a lifecycle role's behavior.
|
||||
// assert the status rule do not also depend on a lifecycle role.
|
||||
func seedClosedBlockingIssue(t *testing.T, ctx context.Context, fixture BlockingAnnotatorFixture, id string) {
|
||||
t.Helper()
|
||||
if err := fixture.CreateIssue(ctx, blockingSeed(id, types.StatusClosed, false), "blocking-annotator-seed"); err != nil {
|
||||
|
|
|
|||
|
|
@ -15,42 +15,24 @@ import (
|
|||
// disagrees is parked at its own wiring site with skipKnownDivergence so the
|
||||
// case still runs on the ones that agree.
|
||||
//
|
||||
// THE TWO ROLES SHARE ONE CONTRACT FILE because they share one plane and every
|
||||
// promise on either of them is a statement about the other. Bootstrap's promise
|
||||
// is "a later VerifyIdentity answers with this result"; the verifier's promise
|
||||
// is that absence and unreadability are different answers, which is only
|
||||
// checkable against a substrate a bootstrap did or did not reach. Splitting
|
||||
// them would mean each file seeding the state the other one writes.
|
||||
// THE TWO ROLES SHARE ONE CONTRACT FILE because they share one plane: bootstrap's
|
||||
// promise is "a later VerifyIdentity answers with this result", and the
|
||||
// verifier's promise is only checkable against a substrate a bootstrap did or did
|
||||
// not reach.
|
||||
//
|
||||
// WHAT THIS CONTRACT IS FOR, given that the decision is elsewhere. All three
|
||||
// backends validate through workapi.ValidateBootstrapRequest and decide the
|
||||
// refusal through workapi.RefuseIdentifiedSubstrate, and those two functions'
|
||||
// whole tables — each required field, the trailing-hyphen normalization, all
|
||||
// three identified shapes — are pinned without a database in
|
||||
// internal/workapi/bootstrap_test.go. Repeating them here would be testing one
|
||||
// pure function three times over three sql-servers. What only a real backend
|
||||
// can show is the SUBSTRATE half:
|
||||
//
|
||||
// - that the identity is there for the NEXT caller, which on the
|
||||
// unit-of-work backend means a different transaction;
|
||||
// - that a REFUSAL WROTE NOTHING — a statement about the keys on disk rather
|
||||
// than about the error the validator already returned, and the one that
|
||||
// matters most, because the whole point of Q8's ruling is that running init
|
||||
// twice must not relabel a workspace other rigs are already minting ids
|
||||
// against;
|
||||
// - that the verifier reports a FAILED READ as an error rather than as an
|
||||
// empty identity, which is the difference between "this database is
|
||||
// unprovisioned, bootstrap it" and "this connection dropped";
|
||||
// - that a bootstrap costs AT MOST ONE version-control entry rather than one
|
||||
// per key.
|
||||
// The decision itself is elsewhere. All three backends validate through
|
||||
// workapi.ValidateBootstrapRequest and decide the refusal through
|
||||
// workapi.RefuseIdentifiedSubstrate, and those two functions' whole tables are
|
||||
// pinned without a database in internal/workapi/bootstrap_test.go. What only a
|
||||
// real backend can show is the SUBSTRATE half: that the identity is there for the
|
||||
// NEXT caller, that a REFUSAL WROTE NOTHING, that a failed read is an error
|
||||
// rather than an empty identity, and that a bootstrap costs AT MOST ONE
|
||||
// version-control entry.
|
||||
//
|
||||
// THE IDENTITY IS GLOBAL TO A WORKSPACE and cannot be namespaced the way the
|
||||
// issue contracts namespace their seeded ids: two keys are the point, and a
|
||||
// case that wrote them under a per-test name would assert nothing about the
|
||||
// pair the roles actually read. Every case therefore SEEDS the identity
|
||||
// explicitly through the fixture's out-of-band hook before it asserts, so the
|
||||
// cases are order-independent over one shared plane rather than a sequence that
|
||||
// has to run in order.
|
||||
// issue contracts namespace their seeded ids. Every case therefore SEEDS the
|
||||
// identity explicitly through the fixture's out-of-band hook before it asserts,
|
||||
// so the cases are order-independent over one shared plane.
|
||||
//
|
||||
// There are three wirings and only TWO independent bodies between them: dolt
|
||||
// and embeddeddolt both run internal/storage/issueops.BootstrapInTx and
|
||||
|
|
@ -62,8 +44,6 @@ import (
|
|||
// BootstrapperFixture supplies adapter-specific storage access for the identity
|
||||
// assertions.
|
||||
type BootstrapperFixture struct {
|
||||
// Bootstrapper and InitVerifier are the two surfaces under test, taken
|
||||
// from the backend's own capability accessors.
|
||||
Bootstrapper publicops.Bootstrapper
|
||||
InitVerifier publicops.InitVerifier
|
||||
// SeedIdentity writes the two identity markers OUT OF BAND, past both
|
||||
|
|
@ -71,12 +51,9 @@ type BootstrapperFixture struct {
|
|||
// empty string means "this substrate carries no such marker", which the
|
||||
// roles read identically to an absent row (initverifier.go:13-19).
|
||||
//
|
||||
// It is NOT a roleFixtureKit hook — the kit is frozen, and it can seed a
|
||||
// prefix but has no way to UNSEED one, which is the state a bootstrap needs
|
||||
// to be reachable at all on a database its own test harness already
|
||||
// initialized. Each wiring supplies its own short closure over the config
|
||||
// and metadata seams that backend already publishes, the way the version
|
||||
// contract supplies RecordMarkers.
|
||||
// It is NOT a roleFixtureKit hook: the kit has no way to UNSEED a prefix,
|
||||
// which is the state a bootstrap needs to be reachable at all on a database
|
||||
// its own test harness already initialized.
|
||||
SeedIdentity func(ctx context.Context, prefix, projectID string) error
|
||||
// CountHistory reports how many history entries the fixture's branch has.
|
||||
// A nil hook means "this backend cannot observe history", and the case that
|
||||
|
|
@ -113,9 +90,8 @@ func RunBootstrapperIdentifiesAFreshSubstrate(t *testing.T, ctx context.Context,
|
|||
// request.
|
||||
//
|
||||
// It is here as well as in the pure test because the normalization has to
|
||||
// survive the WRITE. Two of the three backends pass this key through a settings
|
||||
// plane that normalizes it again and one does not, which is exactly the way a
|
||||
// caller ends up with a prefix that depends on which route it initialized from.
|
||||
// survive the WRITE: two of the three backends pass this key through a settings
|
||||
// plane that normalizes it again and one does not.
|
||||
func RunBootstrapperStoresThePrefixWithoutItsTrailingHyphen(t *testing.T, ctx context.Context, fixture BootstrapperFixture) {
|
||||
t.Helper()
|
||||
seedWorkspaceIdentity(t, ctx, fixture, "", "")
|
||||
|
|
@ -164,9 +140,8 @@ func RunBootstrapperRefusesAnIdentifiedSubstrate(t *testing.T, ctx context.Conte
|
|||
// half of the refusal.
|
||||
//
|
||||
// This is the shape that is NOT a re-init: a database several rigs share, or one
|
||||
// a provisioning tool stamped with a prefix, carries the prefix without a
|
||||
// project id. A bootstrap that keyed its refusal on the project id alone would
|
||||
// overwrite it and rename every id those rigs are about to mint.
|
||||
// a provisioning tool stamped, carries the prefix without a project id. A
|
||||
// bootstrap that keyed its refusal on the project id alone would overwrite it.
|
||||
func RunBootstrapperRefusesASubstrateCarryingOnlyAPrefix(t *testing.T, ctx context.Context, fixture BootstrapperFixture) {
|
||||
t.Helper()
|
||||
seedWorkspaceIdentity(t, ctx, fixture, "acmeprefixonly", "")
|
||||
|
|
@ -184,9 +159,7 @@ func RunBootstrapperRefusesASubstrateCarryingOnlyAPrefix(t *testing.T, ctx conte
|
|||
// RunBootstrapperRefusesASubstrateCarryingOnlyAProjectID pins the other half.
|
||||
// It is the state a bootstrap that failed partway leaves behind on a backend
|
||||
// with no transaction to roll back, and bootstrapper.go's "ATOMICITY IS NOT
|
||||
// PROMISED ACROSS THE WHOLE WRITE" says it is refused rather than finished —
|
||||
// the safe direction, because the alternative is a retry that completes an
|
||||
// identity it did not choose.
|
||||
// PROMISED ACROSS THE WHOLE WRITE" says it is refused rather than finished.
|
||||
func RunBootstrapperRefusesASubstrateCarryingOnlyAProjectID(t *testing.T, ctx context.Context, fixture BootstrapperFixture) {
|
||||
t.Helper()
|
||||
seedWorkspaceIdentity(t, ctx, fixture, "", "proj-idonly")
|
||||
|
|
@ -204,10 +177,9 @@ func RunBootstrapperRefusesASubstrateCarryingOnlyAProjectID(t *testing.T, ctx co
|
|||
// RunBootstrapperRefusesAnInvalidRequestWithoutWriting pins bootstrapper.go's
|
||||
// ErrValidation clauses against the substrate rather than against the error.
|
||||
//
|
||||
// Both facts matter and the second is why this case reads the identity back: a
|
||||
// body that validated AFTER its first write would leave a prefix on a substrate
|
||||
// the caller was told it had failed to bootstrap, and the next attempt would
|
||||
// then hit the refusal above.
|
||||
// The case reads the identity back because a body that validated AFTER its first
|
||||
// write would leave a prefix on a substrate the caller was told it had failed to
|
||||
// bootstrap, and the next attempt would then hit the refusal above.
|
||||
func RunBootstrapperRefusesAnInvalidRequestWithoutWriting(t *testing.T, ctx context.Context, fixture BootstrapperFixture) {
|
||||
t.Helper()
|
||||
seedWorkspaceIdentity(t, ctx, fixture, "", "")
|
||||
|
|
@ -224,11 +196,10 @@ func RunBootstrapperRefusesAnInvalidRequestWithoutWriting(t *testing.T, ctx cont
|
|||
// RunBootstrapperLeavesTheSubstrateUntouchedWhenItCannotComplete pins the case
|
||||
// that separates a failure from a refusal.
|
||||
//
|
||||
// A canceled context is the one failure every backend can be made to have. It is
|
||||
// not the only one they will meet in the field, but a body that respects
|
||||
// cancellation on the way in is a body that has not written before it looked —
|
||||
// and the workspace it leaves behind is one the next attempt can still
|
||||
// bootstrap, rather than one the refusal above will reject forever.
|
||||
// A canceled context is the one failure every backend can be made to have. A
|
||||
// body that respects cancellation on the way in has not written before it
|
||||
// looked, so the workspace it leaves behind is one the next attempt can still
|
||||
// bootstrap rather than one the refusal above will reject forever.
|
||||
func RunBootstrapperLeavesTheSubstrateUntouchedWhenItCannotComplete(t *testing.T, ctx context.Context, fixture BootstrapperFixture) {
|
||||
t.Helper()
|
||||
seedWorkspaceIdentity(t, ctx, fixture, "", "")
|
||||
|
|
@ -248,12 +219,10 @@ func RunBootstrapperLeavesTheSubstrateUntouchedWhenItCannotComplete(t *testing.T
|
|||
// RunBootstrapperRecordsAtMostOneHistoryEntry pins bootstrapper.go's "AT MOST
|
||||
// ONE VERSION-CONTROL ENTRY".
|
||||
//
|
||||
// The promise is deliberately an upper bound rather than a number: the identity
|
||||
// lands on planes that travel, so a backend that commits at all is right to
|
||||
// record the bootstrap, and one whose front door commits the whole of `bd init`
|
||||
// afterwards is right to record none. What it forbids is the shape a caller
|
||||
// writing these six values through six ordinary setters gets, which is six
|
||||
// entries.
|
||||
// The promise is an upper bound rather than a number: a backend that commits at
|
||||
// all is right to record the bootstrap, and one whose front door commits the
|
||||
// whole of `bd init` afterwards is right to record none. What it forbids is the
|
||||
// one-entry-per-key shape six ordinary setters would produce.
|
||||
func RunBootstrapperRecordsAtMostOneHistoryEntry(t *testing.T, ctx context.Context, fixture BootstrapperFixture) {
|
||||
t.Helper()
|
||||
if fixture.CountHistory == nil {
|
||||
|
|
@ -282,9 +251,9 @@ func RunBootstrapperRecordsAtMostOneHistoryEntry(t *testing.T, ctx context.Conte
|
|||
// initverifier.go:13-19: "" is a NORMAL ANSWER, not an error and not a missing
|
||||
// row to classify.
|
||||
//
|
||||
// It is the answer the one caller that matters acts on — `bd init` deciding
|
||||
// whether there is anything to adopt — and turning it into ErrNotFound would
|
||||
// make the ordinary case look like a failure.
|
||||
// It is the answer `bd init` acts on when it decides whether there is anything
|
||||
// to adopt, so turning it into ErrNotFound would make the ordinary case look
|
||||
// like a failure.
|
||||
func RunInitVerifierAnswersEmptyForAnUnidentifiedSubstrate(t *testing.T, ctx context.Context, fixture BootstrapperFixture) {
|
||||
t.Helper()
|
||||
seedWorkspaceIdentity(t, ctx, fixture, "", "")
|
||||
|
|
@ -301,12 +270,8 @@ func RunInitVerifierAnswersEmptyForAnUnidentifiedSubstrate(t *testing.T, ctx con
|
|||
// RunInitVerifierReportsAPartialIdentityAsItStands pins the verifier's job on
|
||||
// the state the refusal cases care about: it REPORTS what is there, marker by
|
||||
// marker, rather than collapsing a half-identified substrate into identified or
|
||||
// unidentified.
|
||||
//
|
||||
// That is what lets its caller tell a database a provisioning tool stamped with
|
||||
// a prefix apart from a bootstrap that failed partway — two states with the same
|
||||
// answer to "is this identified?" and different answers to "what should happen
|
||||
// next?".
|
||||
// unidentified. That is what lets its caller tell a database a provisioning tool
|
||||
// stamped with a prefix apart from a bootstrap that failed partway.
|
||||
func RunInitVerifierReportsAPartialIdentityAsItStands(t *testing.T, ctx context.Context, fixture BootstrapperFixture) {
|
||||
t.Helper()
|
||||
seedWorkspaceIdentity(t, ctx, fixture, "acmepartial", "")
|
||||
|
|
@ -340,10 +305,8 @@ func RunInitVerifierReportsAFailedReadAsAnError(t *testing.T, ctx context.Contex
|
|||
}
|
||||
|
||||
// RunInitVerifierWritesNothing pins initverifier.go's "IT WRITES NOTHING",
|
||||
// including the version-control entry: a verifier that repaired or recorded what
|
||||
// it found would be the bootstrap these two roles exist to keep separate, and a
|
||||
// read that committed would put an entry in the log of every workspace `bd init`
|
||||
// merely LOOKED at.
|
||||
// including the version-control entry: a read that committed would put an entry
|
||||
// in the log of every workspace `bd init` merely LOOKED at.
|
||||
func RunInitVerifierWritesNothing(t *testing.T, ctx context.Context, fixture BootstrapperFixture) {
|
||||
t.Helper()
|
||||
if fixture.CountHistory == nil {
|
||||
|
|
@ -397,8 +360,7 @@ func verifyWorkspaceIdentity(t *testing.T, ctx context.Context, fixture Bootstra
|
|||
}
|
||||
|
||||
// assertWorkspaceIdentity reads the pair back THROUGH InitVerifier, which is the
|
||||
// promise being checked: bootstrapper.go says a later VerifyIdentity is what
|
||||
// "bootstrapped" means, and on the unit-of-work backend that read is a new
|
||||
// promise being checked. On the unit-of-work backend that read is a new
|
||||
// transaction — the only place a write that never committed shows up.
|
||||
func assertWorkspaceIdentity(t *testing.T, ctx context.Context, fixture BootstrapperFixture, prefix, projectID string) {
|
||||
t.Helper()
|
||||
|
|
|
|||
|
|
@ -11,16 +11,15 @@ import (
|
|||
)
|
||||
|
||||
// This file holds the contract every implementation of publicops.Counter must
|
||||
// satisfy. Each case asserts what issueops/counter.go PROMISES, cited by line,
|
||||
// rather than what any one backend happens to do today; a backend that
|
||||
// disagrees is parked at its own wiring site with skipKnownDivergence so the
|
||||
// case still runs on the ones that agree.
|
||||
// satisfy. Each case asserts what issueops/counter.go PROMISES, cited by line;
|
||||
// a backend that disagrees is parked at its own wiring site with
|
||||
// skipKnownDivergence so the case still runs on the ones that agree.
|
||||
//
|
||||
// There are three wirings — the server-backed store, the embedded store and
|
||||
// the unit-of-work provider — and, unusually for this suite, only ONE shared
|
||||
// body between any two of them: dolt and embeddeddolt both hand back
|
||||
// internal/workapi/storecounter, so they are one vote plus an engine check,
|
||||
// and the unit-of-work provider is the second. All three build their filter
|
||||
// the unit-of-work provider — but only two independent votes: dolt and
|
||||
// embeddeddolt both hand back internal/workapi/storecounter, so they are one
|
||||
// vote plus an engine check, and the unit-of-work provider is the second. All
|
||||
// three build their filter
|
||||
// through workapi.BuildCountFilter, so what these cases can catch below that
|
||||
// builder is the EXECUTION half — which table each seam counts, how it merges
|
||||
// the wisp tier, and how it names a bucket.
|
||||
|
|
@ -29,9 +28,7 @@ import (
|
|||
// The three fixtures share one database per suite and the two store fixtures
|
||||
// share it with every other role's cases, so an unscoped count would be an
|
||||
// assertion about the whole workspace and would fail the moment a sibling
|
||||
// suite seeded a row. Scoping also makes the expected numbers small enough to
|
||||
// write literally, which is what lets a failure read as "3 rows, want 2"
|
||||
// rather than as two large numbers that differ.
|
||||
// suite seeded a row.
|
||||
//
|
||||
// What is deliberately NOT here:
|
||||
// - the mapping from flags to a request, which is `bd count`'s job and is
|
||||
|
|
@ -44,8 +41,7 @@ import (
|
|||
|
||||
// CounterFixture supplies adapter-specific storage access for the count
|
||||
// assertions. Every field is named and typed exactly like the per-backend
|
||||
// roleFixtureKit hook it is filled from, so a wiring is kit plus accessor plus
|
||||
// prefix with no adapter in between.
|
||||
// roleFixtureKit hook it is filled from.
|
||||
type CounterFixture struct {
|
||||
// IssuePrefix namespaces the ids each assertion seeds, so several of them
|
||||
// can share one database.
|
||||
|
|
@ -59,18 +55,16 @@ type CounterFixture struct {
|
|||
CreateWisp func(context.Context, *types.Issue, string) error
|
||||
// CountHistory reports how many history entries the fixture's branch has.
|
||||
// A nil hook means "this backend cannot observe history", and the case
|
||||
// that needs it SKIPS with that reason rather than passing quietly.
|
||||
// that needs it SKIPS rather than passing quietly.
|
||||
CountHistory func(context.Context) (int, error)
|
||||
}
|
||||
|
||||
// RunCounterCountsTheDurablePlaneByDefault pins counter.go:123-126 from the
|
||||
// unset side: without IncludeInfra a count answers for the durable plane only.
|
||||
//
|
||||
// The wisp seeded here is the half that catches a body that dropped the
|
||||
// SkipWisps default — the merge is the storage seam's DEFAULT (search.go and
|
||||
// count.go both merge unless told not to), so "durable only" is an active
|
||||
// decision this builder makes on every plain count and not something that
|
||||
// falls out of doing nothing.
|
||||
// The wisp seeded here catches a body that dropped the SkipWisps default: the
|
||||
// merge is the storage seam's DEFAULT, so "durable only" is an active decision
|
||||
// this builder makes on every plain count.
|
||||
func RunCounterCountsTheDurablePlaneByDefault(t *testing.T, ctx context.Context, fixture CounterFixture) {
|
||||
t.Helper()
|
||||
durable := fixture.IssuePrefix + "-plane-durable"
|
||||
|
|
@ -84,11 +78,8 @@ func RunCounterCountsTheDurablePlaneByDefault(t *testing.T, ctx context.Context,
|
|||
|
||||
// RunCounterIncludeInfraMergesTheWispTier pins the first of the four things
|
||||
// counter.go:108-117 promises IncludeInfra does at once: the ephemeral tier is
|
||||
// merged in.
|
||||
//
|
||||
// It is the same two seeds the case above uses, deliberately: the pair of
|
||||
// cases is one A/B on a single flag, so a failure names the flag rather than
|
||||
// leaving a reader to compare two differently-seeded fixtures.
|
||||
// merged in. It is the same two seeds the case above uses, deliberately: the
|
||||
// pair of cases is one A/B on a single flag.
|
||||
func RunCounterIncludeInfraMergesTheWispTier(t *testing.T, ctx context.Context, fixture CounterFixture) {
|
||||
t.Helper()
|
||||
durable := fixture.IssuePrefix + "-infra-durable"
|
||||
|
|
@ -110,7 +101,7 @@ func RunCounterIncludeInfraMergesTheWispTier(t *testing.T, ctx context.Context,
|
|||
// The DEFAULT count is asserted first and includes the gate, which is the
|
||||
// asymmetry worth pinning: the exclusion belongs to the --include-infra mode
|
||||
// alone, because that mode exists to match `bd list --include-infra --all`'s
|
||||
// cardinality and a default listing hides gates. A plain count hides nothing.
|
||||
// cardinality.
|
||||
func RunCounterIncludeInfraExcludesGates(t *testing.T, ctx context.Context, fixture CounterFixture) {
|
||||
t.Helper()
|
||||
task := fixture.IssuePrefix + "-gate-task"
|
||||
|
|
@ -134,10 +125,8 @@ func RunCounterIncludeInfraExcludesGates(t *testing.T, ctx context.Context, fixt
|
|||
|
||||
// RunCounterCountsClosedRows pins counter.go:233-235: an empty request counts
|
||||
// every durable row INCLUDING closed ones, because a count applies none of the
|
||||
// listing's default exclusions.
|
||||
//
|
||||
// This is the clause that makes Counter a separate role from Reader rather
|
||||
// than a counted variant of it. A `bd list` of the same two rows shows one.
|
||||
// listing's default exclusions. A `bd list` of the same two rows shows one,
|
||||
// which is what makes Counter a separate role from Reader.
|
||||
func RunCounterCountsClosedRows(t *testing.T, ctx context.Context, fixture CounterFixture) {
|
||||
t.Helper()
|
||||
open := fixture.IssuePrefix + "-status-open"
|
||||
|
|
@ -164,8 +153,7 @@ func RunCounterCountsClosedRows(t *testing.T, ctx context.Context, fixture Count
|
|||
// since dropped reads a zero, and that is the shipped behavior of both front
|
||||
// doors.
|
||||
//
|
||||
// The nil error is the load-bearing half. There is no ErrNotFound on this
|
||||
// role: a question about a set has an answer even when the set is empty.
|
||||
// The nil error is the load-bearing half: there is no ErrNotFound on this role.
|
||||
func RunCounterAnUnknownStatusMatchesNothing(t *testing.T, ctx context.Context, fixture CounterFixture) {
|
||||
t.Helper()
|
||||
anchor := fixture.IssuePrefix + "-unknown-status"
|
||||
|
|
@ -226,10 +214,9 @@ func RunCounterGroupsPartitionTheScalarSet(t *testing.T, ctx context.Context, fi
|
|||
//
|
||||
// This is the one dimension where a caller summing the buckets reports a
|
||||
// workspace larger than it is, and it is why the role computes the total with
|
||||
// a scalar count instead of a SUM. The "(no labels)" bucket is asserted in the
|
||||
// same case because it is the other half of the same query
|
||||
// (countByLabelInTx): a body that dropped it would leave the buckets summing
|
||||
// to LESS than the total, which is the mirror-image failure.
|
||||
// a scalar count instead of a SUM. The "(no labels)" bucket is asserted here
|
||||
// too because a body that dropped it would leave the buckets summing to LESS
|
||||
// than the total, which is the mirror-image failure.
|
||||
func RunCounterLabelBucketsOverlapSoTotalIsNotTheirSum(t *testing.T, ctx context.Context, fixture CounterFixture) {
|
||||
t.Helper()
|
||||
tagged := fixture.IssuePrefix + "-label-tagged"
|
||||
|
|
@ -254,12 +241,9 @@ func RunCounterLabelBucketsOverlapSoTotalIsNotTheirSum(t *testing.T, ctx context
|
|||
|
||||
// RunCounterNamesTheEmptyBuckets pins the two synthesized keys
|
||||
// CountByGroupResult.Groups promises (counter.go:159-161): unassigned rows
|
||||
// bucket under "(unassigned)", never under the empty string.
|
||||
//
|
||||
// The empty string is the failure this guards against and not a hypothetical:
|
||||
// the column holds one for an unassigned row, so a body that skipped the
|
||||
// normalization would produce a map with a "" key that every front door prints
|
||||
// as a blank line with a number after it.
|
||||
// bucket under "(unassigned)", never under the empty string. The column holds
|
||||
// an empty string for an unassigned row, so a body that skipped the
|
||||
// normalization produces a map with a "" key.
|
||||
func RunCounterNamesTheEmptyBuckets(t *testing.T, ctx context.Context, fixture CounterFixture) {
|
||||
t.Helper()
|
||||
assigned := fixture.IssuePrefix + "-assignee-taken"
|
||||
|
|
@ -279,13 +263,9 @@ func RunCounterNamesTheEmptyBuckets(t *testing.T, ctx context.Context, fixture C
|
|||
|
||||
// RunCounterPrefixesPriorityBuckets pins the third normalization
|
||||
// CountByGroupResult.Groups promises (counter.go:157-158): a priority bucket
|
||||
// is "P" followed by the number.
|
||||
//
|
||||
// It matters beyond cosmetics because the key is what both front doors print
|
||||
// and what a JSON consumer keys on. It is also the one bucket whose underlying
|
||||
// column is an integer, so it is the one a body reaches through a CAST — the
|
||||
// step where a backend can come back with "2" where another comes back with
|
||||
// "P2".
|
||||
// is "P" followed by the number. It is the one bucket whose underlying column
|
||||
// is an integer, so it is the one a body reaches through a CAST — the step
|
||||
// where a backend can come back with "2" where another comes back with "P2".
|
||||
func RunCounterPrefixesPriorityBuckets(t *testing.T, ctx context.Context, fixture CounterFixture) {
|
||||
t.Helper()
|
||||
high := fixture.IssuePrefix + "-priority-high"
|
||||
|
|
@ -306,11 +286,9 @@ func RunCounterPrefixesPriorityBuckets(t *testing.T, ctx context.Context, fixtur
|
|||
// CountGroup set is closed, and a value outside it is ErrValidation rather
|
||||
// than an empty answer.
|
||||
//
|
||||
// The empty GroupBy is included because it is the one a caller reaches by
|
||||
// forgetting a field rather than by misspelling one, and because "no dimension"
|
||||
// is not a scalar count in disguise — a caller that wanted a number calls
|
||||
// Count. The refusal is TYPED so both front doors classify it with errors.Is
|
||||
// instead of matching on the storage seam's "unsupported groupBy" prose.
|
||||
// The empty GroupBy is included because "no dimension" is not a scalar count
|
||||
// in disguise. The refusal is TYPED so both front doors classify it with
|
||||
// errors.Is instead of matching on the seam's "unsupported groupBy" prose.
|
||||
func RunCounterRefusesAnUnknownGroup(t *testing.T, ctx context.Context, fixture CounterFixture) {
|
||||
t.Helper()
|
||||
anchor := fixture.IssuePrefix + "-badgroup"
|
||||
|
|
@ -330,12 +308,9 @@ func RunCounterRefusesAnUnknownGroup(t *testing.T, ctx context.Context, fixture
|
|||
// RunCounterNormalizesLabelsAndLeavesTheRequestAlone pins the two halves of
|
||||
// counter.go:76-80 and :217-221 that meet on the same field: label entries are
|
||||
// trimmed and de-duplicated INSIDE, and the caller's slice is not written
|
||||
// through on the way.
|
||||
//
|
||||
// The snapshot half is not free here the way it is for a request of three
|
||||
// strings. CountRequest carries two slices, normalization is exactly the step
|
||||
// that would write through them, and a caller reusing one request for several
|
||||
// counts is the ordinary way to use this role.
|
||||
// through on the way. Normalization is exactly the step that would write
|
||||
// through the caller's slices, and reusing one request for several counts is
|
||||
// the ordinary way to use this role.
|
||||
func RunCounterNormalizesLabelsAndLeavesTheRequestAlone(t *testing.T, ctx context.Context, fixture CounterFixture) {
|
||||
t.Helper()
|
||||
tagged := fixture.IssuePrefix + "-normalize"
|
||||
|
|
@ -368,10 +343,8 @@ func RunCounterNormalizesLabelsAndLeavesTheRequestAlone(t *testing.T, ctx contex
|
|||
// records a history entry, and a refused count does not either.
|
||||
//
|
||||
// It is asserted on the history log rather than on a row read-back because
|
||||
// that is the observable both an accidental commit and an accidental write
|
||||
// would move: every versioned unit of work in this tree ends in a Dolt commit,
|
||||
// so a count that took a write transaction would show up here even when it
|
||||
// changed no column.
|
||||
// every versioned unit of work in this tree ends in a Dolt commit, so a count
|
||||
// that took a write transaction shows up here even when it changed no column.
|
||||
func RunCounterWritesNothing(t *testing.T, ctx context.Context, fixture CounterFixture) {
|
||||
t.Helper()
|
||||
anchor := fixture.IssuePrefix + "-readonly"
|
||||
|
|
@ -394,12 +367,6 @@ func RunCounterWritesNothing(t *testing.T, ctx context.Context, fixture CounterF
|
|||
|
||||
// counterScope is the request every case starts from: a predicate narrowed to
|
||||
// exactly the ids that case seeded.
|
||||
//
|
||||
// It exists because the three fixtures share a database with each other's
|
||||
// cases and, on the two store backends, with every other role's suite. An
|
||||
// unscoped count would assert about the whole workspace and would break the
|
||||
// day a sibling seeded a row, which is a failure that says nothing about the
|
||||
// count.
|
||||
func counterScope(ids ...string) publicops.CountRequest {
|
||||
filter := ""
|
||||
for i, id := range ids {
|
||||
|
|
@ -436,8 +403,7 @@ func seedCounterWisp(t *testing.T, ctx context.Context, fixture CounterFixture,
|
|||
}
|
||||
}
|
||||
|
||||
// counterTotal runs one scalar count and fails the case on an error, because
|
||||
// every caller here has already established that the predicate is well-formed.
|
||||
// counterTotal runs one scalar count and fails the case on an error.
|
||||
func counterTotal(t *testing.T, ctx context.Context, fixture CounterFixture, request publicops.CountRequest) int64 {
|
||||
t.Helper()
|
||||
result, err := fixture.Counter.Count(ctx, request)
|
||||
|
|
@ -480,10 +446,9 @@ func assertCounterBuckets(t *testing.T, got map[string]int, want map[string]int)
|
|||
}
|
||||
}
|
||||
|
||||
// counterHistoryCount reads the branch's history depth, or SKIPS the case with
|
||||
// the reason when the backend cannot observe history at all. A silent pass
|
||||
// would be worse than no case: the read-only clause would look pinned on a
|
||||
// backend that never checked it.
|
||||
// counterHistoryCount reads the branch's history depth, or SKIPS the case when
|
||||
// the backend cannot observe history at all. A silent pass would leave the
|
||||
// read-only clause looking pinned on a backend that never checked it.
|
||||
func counterHistoryCount(t *testing.T, ctx context.Context, fixture CounterFixture) int {
|
||||
t.Helper()
|
||||
if fixture.CountHistory == nil {
|
||||
|
|
|
|||
|
|
@ -16,43 +16,35 @@ import (
|
|||
|
||||
// This file holds the contract every implementation of publicops.CycleDetector
|
||||
// must satisfy. Each case asserts what issueops/cycledetector.go PROMISES,
|
||||
// cited by line, rather than what any one backend happens to do today; a backend
|
||||
// that disagrees is parked at its own wiring site with skipKnownDivergence so
|
||||
// the case still runs on the ones that agree.
|
||||
// cited by line; a backend that disagrees is parked at its own wiring site with
|
||||
// skipKnownDivergence so the case still runs on the ones that agree.
|
||||
//
|
||||
// There are three wirings and TWO INDEPENDENT BODIES. The server-backed and
|
||||
// embedded stores each wrap issueops.DetectCycleReportInTx in five lines around
|
||||
// their own transaction, so they are one vote plus an engine check; the
|
||||
// unit-of-work provider reaches the same function through the domain repository
|
||||
// and is the second. The canonicalization and the partial-hydration rule are
|
||||
// pure functions below all three and are pinned directly, without a database, in
|
||||
// internal/storage/issueops/cycle_report_test.go. What these cases add is
|
||||
// everything the pure tests cannot see: which TABLES each seam reads, whether
|
||||
// the two planes are merged, which edge types are followed, and whether the
|
||||
// hydration finds the same rows the walk named.
|
||||
// pure functions below all three and are pinned without a database in
|
||||
// internal/storage/issueops/cycle_report_test.go. What these cases add is what
|
||||
// the pure tests cannot see: which TABLES each seam reads, whether the two
|
||||
// planes are merged, and which edge types are followed.
|
||||
//
|
||||
// SEEDING A CYCLE TAKES RAW SQL, and that is a fact about the system rather
|
||||
// than a shortcut. Every write path refuses to create one — the editor's
|
||||
// per-edge probe, its whole-graph gate, and the same check inside the storage
|
||||
// seam — so there is no supported verb that produces the state this role
|
||||
// exists to report. Cycles reach a real database by import, by bulk writes, by
|
||||
// concurrent adds that each saw an acyclic graph, and from rows written before
|
||||
// the gate existed. The fixture's Exec hook is how a case reproduces that, and
|
||||
// the INSERT text is written once here rather than three times in the wirings.
|
||||
// than a shortcut: every write path refuses to create one, so no supported verb
|
||||
// produces the state this role exists to report. Cycles reach a real database by
|
||||
// import, by bulk writes, by concurrent adds that each saw an acyclic graph, and
|
||||
// from rows written before the gate existed.
|
||||
//
|
||||
// EVERY CASE SCOPES ITSELF BY MEMBER SET. The report is global — a cycle has no
|
||||
// anchor to filter on — and the fixtures share one database with each other's
|
||||
// cases and, on the two store backends, with every other role's suite. So a case
|
||||
// seeds ids under the fixture prefix and then looks for the ONE reported cycle
|
||||
// whose members are exactly those ids, instead of asserting about the size of
|
||||
// the whole report.
|
||||
// cases. So a case seeds ids under the fixture prefix and then looks for the ONE
|
||||
// reported cycle whose members are exactly those ids.
|
||||
|
||||
// CycleDetectorFixture supplies adapter-specific storage access for the cycle
|
||||
// assertions. Every field but Exec is named and typed exactly like the
|
||||
// per-backend roleFixtureKit hook it is filled from.
|
||||
type CycleDetectorFixture struct {
|
||||
// IssuePrefix namespaces the ids each assertion seeds, so several of them
|
||||
// can share one database.
|
||||
// IssuePrefix namespaces the ids each assertion seeds.
|
||||
IssuePrefix string
|
||||
Detector publicops.CycleDetector
|
||||
// CreateIssue seeds a durable issue in the issues plane.
|
||||
|
|
@ -61,20 +53,19 @@ type CycleDetectorFixture struct {
|
|||
CreateWisp func(context.Context, *types.Issue, string) error
|
||||
// Exec runs every statement IN ORDER ON ONE SESSION, and is the only way to
|
||||
// seed a cycle at all; see the note above. It is NOT a roleFixtureKit hook —
|
||||
// the kit is frozen and exposes reads only — so each wiring supplies its own
|
||||
// short closure over the raw SQL access that backend's tests already use.
|
||||
// the kit is frozen and exposes reads only.
|
||||
//
|
||||
// ONE SESSION is load-bearing rather than a convenience. Seeding an orphaned
|
||||
// edge means turning foreign_key_checks off around the inserts, and that is a
|
||||
// SESSION variable: a hook that took one statement at a time would silently
|
||||
// re-enable the constraint between the toggle and the insert it was for.
|
||||
// ONE SESSION is load-bearing. Seeding an orphaned edge means turning
|
||||
// foreign_key_checks off around the inserts, and that is a SESSION variable:
|
||||
// a hook that took one statement at a time would silently re-enable the
|
||||
// constraint between the toggle and the insert it was for.
|
||||
//
|
||||
// A nil Exec means "this backend cannot seed a cycle", and every case that
|
||||
// needs one SKIPS with that reason rather than passing quietly.
|
||||
Exec func(ctx context.Context, statements []SQLStatement) error
|
||||
// CountHistory reports how many history entries the fixture's branch has. A
|
||||
// nil hook means "this backend cannot observe history", and the case that
|
||||
// needs it SKIPS with that reason.
|
||||
// needs it SKIPS.
|
||||
CountHistory func(context.Context) (int, error)
|
||||
}
|
||||
|
||||
|
|
@ -86,12 +77,9 @@ type SQLStatement struct {
|
|||
|
||||
// RunCycleDetectorReportsNoCycleForAnAcyclicSubgraph pins cycledetector.go:135
|
||||
// from the empty side: an acyclic graph is an empty report and a nil error,
|
||||
// with no ErrNotFound to classify.
|
||||
//
|
||||
// It asserts about the ids it seeded rather than about the size of the whole
|
||||
// report, because the report is global and the sibling cases below deliberately
|
||||
// leave cycles in the database. The nil-slice half IS asserted globally — that
|
||||
// one is a property of the answer, not of the workspace (cycledetector.go:78).
|
||||
// with no ErrNotFound to classify. The nil-slice half IS asserted globally —
|
||||
// that one is a property of the answer, not of the workspace
|
||||
// (cycledetector.go:78).
|
||||
func RunCycleDetectorReportsNoCycleForAnAcyclicSubgraph(t *testing.T, ctx context.Context, fixture CycleDetectorFixture) {
|
||||
t.Helper()
|
||||
first := fixture.IssuePrefix + "-acyclic-a"
|
||||
|
|
@ -116,11 +104,9 @@ func RunCycleDetectorReportsNoCycleForAnAcyclicSubgraph(t *testing.T, ctx contex
|
|||
// (cycledetector.go:63).
|
||||
//
|
||||
// The three ids are seeded so that the edge order and the sorted order are NOT
|
||||
// the same sequence — the walk is entered at the lowest id and the cycle runs
|
||||
// away from it in id order only by accident — which is what makes the rotation
|
||||
// assertion say something. The Issue on each member is checked by TITLE, not
|
||||
// merely for being non-nil: hydration reading the right row is the half a
|
||||
// present-but-wrong pointer would pass.
|
||||
// the same sequence, which is what makes the rotation assertion say something.
|
||||
// The Issue on each member is checked by TITLE: a present-but-wrong pointer
|
||||
// would pass the weaker check.
|
||||
func RunCycleDetectorFindsADurableCycleRotatedToItsLowestID(t *testing.T, ctx context.Context, fixture CycleDetectorFixture) {
|
||||
t.Helper()
|
||||
// b -> c -> a -> b. Rotated to the lowest id the path reads a, b, c.
|
||||
|
|
@ -153,14 +139,13 @@ func RunCycleDetectorFindsADurableCycleRotatedToItsLowestID(t *testing.T, ctx co
|
|||
}
|
||||
|
||||
// RunCycleDetectorReportsTheSameCyclesEveryRun pins cycledetector.go:52-58 and
|
||||
// :91-92 — the ruling that made this commit necessary. Two calls against an
|
||||
// unchanged database must agree, id for id and cycle for cycle.
|
||||
// :91-92: two calls against an unchanged database must agree, id for id and
|
||||
// cycle for cycle.
|
||||
//
|
||||
// It compares the WHOLE report rather than the case's own cycle, because the
|
||||
// failure it guards against is not local: the walk used to iterate a Go map, so
|
||||
// an unrelated cycle elsewhere in the workspace could change which back edges
|
||||
// this one's nodes were reached by. Several calls, because a map with few keys
|
||||
// can iterate the same way twice by chance.
|
||||
// It compares the WHOLE report rather than the case's own cycle: the walk used
|
||||
// to iterate a Go map, so an unrelated cycle elsewhere could change which back
|
||||
// edges this one's nodes were reached by. Several calls, because a map with few
|
||||
// keys can iterate the same way twice by chance.
|
||||
func RunCycleDetectorReportsTheSameCyclesEveryRun(t *testing.T, ctx context.Context, fixture CycleDetectorFixture) {
|
||||
t.Helper()
|
||||
// A branchy fixture: two cycles sharing a node, plus a tail into them, so
|
||||
|
|
@ -191,10 +176,8 @@ func RunCycleDetectorReportsTheSameCyclesEveryRun(t *testing.T, ctx context.Cont
|
|||
|
||||
// RunCycleDetectorMergesTheDurableAndEphemeralPlanes pins
|
||||
// cycledetector.go:120-122: the two dependency planes are one graph, so a cycle
|
||||
// that runs issue → wisp → issue is found.
|
||||
//
|
||||
// This is the clause a single-table read passes every other case and fails here,
|
||||
// and it is why the role cannot be answered by reading `dependencies` alone.
|
||||
// that runs issue → wisp → issue is found. This is the clause a single-table
|
||||
// read passes every other case and fails here.
|
||||
func RunCycleDetectorMergesTheDurableAndEphemeralPlanes(t *testing.T, ctx context.Context, fixture CycleDetectorFixture) {
|
||||
t.Helper()
|
||||
issue := fixture.IssuePrefix + "-plane-issue"
|
||||
|
|
@ -220,10 +203,9 @@ func RunCycleDetectorMergesTheDurableAndEphemeralPlanes(t *testing.T, ctx contex
|
|||
// `waits-for`, whose gate semantics make a mutual wait legitimate, and not
|
||||
// `parent-child`, which the ADD-time gate does walk.
|
||||
//
|
||||
// The conditional-blocks half is asserted in the same case as the two
|
||||
// exclusions on purpose: a body that narrowed the edge set to `blocks` alone
|
||||
// would pass an exclusion-only case, and a body that walked everything would
|
||||
// pass an inclusion-only one.
|
||||
// The conditional-blocks half is asserted in the same case as the exclusions on
|
||||
// purpose: a body narrowed to `blocks` alone would pass an exclusion-only case,
|
||||
// and a body that walked everything would pass an inclusion-only one.
|
||||
func RunCycleDetectorFollowsOnlyBlockingEdges(t *testing.T, ctx context.Context, fixture CycleDetectorFixture) {
|
||||
t.Helper()
|
||||
for _, test := range []struct {
|
||||
|
|
@ -256,11 +238,9 @@ func RunCycleDetectorFollowsOnlyBlockingEdges(t *testing.T, ctx context.Context,
|
|||
|
||||
// RunCycleDetectorReportsAnHonestPartial pins cycledetector.go:140-144 and
|
||||
// :24-33 against real storage: a member the database cannot describe keeps its
|
||||
// place on the path, carries no issue, and marks the cycle.
|
||||
//
|
||||
// The failure it guards against is the shipped one. The previous body dropped
|
||||
// the member, so this three-node cycle came back as a TWO-node cycle and looked
|
||||
// complete; nothing on the wire said a name was missing.
|
||||
// place on the path, carries no issue, and marks the cycle. The previous body
|
||||
// dropped the member, so this three-node cycle came back as a TWO-node cycle and
|
||||
// looked complete.
|
||||
func RunCycleDetectorReportsAnHonestPartial(t *testing.T, ctx context.Context, fixture CycleDetectorFixture) {
|
||||
t.Helper()
|
||||
live := fixture.IssuePrefix + "-partial-a"
|
||||
|
|
@ -294,12 +274,9 @@ func RunCycleDetectorReportsAnHonestPartial(t *testing.T, ctx context.Context, f
|
|||
|
||||
// RunCycleDetectorCountsAWhollyUndescribableCycle pins cycledetector.go:81-85:
|
||||
// a cycle no member of which can be described is still IN the report, so the
|
||||
// count cannot shrink because rows went missing.
|
||||
//
|
||||
// It is the half of the ruling the case above cannot show. Under the previous
|
||||
// body this cycle produced nothing at all — not a shortened path, not a marked
|
||||
// one — so `bd dep cycles` printed a smaller number and a workspace looked
|
||||
// healthier than it was.
|
||||
// count cannot shrink because rows went missing. Under the previous body this
|
||||
// cycle produced nothing at all, so `bd dep cycles` printed a smaller number and
|
||||
// a workspace looked healthier than it was.
|
||||
func RunCycleDetectorCountsAWhollyUndescribableCycle(t *testing.T, ctx context.Context, fixture CycleDetectorFixture) {
|
||||
t.Helper()
|
||||
first := fixture.IssuePrefix + "-ghost-a"
|
||||
|
|
@ -321,12 +298,10 @@ func RunCycleDetectorCountsAWhollyUndescribableCycle(t *testing.T, ctx context.C
|
|||
}
|
||||
|
||||
// RunCycleDetectorWritesNothing pins cycledetector.go:130-131: detecting is a
|
||||
// read. Nothing records a history entry.
|
||||
//
|
||||
// It is asserted on the history log rather than on a row read-back because that
|
||||
// is the observable an accidental commit would move: every versioned unit of
|
||||
// work in this tree ends in a Dolt commit, so a sweep that took a write
|
||||
// transaction would show up here even when it changed no column.
|
||||
// read. It is asserted on the history log rather than on a row read-back
|
||||
// because every versioned unit of work in this tree ends in a Dolt commit, so a
|
||||
// sweep that took a write transaction would show up here even when it changed
|
||||
// no column.
|
||||
func RunCycleDetectorWritesNothing(t *testing.T, ctx context.Context, fixture CycleDetectorFixture) {
|
||||
t.Helper()
|
||||
if fixture.CountHistory == nil {
|
||||
|
|
@ -350,16 +325,13 @@ func RunCycleDetectorWritesNothing(t *testing.T, ctx context.Context, fixture Cy
|
|||
}
|
||||
|
||||
// cycleDetectorEdge is one raw blocking edge a case seeds. The zero value of
|
||||
// every optional field is the ordinary durable, issue-targeted `blocks` edge, so
|
||||
// the common case reads as source and target and nothing else.
|
||||
// every optional field is the ordinary durable, issue-targeted `blocks` edge.
|
||||
type cycleDetectorEdge struct {
|
||||
// Table is "dependencies" (default) or "wisp_dependencies". It follows the
|
||||
// SOURCE's plane, exactly as a real add does.
|
||||
Table string
|
||||
// TargetColumn is the typed column the target id lands in:
|
||||
// depends_on_issue_id (default), depends_on_wisp_id, or depends_on_external.
|
||||
// The graph resolves whichever is set, so this is about fidelity to how a
|
||||
// real row is written rather than about what the walk can read.
|
||||
TargetColumn string
|
||||
Source string
|
||||
Target string
|
||||
|
|
@ -371,16 +343,12 @@ type cycleDetectorEdge struct {
|
|||
//
|
||||
// It writes them all in ONE session because of orphaned: a cycle whose members
|
||||
// are not all rows needs foreign_key_checks off, and that is a session variable.
|
||||
// The constraint is real, and it is what makes an orphaned member hard to
|
||||
// produce on purpose — dependencies.issue_id references issues(id) and
|
||||
// wisp_dependencies.issue_id references wisps(id), both ON DELETE CASCADE — so a
|
||||
// live database reaches this state only the way it actually does: an import, a
|
||||
// clone, or a migration that wrote with the checks off.
|
||||
// The constraint is real — dependencies.issue_id references issues(id) and
|
||||
// wisp_dependencies.issue_id references wisps(id), both ON DELETE CASCADE.
|
||||
//
|
||||
// Each edge's primary key is derived from the edge rather than random, so that
|
||||
// re-running a suite against a surviving database is idempotent instead of a
|
||||
// duplicate-key failure, and hashed because the column is CHAR(36) and the ids
|
||||
// are not.
|
||||
// re-running a suite against a surviving database is idempotent, and hashed
|
||||
// because the column is CHAR(36) and the ids are not.
|
||||
func seedCycleDetectorEdges(t *testing.T, ctx context.Context, fixture CycleDetectorFixture, orphaned bool, edges ...cycleDetectorEdge) {
|
||||
t.Helper()
|
||||
if fixture.Exec == nil {
|
||||
|
|
@ -445,7 +413,7 @@ func seedCycleDetectorWisp(t *testing.T, ctx context.Context, fixture CycleDetec
|
|||
}
|
||||
|
||||
// cycleDetectorSeed titles each row with its own id, so a hydration assertion
|
||||
// can tell "the right row" from "a row".
|
||||
// can tell the right row from a row.
|
||||
func cycleDetectorSeed(id string) *types.Issue {
|
||||
return &types.Issue{
|
||||
ID: id,
|
||||
|
|
@ -466,7 +434,7 @@ func cycleDetectorReport(t *testing.T, ctx context.Context, fixture CycleDetecto
|
|||
}
|
||||
|
||||
// cycleDetectorPaths renders a report as id paths, which is what the
|
||||
// determinism case compares and what a failure message can be read from.
|
||||
// determinism case compares.
|
||||
func cycleDetectorPaths(report publicops.CycleReport) [][]string {
|
||||
out := make([][]string, 0, len(report.Cycles))
|
||||
for _, cycle := range report.Cycles {
|
||||
|
|
@ -480,11 +448,9 @@ func cycleDetectorPaths(report publicops.CycleReport) [][]string {
|
|||
}
|
||||
|
||||
// cycleDetectorFind returns the one reported cycle whose members are exactly
|
||||
// ids, and fails the case when there is not exactly one.
|
||||
//
|
||||
// Matching on the whole member SET rather than on containment is what makes the
|
||||
// scoping honest: a body that added a node to the path, or dropped one, does not
|
||||
// quietly satisfy a containment check.
|
||||
// ids, and fails the case when there is not exactly one. Matching on the whole
|
||||
// member SET rather than on containment is what makes the scoping honest: a
|
||||
// body that added a node to the path, or dropped one, does not pass.
|
||||
func cycleDetectorFind(t *testing.T, report publicops.CycleReport, ids ...string) publicops.Cycle {
|
||||
t.Helper()
|
||||
want := slices.Sorted(slices.Values(ids))
|
||||
|
|
@ -507,8 +473,7 @@ func cycleDetectorFind(t *testing.T, report publicops.CycleReport, ids ...string
|
|||
}
|
||||
|
||||
// cycleDetectorTouching returns the paths of every reported cycle that mentions
|
||||
// any of ids, for the cases that assert a cycle is ABSENT. It reports the paths
|
||||
// rather than a count so a failure names what it found.
|
||||
// any of ids, for the cases that assert a cycle is ABSENT.
|
||||
func cycleDetectorTouching(report publicops.CycleReport, ids ...string) [][]string {
|
||||
var out [][]string
|
||||
for _, path := range cycleDetectorPaths(report) {
|
||||
|
|
@ -519,10 +484,9 @@ func cycleDetectorTouching(report publicops.CycleReport, ids ...string) [][]stri
|
|||
return out
|
||||
}
|
||||
|
||||
// assertCycleDetectorPath checks a cycle's path against the expected edge order
|
||||
// after canonical rotation, which the caller states in edge order starting
|
||||
// anywhere. It rotates the expectation itself, so a case can spell the cycle the
|
||||
// way it seeded it and still assert the canonical answer.
|
||||
// assertCycleDetectorPath checks a cycle's path against the expected edge
|
||||
// order, which the caller may state starting anywhere: it rotates the
|
||||
// expectation itself.
|
||||
func assertCycleDetectorPath(t *testing.T, cycle publicops.Cycle, edgeOrder ...string) {
|
||||
t.Helper()
|
||||
lowest := 0
|
||||
|
|
|
|||
|
|
@ -24,30 +24,18 @@ import (
|
|||
// domain use cases and is genuinely separate code. So the wirings are one vote
|
||||
// plus an engine check, and a second independent vote.
|
||||
//
|
||||
// WHAT THE AUDIT SUITE ALREADY COVERS, AND WHY THIS IS NOT A SECOND COPY OF IT.
|
||||
// backend/conformance/audit_issue-lifecycle.go pins cascade, force, the orphan
|
||||
// guard and the dry-run counts at the STORAGE SEAM — `DeleteIssues` on
|
||||
// storage.DoltStorage — and it stays the right home for that method, which
|
||||
// `bd gc`, `bd wisp` and the sweeper still call directly. It cannot see the
|
||||
// role: its Factory hands back a bare storage.DoltStorage, so the unit-of-work
|
||||
// provider — the backend where the guard did not exist at all before this
|
||||
// commit — never runs a case placed there. The cases below are therefore
|
||||
// deliberately NOT that method's cases repeated: they are about the promises
|
||||
// the ROLE adds on top of it, which the storage seam has no opinion on —
|
||||
// id normalization, the ordered refusals, the typed errors, the reference
|
||||
// rewrite inside the transaction, and the history entry.
|
||||
// guard and the dry-run counts at the STORAGE SEAM, and cannot see the role at
|
||||
// all. The cases below are the promises the ROLE adds on top of it: id
|
||||
// normalization, the ordered refusals, the typed errors, the reference rewrite
|
||||
// inside the transaction, and the history entry.
|
||||
//
|
||||
// EVERY CASE NAMESPACES ITS SEEDS with fixture.IssuePrefix and its own tag,
|
||||
// because the three wirings share one database across the whole role suite and
|
||||
// a delete is one of the two operations here that can destroy another case's
|
||||
// fixture. Unlike the sweeper's cases they do not need a pattern to scope the
|
||||
// OPERATION — a delete only ever touches ids it was handed — so the namespacing
|
||||
// is about collisions rather than about blast radius.
|
||||
// EVERY CASE NAMESPACES ITS SEEDS with fixture.IssuePrefix and its own tag: the
|
||||
// three wirings share one database across the whole role suite, and a delete
|
||||
// can destroy another case's fixture.
|
||||
|
||||
// DeleterFixture supplies adapter-specific storage access for the named-row
|
||||
// erasure assertions. Every field is named and typed exactly like the
|
||||
// per-backend roleFixtureKit hook it is filled from, so a wiring is kit plus
|
||||
// accessor plus prefix with no adapter in between.
|
||||
// erasure assertions.
|
||||
type DeleterFixture struct {
|
||||
// IssuePrefix namespaces the ids each assertion seeds, so several of them
|
||||
// can share one database.
|
||||
|
|
@ -59,11 +47,10 @@ type DeleterFixture struct {
|
|||
// CreateWisp seeds an ephemeral issue in the wisps plane.
|
||||
CreateWisp func(context.Context, *types.Issue, string) error
|
||||
// AddDependency seeds ONE edge, routed to the plane the edge's SOURCE
|
||||
// lives in. It is what makes a dependent, which is what this role's guard
|
||||
// is about.
|
||||
// lives in.
|
||||
AddDependency func(context.Context, *types.Dependency, string) error
|
||||
// QueryScalar runs a single-row query and scans it. It is how these cases
|
||||
// observe the ONE thing a delete result cannot be trusted to report about
|
||||
// check the one thing a delete result cannot be trusted to report about
|
||||
// itself: whether the rows are really gone.
|
||||
QueryScalar func(context.Context, string, []any, ...any) error
|
||||
// CountHistory reports how many history entries the fixture's branch has.
|
||||
|
|
@ -76,9 +63,9 @@ type DeleterFixture struct {
|
|||
// database (issueops/deleter.go, DeleteRequest.IDs: "an empty or all-blank
|
||||
// slice is ErrValidation rather than a no-op").
|
||||
//
|
||||
// A no-op would be the dangerous answer here rather than merely a sloppy one:
|
||||
// a caller whose id list came out empty because its own construction broke
|
||||
// would read "deleted 0" and conclude the workspace was already clean.
|
||||
// A no-op is the dangerous answer, not merely the sloppy one: a caller whose id
|
||||
// list came out empty because its own construction broke would read "deleted 0"
|
||||
// and conclude the workspace was already clean.
|
||||
func RunDeleterRefusesAMalformedRequest(t *testing.T, ctx context.Context, fixture DeleterFixture) {
|
||||
t.Helper()
|
||||
for _, test := range []struct {
|
||||
|
|
@ -109,10 +96,8 @@ func RunDeleterRefusesAMalformedRequest(t *testing.T, ctx context.Context, fixtu
|
|||
//
|
||||
// It is asserted with a REAL id beside the typo, because that is the only
|
||||
// arrangement that can fail: an implementation that deleted as it resolved
|
||||
// would pass a single-absent-id case perfectly and still have erased the row
|
||||
// this one seeds. And it is asserted under DryRun too, because the leaf
|
||||
// promises a preview refuses where the real run refuses — a preview that
|
||||
// succeeded here would tell a caller to go ahead.
|
||||
// would pass a single-absent-id case perfectly. And under DryRun too, because a
|
||||
// preview that succeeded here would tell a caller to go ahead.
|
||||
func RunDeleterRefusesAnAbsentID(t *testing.T, ctx context.Context, fixture DeleterFixture) {
|
||||
t.Helper()
|
||||
stored := deleterSeedIssue(t, ctx, fixture, "gone", "real")
|
||||
|
|
@ -147,10 +132,9 @@ func RunDeleterRefusesAnAbsentID(t *testing.T, ctx context.Context, fixture Dele
|
|||
// refused"), and the exception beside it: a dependent the request DID name is
|
||||
// not a dependent for this purpose.
|
||||
//
|
||||
// The refusal is asserted with its EFFECT as well as its type. A guard that
|
||||
// The refusal is asserted with its EFFECT as well as its type: a guard that
|
||||
// returned the error after deleting would satisfy an errors.Is assertion
|
||||
// perfectly, and on this operation that is the failure worth spending seeded
|
||||
// rows to rule out.
|
||||
// perfectly.
|
||||
func RunDeleterRefusesDependentsOutsideTheRequest(t *testing.T, ctx context.Context, fixture DeleterFixture) {
|
||||
t.Helper()
|
||||
blocker := deleterSeedIssue(t, ctx, fixture, "guard", "blocker")
|
||||
|
|
@ -196,13 +180,9 @@ func RunDeleterRefusesDependentsOutsideTheRequest(t *testing.T, ctx context.Cont
|
|||
|
||||
// RunDeleterForceOrphansDependents pins what --force MEANS after this commit
|
||||
// (issueops/deleter.go, DeleteRequest.Force: "deletes the named rows and leaves
|
||||
// rows that depended on them ORPHANED"), and it is the case that would have
|
||||
// caught the drift this commit removes: the proxied route used to hardcode
|
||||
// cascade, so `--force` there deleted the dependent instead of orphaning it.
|
||||
//
|
||||
// DeleteResult.Orphaned is asserted alongside the surviving row, because the
|
||||
// number a caller acts on and the row that is actually there are two different
|
||||
// claims and only one of them was ever true on that route.
|
||||
// rows that depended on them ORPHANED"). It is the case that catches the drift
|
||||
// this commit removes: the proxied route used to hardcode cascade, so `--force`
|
||||
// there deleted the dependent instead of orphaning it.
|
||||
func RunDeleterForceOrphansDependents(t *testing.T, ctx context.Context, fixture DeleterFixture) {
|
||||
t.Helper()
|
||||
blocker := deleterSeedIssue(t, ctx, fixture, "force", "blocker")
|
||||
|
|
@ -229,11 +209,9 @@ func RunDeleterForceOrphansDependents(t *testing.T, ctx context.Context, fixture
|
|||
// RunDeleterCascadeDeletesTheClosure pins the other mode (issueops/deleter.go,
|
||||
// DeleteRequest.Cascade) over a chain rather than a single edge, because
|
||||
// "transitive" is the whole claim and a one-edge fixture cannot tell a
|
||||
// transitive expansion from a direct one.
|
||||
//
|
||||
// It also pins the interaction the leaf spells out: a request carrying BOTH
|
||||
// Cascade and Force is legal and behaves as Cascade, with Orphaned empty —
|
||||
// there is nothing left outside the closure to orphan.
|
||||
// transitive expansion from a direct one. It also pins the interaction the leaf
|
||||
// spells out: a request carrying BOTH Cascade and Force is legal and behaves as
|
||||
// Cascade.
|
||||
func RunDeleterCascadeDeletesTheClosure(t *testing.T, ctx context.Context, fixture DeleterFixture) {
|
||||
t.Helper()
|
||||
root := deleterSeedIssue(t, ctx, fixture, "casc", "root")
|
||||
|
|
@ -263,12 +241,10 @@ func RunDeleterCascadeDeletesTheClosure(t *testing.T, ctx context.Context, fixtu
|
|||
// TRANSITIVE CLOSURE of everything that depends on the named rows, IN BOTH
|
||||
// PLANES").
|
||||
//
|
||||
// RunDeleterCascadeDeletesTheClosure above proves the closure over a durable
|
||||
// chain and ErasesAcrossBothPlanes proves a mixed request over an EDGE-FREE
|
||||
// pair, so between them nothing asserted what a cascade rooted at a WISP does
|
||||
// to the durable rows hanging off it. That gap is not academic: `bd wisp gc`
|
||||
// deletes wisps with cascade hardcoded, so this is the quadrant routine
|
||||
// housekeeping runs through.
|
||||
// The other cascade cases are durable-only or edge-free, so nothing else
|
||||
// asserts what a cascade rooted at a WISP does to the durable rows hanging off
|
||||
// it. `bd wisp gc` deletes wisps with cascade hardcoded, so routine
|
||||
// housekeeping runs through this quadrant.
|
||||
//
|
||||
// The chain is two edges deep on purpose, and its second link is durable, so
|
||||
// this cannot be satisfied by a body that merely follows one cross-plane edge.
|
||||
|
|
@ -299,14 +275,11 @@ func RunDeleterCascadeFromAWispRootDeletesTheClosure(t *testing.T, ctx context.C
|
|||
// "WITHOUT Cascade AND WITHOUT Force, a NAMED ROW that some row OUTSIDE the
|
||||
// request depends on is refused" — a named row, not a named durable row).
|
||||
//
|
||||
// RunDeleterRefusesDependentsOutsideTheRequest and
|
||||
// RunDeleterForceOrphansDependents are both durable-only, so a body that
|
||||
// partitioned the request and asked the guard only about the durable half
|
||||
// passed them while silently orphaning a workspace's graph through the other
|
||||
// half. Both halves of the clause are asserted here — the unforced refusal and
|
||||
// the forced orphan report — because a body that reported the orphan without
|
||||
// refusing, or refused without reporting, is wrong in a different direction
|
||||
// and the two share one scan.
|
||||
// The other two guard cases are durable-only, so a body that partitioned the
|
||||
// request and asked the guard only about the durable half passed them while
|
||||
// silently orphaning a workspace's graph through the other half. Both halves of
|
||||
// the clause are asserted here — the unforced refusal and the forced orphan
|
||||
// report — because a body can get either one right on its own.
|
||||
func RunDeleterGuardsAWispNamedWithADurableDependent(t *testing.T, ctx context.Context, fixture DeleterFixture) {
|
||||
t.Helper()
|
||||
wisp := deleterSeedWisp(t, ctx, fixture, "wguard", "wisp")
|
||||
|
|
@ -350,8 +323,6 @@ func RunDeleterGuardsAWispNamedWithADurableDependent(t *testing.T, ctx context.C
|
|||
}
|
||||
deleterAssertWispRows(t, ctx, fixture, 0, wisp)
|
||||
deleterAssertIssueRows(t, ctx, fixture, 1, dependent)
|
||||
// The orphan loses its cross-plane edge with the wisp it pointed at; a
|
||||
// surviving edge into a deleted wisp would be dangling rather than orphaned.
|
||||
deleterAssertEdgeRows(t, ctx, fixture, 0, dependent, wisp)
|
||||
}
|
||||
|
||||
|
|
@ -362,8 +333,7 @@ func RunDeleterGuardsAWispNamedWithADurableDependent(t *testing.T, ctx context.C
|
|||
//
|
||||
// The two bodies scan different tables to answer it, so this is one of the few
|
||||
// places three green legs really would be two independent votes — and neither
|
||||
// was being taken. It is the shape of the defect wave 4 fixed: a guard that
|
||||
// asked about the durable half only, with 59 cases green.
|
||||
// was being taken.
|
||||
func RunDeleterGuardsADurableNamedWithAWispDependent(t *testing.T, ctx context.Context, fixture DeleterFixture) {
|
||||
t.Helper()
|
||||
blocker := deleterSeedIssue(t, ctx, fixture, "dguard", "durable blocker")
|
||||
|
|
@ -412,22 +382,17 @@ func RunDeleterGuardsADurableNamedWithAWispDependent(t *testing.T, ctx context.C
|
|||
|
||||
// RunDeleterNeverCallsALiveRowDeleted pins the invariant that makes the
|
||||
// under-deleting cascade impossible to reintroduce quietly: THE SET WHOSE
|
||||
// CITATIONS ARE REWRITTEN IS THE SET THAT WAS DELETED. A `[deleted:<id>]`
|
||||
// marker in a surviving row is a claim about the workspace, and this case
|
||||
// checks the claim against the rows.
|
||||
// CITATIONS ARE REWRITTEN IS THE SET THAT WAS DELETED.
|
||||
//
|
||||
// It is written as a biconditional rather than a count, because the counts
|
||||
// cannot see it: an implementation whose rewrite set is a strict SUPERSET of
|
||||
// its deletion set reports a perfectly plausible ReferencesUpdated and leaves
|
||||
// a neighbor's description saying a LIVE issue is gone. No other case here
|
||||
// reads a surviving row's text back and compares it against what is actually
|
||||
// stored.
|
||||
// a neighbor's description saying a LIVE issue is gone.
|
||||
//
|
||||
// The fixture is the cheapest arrangement in which the two sets can differ: a
|
||||
// wisp root, a durable row reachable only through it, and a third row that the
|
||||
// durable one DEPENDS ON — so the third row is a graph neighbor of the deletion
|
||||
// set (its text is in scope for the rewrite) without being a dependent of
|
||||
// anything (so it is never in the closure and always survives).
|
||||
// durable one DEPENDS ON — a graph neighbor of the deletion set (in scope for
|
||||
// the rewrite) that is never in the closure, so it always survives.
|
||||
func RunDeleterNeverCallsALiveRowDeleted(t *testing.T, ctx context.Context, fixture DeleterFixture) {
|
||||
t.Helper()
|
||||
root := deleterSeedWisp(t, ctx, fixture, "live", "root")
|
||||
|
|
@ -470,13 +435,9 @@ func RunDeleterNeverCallsALiveRowDeleted(t *testing.T, ctx context.Context, fixt
|
|||
}
|
||||
|
||||
// RunDeleterErasesAcrossBothPlanes pins that one request reaches BOTH tiers
|
||||
// (issueops/deleter.go, DeleteRequest.IDs: "in either plane").
|
||||
//
|
||||
// It is the case the storage seam's own suite cannot stand in for, because the
|
||||
// role is where a front door's mixed id list arrives: `bd delete` takes
|
||||
// whatever ids the caller names and one `--from-file` batch may legitimately
|
||||
// mix a wisp with an issue. A body that routed the whole request by one flag
|
||||
// would delete the issue and silently report the wisp as gone.
|
||||
// (issueops/deleter.go, DeleteRequest.IDs: "in either plane"). One `--from-file`
|
||||
// batch may legitimately mix a wisp with an issue, and a body that routed the
|
||||
// whole request by one flag would silently report the wisp as gone.
|
||||
func RunDeleterErasesAcrossBothPlanes(t *testing.T, ctx context.Context, fixture DeleterFixture) {
|
||||
t.Helper()
|
||||
issue := deleterSeedIssue(t, ctx, fixture, "plane", "issue")
|
||||
|
|
@ -517,9 +478,9 @@ func RunDeleterCollapsesDuplicateIDs(t *testing.T, ctx context.Context, fixture
|
|||
// becomes `[deleted:<id>]`, matched at word boundaries.
|
||||
//
|
||||
// The NEGATIVE half is the half worth having. A neighbor also cites an id that
|
||||
// merely has the deleted one as a PREFIX, and that citation must survive
|
||||
// untouched: a rewrite that used a bare substring match would corrupt a
|
||||
// bystander's text on every delete, and no count in the result would show it.
|
||||
// merely has the deleted one as a PREFIX, and that citation must survive: a
|
||||
// bare substring match would corrupt a bystander's text on every delete, and no
|
||||
// count in the result would show it.
|
||||
func RunDeleterRewritesReferencesInNeighbors(t *testing.T, ctx context.Context, fixture DeleterFixture) {
|
||||
t.Helper()
|
||||
target := deleterSeedIssue(t, ctx, fixture, "refs", "target")
|
||||
|
|
@ -573,9 +534,9 @@ func RunDeleterRewritesReferencesInNeighbors(t *testing.T, ctx context.Context,
|
|||
// preview reports the counts the real deletion goes on to report, rewrites
|
||||
// nothing, and leaves every row where it was.
|
||||
//
|
||||
// The two are compared against EACH OTHER rather than against literals, which
|
||||
// is the property a caller actually relies on — a preview whose number differs
|
||||
// from the run it precedes is worse than no preview.
|
||||
// The two are compared against EACH OTHER rather than against literals: a
|
||||
// preview whose number differs from the run it precedes is worse than no
|
||||
// preview.
|
||||
func RunDeleterDryRunChangesNothing(t *testing.T, ctx context.Context, fixture DeleterFixture) {
|
||||
t.Helper()
|
||||
first := deleterSeedIssue(t, ctx, fixture, "dry", "1")
|
||||
|
|
@ -642,11 +603,9 @@ func RunDeleterRecordsAtMostOneHistoryEntry(t *testing.T, ctx context.Context, f
|
|||
// (issueops/deleter.go, DeleteRequest: "IDs is read, never written through, and
|
||||
// never sorted in place").
|
||||
//
|
||||
// It matters more here than on the roles whose requests are scalars: every
|
||||
// implementation NORMALIZES the id slice, and normalizing in place is the most
|
||||
// natural way to write that — it would hand the caller back a shorter, trimmed,
|
||||
// reordered version of the list it passed, which is the list a CLI then echoes
|
||||
// in its confirmation hint.
|
||||
// Every implementation NORMALIZES the id slice, and normalizing in place would
|
||||
// hand the caller back a shorter, trimmed, reordered version of the list it
|
||||
// passed — the list a CLI then echoes in its confirmation hint.
|
||||
func RunDeleterDoesNotMutateTheCallerRequest(t *testing.T, ctx context.Context, fixture DeleterFixture) {
|
||||
t.Helper()
|
||||
id := deleterSeedIssue(t, ctx, fixture, "immutable", "target")
|
||||
|
|
@ -701,15 +660,13 @@ func deleterSeedIssue(t *testing.T, ctx context.Context, fixture DeleterFixture,
|
|||
return deleterSeed(t, ctx, fixture, deleterIssue(fixture, tag, name, false))
|
||||
}
|
||||
|
||||
// deleterSeedWisp is its ephemeral sibling, used by the one case that is
|
||||
// about which PLANE a row lives in.
|
||||
// deleterSeedWisp is its ephemeral sibling.
|
||||
func deleterSeedWisp(t *testing.T, ctx context.Context, fixture DeleterFixture, tag, name string) string {
|
||||
t.Helper()
|
||||
return deleterSeed(t, ctx, fixture, deleterIssue(fixture, tag, name, true))
|
||||
}
|
||||
|
||||
// deleterAddEdge makes dependent depend on blocker, which is what makes
|
||||
// dependent a DEPENDENT of blocker for this role's guard.
|
||||
// deleterAddEdge makes dependent depend on blocker.
|
||||
func deleterAddEdge(t *testing.T, ctx context.Context, fixture DeleterFixture, dependent, blocker string) {
|
||||
t.Helper()
|
||||
err := fixture.AddDependency(ctx, &types.Dependency{
|
||||
|
|
@ -736,9 +693,8 @@ func deleterDelete(t *testing.T, ctx context.Context, fixture DeleterFixture, re
|
|||
return result
|
||||
}
|
||||
|
||||
// deleterAssertIssueRows counts the named ids in the ISSUES plane. It is the
|
||||
// assertion that does not trust the result the delete reported about itself,
|
||||
// which on a destructive operation is the one that matters.
|
||||
// deleterAssertIssueRows counts the named ids in the ISSUES plane, rather than
|
||||
// trusting the result the delete reported about itself.
|
||||
func deleterAssertIssueRows(t *testing.T, ctx context.Context, fixture DeleterFixture, want int, ids ...string) {
|
||||
t.Helper()
|
||||
placeholders := make([]string, len(ids))
|
||||
|
|
@ -777,8 +733,7 @@ func deleterAssertWispRows(t *testing.T, ctx context.Context, fixture DeleterFix
|
|||
}
|
||||
|
||||
// deleterRowCount REPORTS how many rows one id has in one plane instead of
|
||||
// asserting a number, for the case whose assertion depends on which answer the
|
||||
// implementation gave.
|
||||
// asserting a number, for the case whose assertion depends on the answer.
|
||||
//
|
||||
//nolint:gosec // G201: table is chosen by the caller from the two plane tables.
|
||||
func deleterRowCount(t *testing.T, ctx context.Context, fixture DeleterFixture, table, id string) int {
|
||||
|
|
@ -805,9 +760,8 @@ func deleterAssertEdgeRows(t *testing.T, ctx context.Context, fixture DeleterFix
|
|||
}
|
||||
}
|
||||
|
||||
// deleterText reads one long text column straight out of the issues table,
|
||||
// because the rewrite is a claim about stored bytes rather than about anything
|
||||
// the role reports.
|
||||
// deleterText reads one long text column straight out of the issues table: the
|
||||
// rewrite is a claim about stored bytes, not about anything the role reports.
|
||||
//
|
||||
//nolint:gosec // G201: column is chosen by the caller from a fixed set of four.
|
||||
func deleterText(t *testing.T, ctx context.Context, fixture DeleterFixture, id, column string) string {
|
||||
|
|
|
|||
|
|
@ -11,9 +11,8 @@ import (
|
|||
|
||||
// This file holds the contract every implementation of publicops.EdgeReader
|
||||
// must satisfy. Each case asserts what issueops/edgereader.go PROMISES, cited
|
||||
// by line, rather than what any one backend happens to do today; a backend that
|
||||
// disagrees is parked at its own wiring site with skipKnownDivergence so the
|
||||
// case still runs on the ones that agree.
|
||||
// by line; a backend that disagrees is parked at its own wiring site with
|
||||
// skipKnownDivergence so the case still runs on the ones that agree.
|
||||
//
|
||||
// There are three wirings — the server-backed store, the embedded store and the
|
||||
// unit-of-work provider — and TWO BODIES, not three. dolt and embeddeddolt both
|
||||
|
|
@ -23,16 +22,13 @@ import (
|
|||
// batched by-id use-case reads instead of a batched EXISTS over the two tables.
|
||||
// What all three share is ValidateEdgeReadRequest, EdgeReadAnchors and
|
||||
// FinishEdgeRead — the request rules, the de-duplication and the ordering — so
|
||||
// what these cases can catch below those three is the EXECUTION half: which
|
||||
// plane each seam probes, which table it reads edges from, and whether the two
|
||||
// see one snapshot.
|
||||
// what these cases catch below those three is the EXECUTION half.
|
||||
//
|
||||
// EVERY CASE NAMES THE EXACT IDS IT SEEDED. The three fixtures share one
|
||||
// database per suite and the two store fixtures share it with every other
|
||||
// role's cases, so an assertion that read "every anchor" would be an assertion
|
||||
// about the whole workspace and would fail the moment a sibling suite seeded a
|
||||
// row. Naming the anchors also keeps the expected answers small enough to write
|
||||
// literally.
|
||||
// row.
|
||||
//
|
||||
// What is deliberately NOT here:
|
||||
// - the mapping from `bd dep list`'s arguments to a request, which is the
|
||||
|
|
@ -44,8 +40,7 @@ import (
|
|||
|
||||
// EdgeReaderFixture supplies adapter-specific storage access for the
|
||||
// stored-edge assertions. Every field is named and typed exactly like the
|
||||
// per-backend roleFixtureKit hook it is filled from, so a wiring is kit plus
|
||||
// accessor plus prefix with no adapter in between.
|
||||
// per-backend roleFixtureKit hook it is filled from.
|
||||
type EdgeReaderFixture struct {
|
||||
// IssuePrefix namespaces the ids each assertion seeds, so several of them
|
||||
// can share one database.
|
||||
|
|
@ -62,17 +57,15 @@ type EdgeReaderFixture struct {
|
|||
AddDependency func(context.Context, *types.Dependency, string) error
|
||||
// CountHistory reports how many history entries the fixture's branch has.
|
||||
// A nil hook means "this backend cannot observe history", and the case that
|
||||
// needs it SKIPS with that reason rather than passing quietly.
|
||||
// needs it SKIPS rather than passing quietly.
|
||||
CountHistory func(context.Context) (int, error)
|
||||
}
|
||||
|
||||
// RunEdgeReaderAnswersOnePerAnchorInRequestOrder pins edgereader.go:127-133:
|
||||
// one entry per requested id, in the order the request named them.
|
||||
//
|
||||
// The ids are seeded in the REVERSE of the order the request asks for them, so
|
||||
// a body that returned the storage seam's natural order — which is ascending by
|
||||
// source id, because that is what the batched read's ORDER BY gives — would
|
||||
// fail here rather than passing by coincidence.
|
||||
// one entry per requested id, in the order the request named them. The ids are
|
||||
// seeded in the REVERSE of that order, so a body that answered in the storage
|
||||
// seam's natural order (ascending by source id) fails rather than passing by
|
||||
// coincidence.
|
||||
func RunEdgeReaderAnswersOnePerAnchorInRequestOrder(t *testing.T, ctx context.Context, fixture EdgeReaderFixture) {
|
||||
t.Helper()
|
||||
first := fixture.IssuePrefix + "-order-c"
|
||||
|
|
@ -88,9 +81,9 @@ func RunEdgeReaderAnswersOnePerAnchorInRequestOrder(t *testing.T, ctx context.Co
|
|||
// edgereader.go:45-48 and :188-191 together: a miss is reported ON THE ANCHOR
|
||||
// and the call still succeeds, so the anchors that were found still come back.
|
||||
//
|
||||
// The ghost is named BETWEEN two real anchors deliberately. A body that
|
||||
// short-circuited on the first miss would still return the first anchor, and a
|
||||
// case whose ghost came last would not tell the two apart.
|
||||
// The ghost is named BETWEEN two real anchors deliberately: a case whose ghost
|
||||
// came last could not tell a correct body from one that short-circuited on the
|
||||
// first miss.
|
||||
func RunEdgeReaderReportsAMissingAnchorRatherThanFailing(t *testing.T, ctx context.Context, fixture EdgeReaderFixture) {
|
||||
t.Helper()
|
||||
real1 := fixture.IssuePrefix + "-ghost-real1"
|
||||
|
|
@ -105,10 +98,10 @@ func RunEdgeReaderReportsAMissingAnchorRatherThanFailing(t *testing.T, ctx conte
|
|||
assertEdgeReaderMissing(t, result, real2, false)
|
||||
}
|
||||
|
||||
// RunEdgeReaderDistinguishesNoEdgesFromNoAnchor pins edgereader.go:104-115 —
|
||||
// the whole reason the flag exists. An issue with no dependencies is the COMMON
|
||||
// case, so a body that reported presence from "did any edges come back" would
|
||||
// pass every other case in this file and fail only here.
|
||||
// RunEdgeReaderDistinguishesNoEdgesFromNoAnchor pins edgereader.go:104-115. An
|
||||
// issue with no dependencies is the COMMON case, so a body that reported
|
||||
// presence from "did any edges come back" would pass every other case in this
|
||||
// file and fail only here.
|
||||
func RunEdgeReaderDistinguishesNoEdgesFromNoAnchor(t *testing.T, ctx context.Context, fixture EdgeReaderFixture) {
|
||||
t.Helper()
|
||||
bare := fixture.IssuePrefix + "-bare-present"
|
||||
|
|
@ -137,8 +130,7 @@ func RunEdgeReaderDistinguishesNoEdgesFromNoAnchor(t *testing.T, ctx context.Con
|
|||
// This is the sharpest difference from Relations, which drops such an edge
|
||||
// because it has no far end to hydrate. Two flavors are seeded — an
|
||||
// "external:" reference and a dangling id in another repository's prefix —
|
||||
// because they take different typed target columns and a body that read only
|
||||
// one of them would pass with the other.
|
||||
// because they take different typed target columns.
|
||||
func RunEdgeReaderReturnsTargetsVerbatim(t *testing.T, ctx context.Context, fixture EdgeReaderFixture) {
|
||||
t.Helper()
|
||||
anchor := fixture.IssuePrefix + "-verbatim-src"
|
||||
|
|
@ -155,11 +147,9 @@ func RunEdgeReaderReturnsTargetsVerbatim(t *testing.T, ctx context.Context, fixt
|
|||
}
|
||||
|
||||
// RunEdgeReaderCollapsesRepeatedAnchors pins edgereader.go:59-62: an id named
|
||||
// twice is one anchor, at the position of its first mention.
|
||||
//
|
||||
// The repeat is placed AFTER a different anchor, so a body that de-duplicated
|
||||
// by sorting rather than by first-mention order would answer b, a instead of a,
|
||||
// b and fail.
|
||||
// twice is one anchor, at the position of its first mention. The repeat is
|
||||
// placed AFTER a different anchor, so a body that de-duplicated by sorting
|
||||
// rather than by first mention answers b, a instead of a, b and fails.
|
||||
func RunEdgeReaderCollapsesRepeatedAnchors(t *testing.T, ctx context.Context, fixture EdgeReaderFixture) {
|
||||
t.Helper()
|
||||
first := fixture.IssuePrefix + "-dup-b"
|
||||
|
|
@ -177,11 +167,9 @@ func RunEdgeReaderCollapsesRepeatedAnchors(t *testing.T, ctx context.Context, fi
|
|||
// The three edges are inserted in an order that is neither the target order nor
|
||||
// its reverse, so an implementation answering in insertion order fails here.
|
||||
//
|
||||
// ONLY THE PRIMARY KEY IS EXERCISED, and that is a property of the schema
|
||||
// rather than a hole in the case: all three backends refuse a second edge for a
|
||||
// (source, target) pair they already hold, so an answer with two edges to break
|
||||
// a tie between cannot be seeded through the fixture's AddDependency hook. The
|
||||
// leaf doc states the tiebreaker as a totality guarantee for that reason.
|
||||
// ONLY THE PRIMARY KEY IS EXERCISED: all three backends refuse a second edge
|
||||
// for a (source, target) pair they already hold, so an answer with two edges to
|
||||
// break a tie between cannot be seeded through AddDependency.
|
||||
func RunEdgeReaderOrdersEdgesByTarget(t *testing.T, ctx context.Context, fixture EdgeReaderFixture) {
|
||||
t.Helper()
|
||||
anchor := fixture.IssuePrefix + "-sort-src"
|
||||
|
|
@ -208,11 +196,8 @@ func RunEdgeReaderOrdersEdgesByTarget(t *testing.T, ctx context.Context, fixture
|
|||
|
||||
// RunEdgeReaderFiltersEdgesNotAnchors pins edgereader.go:73-75: the type filter
|
||||
// narrows edges, and an anchor whose every edge it rejects stays present with
|
||||
// none.
|
||||
//
|
||||
// That anchor is the case worth having. A body that dropped an anchor with no
|
||||
// surviving edges would look correct on the first half of this assertion and
|
||||
// would turn a filtered listing into a report that the issue does not exist.
|
||||
// none. A body that dropped it would turn a filtered listing into a report that
|
||||
// the issue does not exist.
|
||||
func RunEdgeReaderFiltersEdgesNotAnchors(t *testing.T, ctx context.Context, fixture EdgeReaderFixture) {
|
||||
t.Helper()
|
||||
kept := fixture.IssuePrefix + "-filter-kept"
|
||||
|
|
@ -236,9 +221,7 @@ func RunEdgeReaderFiltersEdgesNotAnchors(t *testing.T, ctx context.Context, fixt
|
|||
|
||||
// RunEdgeReaderReadsBothPlanes pins the anchor probe against edgereader.go:104:
|
||||
// "no issue AND no wisp carries this id". A wisp anchor is present, and its
|
||||
// edges come back from the ephemeral tier the seed routed them to.
|
||||
//
|
||||
// It is the case most likely to catch a real divergence, because the three
|
||||
// edges come back from the ephemeral tier the seed routed them to. The three
|
||||
// bodies reach the two planes by different routes: a batched EXISTS over
|
||||
// `issues` then `wisps` on the store side, and GetIssuesByIDs plus
|
||||
// GetWispsByIDs on the unit-of-work side.
|
||||
|
|
@ -257,11 +240,8 @@ func RunEdgeReaderReadsBothPlanes(t *testing.T, ctx context.Context, fixture Edg
|
|||
|
||||
// RunEdgeReaderResolvesExactIDsOnly pins edgereader.go:36-43: a prefix of a
|
||||
// real id, a case variant and an id carrying whitespace are all misses, not
|
||||
// resolutions.
|
||||
//
|
||||
// They are misses rather than errors here, which is the per-anchor spelling of
|
||||
// the same promise RelatedRequest.ID makes: this role reports them beside the
|
||||
// anchor that did resolve.
|
||||
// resolutions. They are misses rather than errors: this role reports them
|
||||
// beside the anchor that did resolve.
|
||||
func RunEdgeReaderResolvesExactIDsOnly(t *testing.T, ctx context.Context, fixture EdgeReaderFixture) {
|
||||
t.Helper()
|
||||
anchor := fixture.IssuePrefix + "-exact-anchor"
|
||||
|
|
@ -297,11 +277,9 @@ func RunEdgeReaderAnswersAnEmptyRequest(t *testing.T, ctx context.Context, fixtu
|
|||
}
|
||||
|
||||
// RunEdgeReaderRefusesAnEmptyID pins edgereader.go:50-52: the empty string is
|
||||
// ErrValidation rather than a nameless ghost.
|
||||
//
|
||||
// The refusal must beat the good anchor beside it — a body that answered for
|
||||
// the ids it could and reported the empty one as missing would leave a caller
|
||||
// with an anchor it has no name for.
|
||||
// ErrValidation rather than a nameless ghost. The refusal must beat the good
|
||||
// anchor beside it — a body that answered for the ids it could would leave a
|
||||
// caller with an anchor it has no name for.
|
||||
func RunEdgeReaderRefusesAnEmptyID(t *testing.T, ctx context.Context, fixture EdgeReaderFixture) {
|
||||
t.Helper()
|
||||
anchor := fixture.IssuePrefix + "-emptyid-anchor"
|
||||
|
|
@ -315,7 +293,6 @@ func RunEdgeReaderRefusesAnEmptyID(t *testing.T, ctx context.Context, fixture Ed
|
|||
|
||||
// RunEdgeReaderRefusesAnUnusableType pins edgereader.go:67-71: an entry no edge
|
||||
// could ever carry is ErrValidation rather than a filter that matches nothing.
|
||||
//
|
||||
// The vocabulary itself stays OPEN, which the second half asserts: a
|
||||
// workspace's own type is accepted and simply matches no edge here.
|
||||
func RunEdgeReaderRefusesAnUnusableType(t *testing.T, ctx context.Context, fixture EdgeReaderFixture) {
|
||||
|
|
@ -365,10 +342,8 @@ func RunEdgeReaderLeavesTheRequestAlone(t *testing.T, ctx context.Context, fixtu
|
|||
}
|
||||
|
||||
// RunEdgeReaderWritesNothing pins edgereader.go:175-178: reading edges records
|
||||
// no history entry.
|
||||
//
|
||||
// The delta is taken around the call rather than as an absolute count, because
|
||||
// the seeds above it are versioned writes of their own.
|
||||
// no history entry. The delta is taken around the call rather than as an
|
||||
// absolute count, because the seeds above it are versioned writes of their own.
|
||||
func RunEdgeReaderWritesNothing(t *testing.T, ctx context.Context, fixture EdgeReaderFixture) {
|
||||
t.Helper()
|
||||
if fixture.CountHistory == nil {
|
||||
|
|
|
|||
|
|
@ -158,18 +158,14 @@ func RunIssueOperationsCreateRejectsMissingDependencyTargets(t *testing.T, ctx c
|
|||
}
|
||||
|
||||
// RunIssueOperationsCreateRefusesAnOccupiedID pins the create-only half of the
|
||||
// Lifecycle.Create clause: "It is create-only across issues and wisps: an
|
||||
// occupied ID returns ErrAlreadyExists and leaves persistent state unchanged"
|
||||
// (issueops/issueops.go, Lifecycle.Create). ErrAlreadyExists says the same
|
||||
// thing from the other side — "The issue and wisp tables share one ID space"
|
||||
// (issueops/errors.go) — so ACROSS is asserted in both directions here, not
|
||||
// only for the plane the create happens to target.
|
||||
// Lifecycle.Create clause: "an occupied ID returns ErrAlreadyExists and leaves
|
||||
// persistent state unchanged" (issueops/issueops.go, Lifecycle.Create). The
|
||||
// issue and wisp tables share one ID space, so ACROSS is asserted in both
|
||||
// directions here, not only for the plane the create happens to target.
|
||||
//
|
||||
// This is not a hypothetical. The proxied-server `bd create` route asked its
|
||||
// use case for a plain create with no create-only guard, so `bd create --id
|
||||
// <occupied>` silently UPSERTED the stored row and reported success while the
|
||||
// direct route refused. A front door moving onto the role inherits whatever
|
||||
// the role's implementations do, so every one of them has to refuse.
|
||||
// The proxied-server `bd create` route asked its use case for a plain create
|
||||
// with no create-only guard, so `bd create --id <occupied>` silently UPSERTED
|
||||
// the stored row and reported success while the direct route refused.
|
||||
func RunIssueOperationsCreateRefusesAnOccupiedID(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture) {
|
||||
t.Helper()
|
||||
|
||||
|
|
@ -242,8 +238,8 @@ func RunIssueOperationsCreateRefusesAnOccupiedID(t *testing.T, ctx context.Conte
|
|||
}
|
||||
|
||||
// assertIssueOperationsAlreadyExists checks the refusal an occupied ID gets.
|
||||
// The message must name the ID: a caller that asked for one ID and was refused
|
||||
// cannot act on "issue already exists".
|
||||
// The message must name the ID: a caller refused with a bare "issue already
|
||||
// exists" cannot act on it.
|
||||
func assertIssueOperationsAlreadyExists(t *testing.T, err error, label, id string) {
|
||||
t.Helper()
|
||||
if err == nil {
|
||||
|
|
@ -260,15 +256,12 @@ func assertIssueOperationsAlreadyExists(t *testing.T, err error, label, id strin
|
|||
// RunIssueOperationsCreateInheritsParentLabels pins
|
||||
// CreateRequest.InheritLabelsFromParent — "copies the parent's labels at
|
||||
// creation" — against CreateRequest.Issue's own "Labels are authoritative"
|
||||
// (both issueops/issueops.go, CreateRequest). The two clauses meet on one
|
||||
// create, and the created issue must satisfy both: the request's labels are
|
||||
// there because they are authoritative, and the parent's are there because
|
||||
// inheritance was asked for.
|
||||
// (both issueops/issueops.go, CreateRequest). One create must satisfy both.
|
||||
//
|
||||
// Both `bd create --parent` front doors depend on exactly this. They spell it
|
||||
// differently — the direct route merges the parent's labels itself so its
|
||||
// --dry-run preview can show them and leaves the flag off, the proxied route
|
||||
// sets the flag — so the merge has to be the same set either way.
|
||||
// The two `bd create --parent` front doors spell it differently — the direct
|
||||
// route merges the parent's labels itself so its --dry-run preview can show
|
||||
// them and leaves the flag off, the proxied route sets the flag — so the merge
|
||||
// has to be the same set either way.
|
||||
func RunIssueOperationsCreateInheritsParentLabels(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture) {
|
||||
t.Helper()
|
||||
|
||||
|
|
@ -289,12 +282,10 @@ func RunIssueOperationsCreateInheritsParentLabels(t *testing.T, ctx context.Cont
|
|||
t.Fatalf("Create inheriting child: %v", err)
|
||||
}
|
||||
// A label the child and the parent both carry is one label, not two: the
|
||||
// stored set is a set. The count assertion inside this helper is what says
|
||||
// so.
|
||||
// count assertion inside this helper is what says so.
|
||||
assertIssueOperationsLabels(t, ctx, fixture, inherited.Issue.ID, "inheriting child", "own", "shared", "from-parent")
|
||||
// CreateResult.Issue is "a detached snapshot with labels", so the same set
|
||||
// has to come back on the result rather than only being readable from the
|
||||
// row.
|
||||
// has to come back on the result rather than only from the row.
|
||||
assertIssueOperationsStringSet(t, "inheriting child result labels", inherited.Issue.Labels, "own", "shared", "from-parent")
|
||||
|
||||
// With inheritance off, the request's own labels are the whole set — the
|
||||
|
|
@ -1711,28 +1702,24 @@ func RunIssueOperationsUpdatePersistentPreservesUnversionedClass(t *testing.T, c
|
|||
}
|
||||
|
||||
// RunIssueOperationsUpdateConditionalGuardsGateOrdinaryEdits pins the two
|
||||
// compare-and-set preconditions as PRECONDITIONS ON A PLAIN EDIT, which is not
|
||||
// the same question the assignee-transfer case above asks of them. There they
|
||||
// appear beside a fenced transfer, to pin the ORDER the two guards resolve in;
|
||||
// here they gate an ordinary field update that no fence would touch, which is
|
||||
// how `bd update --if-status`/`--if-assignee` actually reach the contract.
|
||||
// compare-and-set preconditions as PRECONDITIONS ON A PLAIN EDIT. The
|
||||
// assignee-transfer case above pins the ORDER the two guards resolve in beside
|
||||
// a fenced transfer; here they gate an ordinary field update that no fence
|
||||
// would touch, which is how `bd update --if-status`/`--if-assignee` actually
|
||||
// reach the contract.
|
||||
//
|
||||
// The clauses: ExpectedAssignee "requires the current assignee to match" and
|
||||
// ExpectedStatus "requires the current status to match"
|
||||
// (issueops/issueops.go:250-256), under Lifecycle's standing promise that a
|
||||
// "refusal or validation error leaves persistent state unchanged"
|
||||
// (issueops/issueops.go:406-408). The SENTINELS the two refusals wear are not
|
||||
// named by those clauses; they are named by the contract, which already pins
|
||||
// ErrVersionMismatch/ErrStatusMismatch for the same fields on a fenced request
|
||||
// (this file, RunIssueOperationsUpdateAssigneeTransferFence), so asserting them
|
||||
// here extends an established promise rather than inventing one.
|
||||
// (issueops/issueops.go:406-408). The SENTINELS come from
|
||||
// RunIssueOperationsUpdateAssigneeTransferFence in this file.
|
||||
//
|
||||
// Both routes of `bd update` now send these guards to this contract instead of
|
||||
// applying them beside their own read: the direct one always did, and the
|
||||
// proxied one joined it when its hand-rolled read-merge-write was deleted
|
||||
// (bd-xt6de). A refusal that leaked a partial write would exit 13 — "another
|
||||
// actor won the race, nothing was written, do not retry" — while having
|
||||
// written.
|
||||
// applying them beside their own read; the proxied one joined when its
|
||||
// hand-rolled read-merge-write was deleted (bd-xt6de). A refusal that leaked a
|
||||
// partial write would exit 13 — "another actor won the race, nothing was
|
||||
// written, do not retry" — while having written.
|
||||
func RunIssueOperationsUpdateConditionalGuardsGateOrdinaryEdits(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture) {
|
||||
t.Helper()
|
||||
|
||||
|
|
|
|||
|
|
@ -18,35 +18,26 @@ import (
|
|||
// backend that disagrees is parked at its own wiring site with
|
||||
// skipKnownDivergence so the case still runs on the ones that agree.
|
||||
//
|
||||
// TWO BODIES BEHIND THREE WIRINGS, as everywhere here: dolt and embeddeddolt
|
||||
// share internal/workapi/storequerier, and the unit-of-work provider is the
|
||||
// second, genuinely separate vote. They diverge in exactly two places and both
|
||||
// are capabilities rather than opinions — the uow seam renders OFFSET and
|
||||
// reports has-more natively — so the cases below are written to the promise and
|
||||
// the Offset one is written comparatively.
|
||||
// TWO BODIES BEHIND THREE WIRINGS: dolt and embeddeddolt share
|
||||
// internal/workapi/storequerier, and the unit-of-work provider is the second,
|
||||
// genuinely separate vote. They diverge only where the uow seam renders OFFSET
|
||||
// and reports has-more natively, which is why the Offset case is written
|
||||
// comparatively.
|
||||
//
|
||||
// WHAT THESE CASES DO NOT PROVE, stated plainly because the role exists to fix
|
||||
// a specific defect. Both front doors used to bound a predicate query's fetch
|
||||
// at max(3*Limit, 100) rows, so a match beyond that window vanished. Making
|
||||
// that window observable takes MORE THAN A HUNDRED candidate rows in one store,
|
||||
// which is minutes of seeding at three backends for one bit of information. The
|
||||
// arithmetic itself is pinned where it lives and costs nothing —
|
||||
// TestBuildQueryPlanLeavesAPredicateQueryUNBOUNDED in internal/workapi asserts
|
||||
// that a predicate plan's filter carries no row limit at all, and both bodies
|
||||
// execute that plan — and one end-to-end run over a candidate set larger than
|
||||
// the old window is in internal/storage/dolt. What the cases here pin is the
|
||||
// PROMISE the window broke: a page is a prefix of the complete matching set and
|
||||
// has-more is exact.
|
||||
// WHAT THESE CASES DO NOT PROVE: the max(3*Limit, 100) over-fetch window both
|
||||
// front doors used to apply, which takes MORE THAN A HUNDRED candidate rows to
|
||||
// observe. That is pinned by TestBuildQueryPlanLeavesAPredicateQueryUNBOUNDED
|
||||
// in internal/workapi and by one end-to-end run in internal/storage/dolt. What
|
||||
// the cases here pin is the PROMISE the window broke: a page is a prefix of the
|
||||
// complete matching set and has-more is exact.
|
||||
//
|
||||
// EVERY CASE IS SCOPED BY A LABEL and asks for it inside the EXPRESSION, which
|
||||
// is the only scoping tool this role has: there are no filter fields on a query
|
||||
// request, so a case that did not name its own rows would answer about every
|
||||
// row every other case seeded.
|
||||
// EVERY CASE IS SCOPED BY A LABEL asked for inside the EXPRESSION: a query
|
||||
// request has no filter fields, so a case that did not name its own rows would
|
||||
// answer about every row every other case seeded.
|
||||
|
||||
// QuerierFixture supplies adapter-specific storage access for the boolean-query
|
||||
// assertions. Every field is named and typed exactly like the per-backend
|
||||
// roleFixtureKit hook it is filled from, so a wiring is kit plus accessor plus
|
||||
// prefix with no adapter in between.
|
||||
// roleFixtureKit hook it is filled from.
|
||||
type QuerierFixture struct {
|
||||
// IssuePrefix namespaces the ids each assertion seeds, so several of them
|
||||
// can share one database.
|
||||
|
|
@ -63,13 +54,10 @@ type QuerierFixture struct {
|
|||
|
||||
// RunQuerierDisjunctionAnswersEveryMatch pins the capability that makes this a
|
||||
// role at all (issueops/querier.go:99-107): an OR, which no conjunction of
|
||||
// ListRequest fields expresses, answers with the union of both arms and with
|
||||
// nothing else.
|
||||
//
|
||||
// The NOT arm is here for the same reason and is not redundant: a general NOT
|
||||
// is the OTHER expression shape the storage filter cannot carry, and it is the
|
||||
// one whose complement includes rows no base filter narrowed, so an
|
||||
// implementation that leaned on the base filters alone answers it wrongly.
|
||||
// ListRequest fields expresses, answers with the union of both arms and nothing
|
||||
// else. The NOT arm is not redundant — its complement includes rows no base
|
||||
// filter narrowed, so an implementation leaning on the base filters answers it
|
||||
// wrongly.
|
||||
func RunQuerierDisjunctionAnswersEveryMatch(t *testing.T, ctx context.Context, fixture QuerierFixture) {
|
||||
t.Helper()
|
||||
scope := querierLabel(fixture, "or")
|
||||
|
|
@ -98,16 +86,15 @@ func RunQuerierDisjunctionAnswersEveryMatch(t *testing.T, ctx context.Context, f
|
|||
// shorter than that set.
|
||||
//
|
||||
// The limit is walked across the boundary — one below the match count, exactly
|
||||
// on it, and one above — because those three are where a page bound and a
|
||||
// verdict computed from different sets come apart. An implementation that
|
||||
// reported has-more from the row count the DATABASE returned rather than from
|
||||
// the count of MATCHES passes the middle case and fails the other two.
|
||||
// on it, and one above. An implementation that reported has-more from the row
|
||||
// count the DATABASE returned rather than from the count of MATCHES passes the
|
||||
// middle case and fails the other two.
|
||||
func RunQuerierPageIsAPrefixAndHasMoreIsExact(t *testing.T, ctx context.Context, fixture QuerierFixture) {
|
||||
t.Helper()
|
||||
scope := querierLabel(fixture, "page")
|
||||
// Four matching rows and one that does not match, so the matching set is a
|
||||
// STRICT subset of what the base filters admit: a limit applied to the
|
||||
// wrong one of those two answers a different page.
|
||||
// Four matching rows and one that does not, so the matching set is a STRICT
|
||||
// subset of what the base filters admit: a limit applied to the wrong one
|
||||
// of those two answers a different page.
|
||||
for i, tag := range []string{"a", "b", "c", "d"} {
|
||||
seedQuerierIssue(t, ctx, fixture, querierIssue(querierID(fixture, "page", tag), types.TypeBug, i, scope))
|
||||
}
|
||||
|
|
@ -149,16 +136,14 @@ func RunQuerierPageIsAPrefixAndHasMoreIsExact(t *testing.T, ctx context.Context,
|
|||
}
|
||||
|
||||
// RunQuerierSortSeesTheWholeMatchingSet pins the half of the display-order
|
||||
// promise that only a predicate query can show (issueops/querier.go:45-53): the
|
||||
// order is applied to the rows the QUERY bounded, and a predicate query bounds
|
||||
// nothing, so a one-row page under a sort is the best row in the whole matching
|
||||
// set rather than the first one the database happened to return.
|
||||
// promise that only a predicate query can show (issueops/querier.go:45-53): a
|
||||
// predicate query bounds nothing, so a one-row page under a sort is the best row
|
||||
// in the whole matching set.
|
||||
//
|
||||
// The rows are seeded worst-priority-first so that "the first row the database
|
||||
// returned" and "the highest-priority match" are different answers. An
|
||||
// implementation that cut the page before ordering it — which is what both
|
||||
// front doors did, because the window they fetched was all they had — returns
|
||||
// the seeded-first row here.
|
||||
// returned" and "the highest-priority match" are different answers; an
|
||||
// implementation that cut the page before ordering it returns the seeded-first
|
||||
// row.
|
||||
func RunQuerierSortSeesTheWholeMatchingSet(t *testing.T, ctx context.Context, fixture QuerierFixture) {
|
||||
t.Helper()
|
||||
scope := querierLabel(fixture, "sort")
|
||||
|
|
@ -195,9 +180,7 @@ func RunQuerierSortSeesTheWholeMatchingSet(t *testing.T, ctx context.Context, fi
|
|||
|
||||
// RunQuerierHidesClosedUnlessTheExpressionOrTheFlagSaysOtherwise pins the
|
||||
// conditional default (issueops/querier.go:30-39). It is a CONTRACT clause
|
||||
// rather than a CLI default because both front doors have always applied it,
|
||||
// and because it is the one thing about a query's answer that the expression
|
||||
// does not fully determine.
|
||||
// rather than a CLI default because both front doors have always applied it.
|
||||
func RunQuerierHidesClosedUnlessTheExpressionOrTheFlagSaysOtherwise(t *testing.T, ctx context.Context, fixture QuerierFixture) {
|
||||
t.Helper()
|
||||
scope := querierLabel(fixture, "closed")
|
||||
|
|
@ -223,13 +206,10 @@ func RunQuerierHidesClosedUnlessTheExpressionOrTheFlagSaysOtherwise(t *testing.T
|
|||
}
|
||||
|
||||
// RunQuerierRefusesAMalformedRequest pins every deterministic refusal
|
||||
// (issueops/querier.go:23-27, 57-62, 65-91). Each is ErrValidation, and each
|
||||
// matters because a front door that had to make the same decision for itself is
|
||||
// how the two routes came to disagree about what an offset meant.
|
||||
// (issueops/querier.go:23-27, 57-62, 65-91). Each is ErrValidation.
|
||||
//
|
||||
// A matching row is seeded first so every refusal runs against a store that
|
||||
// WOULD have answered, which is what makes a refusal a refusal rather than an
|
||||
// empty result reported the hard way.
|
||||
// WOULD have answered, rather than an empty result reported the hard way.
|
||||
func RunQuerierRefusesAMalformedRequest(t *testing.T, ctx context.Context, fixture QuerierFixture) {
|
||||
t.Helper()
|
||||
scope := querierLabel(fixture, "refuse")
|
||||
|
|
@ -265,25 +245,21 @@ func RunQuerierRefusesAMalformedRequest(t *testing.T, ctx context.Context, fixtu
|
|||
// either HONORED or REFUSED with a typed *ErrUnsupported, and never SILENTLY
|
||||
// IGNORED.
|
||||
//
|
||||
// It is deliberately weaker than "Offset skips N rows", and the weakness is the
|
||||
// same one RunReaderOffsetIsHonoredOrRefused carries: the two bodies disagree by
|
||||
// design, because one seam renders OFFSET and the other does not. Which body
|
||||
// does which is a per-backend fact and is asserted at the wirings, not here.
|
||||
// It is deliberately weaker than "Offset skips N rows", for the same reason
|
||||
// RunReaderOffsetIsHonoredOrRefused is: the two bodies disagree by design,
|
||||
// because one seam renders OFFSET and the other does not. Which body does which
|
||||
// is asserted at the wirings, not here.
|
||||
//
|
||||
// BOTH SHAPES OF EXPRESSION ARE DRIVEN, and that is what this case adds over
|
||||
// the reader's. A predicate query's offset is applied in Go, after the
|
||||
// predicate, over the complete matching set — a different code path from the
|
||||
// filter-expressible one, and the path that used to be refused outright at the
|
||||
// front door because an offset into a truncated window meant nothing.
|
||||
// BOTH SHAPES OF EXPRESSION ARE DRIVEN, which is what this case adds over the
|
||||
// reader's: a predicate query's offset is applied in Go, after the predicate, a
|
||||
// different code path from the filter-expressible one.
|
||||
//
|
||||
// EVERY REQUEST HERE CARRIES A BOUNDED LIMIT, deliberately, and the reason is a
|
||||
// live defect rather than tidiness: an UNLIMITED request with a non-zero Offset
|
||||
// renders SQL the Dolt engine answers with a recovered panic ("makeslice: cap
|
||||
// out of range" out of topRowsIter) instead of rows, on the unit-of-work seam.
|
||||
// That predates this role — `bd query --offset N --limit 0 --proxied-server`
|
||||
// built the same filter — and it is a storage-seam bug, not a contract
|
||||
// question, so this case asks the question it can answer rather than pinning a
|
||||
// crash as behavior.
|
||||
// EVERY REQUEST HERE CARRIES A BOUNDED LIMIT: on the unit-of-work seam an
|
||||
// UNLIMITED request with a non-zero Offset renders SQL the Dolt engine answers
|
||||
// with a recovered panic ("makeslice: cap out of range" out of topRowsIter)
|
||||
// instead of rows. That is a storage-seam bug that predates this role, not a
|
||||
// contract question, so this case asks the question it can answer rather than
|
||||
// pinning a crash as behavior.
|
||||
func RunQuerierOffsetIsHonoredOrRefused(t *testing.T, ctx context.Context, fixture QuerierFixture) {
|
||||
t.Helper()
|
||||
scope := querierLabel(fixture, "offset")
|
||||
|
|
@ -300,8 +276,8 @@ func RunQuerierOffsetIsHonoredOrRefused(t *testing.T, ctx context.Context, fixtu
|
|||
} {
|
||||
t.Run(test.what, func(t *testing.T) {
|
||||
request := publicops.QueryRequest{Expression: test.expression, Limit: querierLimit(10)}
|
||||
// Offset 0 is not a page request, so it is served everywhere and is
|
||||
// the baseline the paged call has to differ from.
|
||||
// Offset 0 is served everywhere; it is the baseline the paged call
|
||||
// has to differ from.
|
||||
unpaged := querierIDs(t, ctx, fixture, request)
|
||||
if len(unpaged) != 3 {
|
||||
t.Fatalf("Offset 0 returned %v, want the three seeded rows", unpaged)
|
||||
|
|
@ -326,8 +302,7 @@ func RunQuerierOffsetIsHonoredOrRefused(t *testing.T, ctx context.Context, fixtu
|
|||
t.Fatalf("Offset 1 returned the same page as Offset 0 (%v) and no error: the offset was silently ignored", got)
|
||||
}
|
||||
// Honored means it skipped MATCHES: two of the three, still in the
|
||||
// unpaged order, never a short page assembled from candidates the
|
||||
// predicate had already rejected.
|
||||
// unpaged order, never a page cut from rejected candidates.
|
||||
if want := unpaged[1:]; !slices.Equal(got, want) {
|
||||
t.Errorf("Offset 1 = %v, want %v — the tail of the same answer", got, want)
|
||||
}
|
||||
|
|
@ -338,8 +313,7 @@ func RunQuerierOffsetIsHonoredOrRefused(t *testing.T, ctx context.Context, fixtu
|
|||
// RunQuerierEmptyMatchIsAWellFormedPage pins the empty answer
|
||||
// (issueops/querier.go:139-141): a nil error, an empty page that is not a nil
|
||||
// slice, and no has-more. There is no ErrNotFound on this role — a question
|
||||
// about a set has an answer even when the set is empty, and a caller polling
|
||||
// for work would otherwise have to classify an error to read "nothing".
|
||||
// about a set has an answer even when the set is empty.
|
||||
func RunQuerierEmptyMatchIsAWellFormedPage(t *testing.T, ctx context.Context, fixture QuerierFixture) {
|
||||
t.Helper()
|
||||
scope := querierLabel(fixture, "empty")
|
||||
|
|
@ -391,10 +365,9 @@ func RunQuerierWritesNothing(t *testing.T, ctx context.Context, fixture QuerierF
|
|||
}
|
||||
|
||||
// RunQuerierDoesNotMutateTheCallerRequest pins the no-mutation promise
|
||||
// (issueops/querier.go:147-148) against a fully populated request. It matters
|
||||
// here even though the request carries no slice: Limit is a POINTER, and an
|
||||
// implementation that defaulted it by writing through that pointer would change
|
||||
// the caller's own variable.
|
||||
// (issueops/querier.go:147-148) against a fully populated request. Limit is a
|
||||
// POINTER, so an implementation that defaulted it by writing through that
|
||||
// pointer would change the caller's own variable.
|
||||
func RunQuerierDoesNotMutateTheCallerRequest(t *testing.T, ctx context.Context, fixture QuerierFixture) {
|
||||
t.Helper()
|
||||
scope := querierLabel(fixture, "immutable")
|
||||
|
|
@ -449,8 +422,7 @@ func seedQuerierIssue(t *testing.T, ctx context.Context, fixture QuerierFixture,
|
|||
}
|
||||
}
|
||||
|
||||
// querierPage runs one query and fails the case on an error, because every
|
||||
// caller here has already established that the request is well-formed.
|
||||
// querierPage runs one query and fails the case on an error.
|
||||
func querierPage(t *testing.T, ctx context.Context, fixture QuerierFixture, request publicops.QueryRequest) publicops.IssuePage {
|
||||
t.Helper()
|
||||
page, err := fixture.Querier.Query(ctx, request)
|
||||
|
|
@ -476,8 +448,7 @@ func querierPageIDs(page publicops.IssuePage) []string {
|
|||
}
|
||||
|
||||
// assertQuerierAnswered compares a page against the ids it must hold, ignoring
|
||||
// order: the cases that use it name no sort, and the order of an unsorted page
|
||||
// is the storage order rather than a promise this contract makes.
|
||||
// order: the order of an unsorted page is storage order, not a promise.
|
||||
func assertQuerierAnswered(t *testing.T, got, want []string, because string) {
|
||||
t.Helper()
|
||||
sortedGot := append([]string(nil), got...)
|
||||
|
|
|
|||
|
|
@ -764,21 +764,14 @@ func RunReaderListEmptyPageIsWellFormed(t *testing.T, ctx context.Context, fixtu
|
|||
// that exceeds it is either HONORED — no page, an error — or REFUSED with a
|
||||
// typed *ErrUnsupported, and never SILENTLY IGNORED.
|
||||
//
|
||||
// It is the MIRROR of RunReaderOffsetIsHonoredOrRefused above, one field over
|
||||
// and pointing the other way: there the unit-of-work body honors and the
|
||||
// store-backed one refuses, here the store-backed one honors and the
|
||||
// unit-of-work one refuses. Which does which is a per-backend fact asserted at
|
||||
// the wirings, not here, and the shared assertion is deliberately the weaker
|
||||
// one — the two bodies disagree by design, so a case written to either
|
||||
// behavior would fail the other.
|
||||
// It is the MIRROR of RunReaderOffsetIsHonoredOrRefused above. Which body
|
||||
// honors and which refuses is a per-backend fact asserted at the wirings, not
|
||||
// here: the two disagree by design, so the shared assertion is the weaker one.
|
||||
//
|
||||
// The never-silently clause is the whole value, exactly as it is for Offset. A
|
||||
// cap is a CIRCUIT BREAKER: a caller sets it because it would rather fail than
|
||||
// wait, so a body that accepts the field and answers the unbounded query hands
|
||||
// that caller the runaway result it was guarding against, with nothing on the
|
||||
// answer to say so. That is the failure this pins, and it is the one the
|
||||
// unit-of-work query path would have had — it reads no MaxRows at all — if the
|
||||
// field had been added without a refusal beside it.
|
||||
// The never-silently clause is the whole value. A cap is a CIRCUIT BREAKER: a
|
||||
// caller sets it because it would rather fail than wait, so a body that accepts
|
||||
// the field and answers the unbounded query hands that caller the runaway
|
||||
// result it was guarding against.
|
||||
//
|
||||
// The complement is asserted too: the SAME request under a cap the result set
|
||||
// fits inside must come back as an ordinary page everywhere. Without it a body
|
||||
|
|
@ -794,8 +787,7 @@ func RunReaderListMaxRowsIsHonoredOrRefused(t *testing.T, ctx context.Context, f
|
|||
idScope := readerIDFilter(ids...)
|
||||
|
||||
// A cap the three seeded rows fit inside. Answered as an ordinary page by
|
||||
// the body that honors caps, and refused by the body that honors none —
|
||||
// which is why the refusal branch is accepted here as well.
|
||||
// the body that honors caps, and refused by the body that honors none.
|
||||
const roomyWhat = "List under a cap the result set fits inside"
|
||||
roomy, err := fixture.Reader.List(ctx, publicops.ListRequest{
|
||||
IDFilter: idScope, SortBy: "created", MaxRows: len(ids) + 1, MaxRowsSource: "--max-rows",
|
||||
|
|
@ -822,7 +814,7 @@ func RunReaderListMaxRowsIsHonoredOrRefused(t *testing.T, ctx context.Context, f
|
|||
}
|
||||
// The honoring branch. The leaf names the answer — *ErrTooManyRows — so a
|
||||
// caller can tell "the cap fired" from any other failure without reading
|
||||
// error text, and that is what is asserted rather than a message.
|
||||
// error text.
|
||||
var tooMany *storageops.ErrTooManyRows
|
||||
if !errors.As(err, &tooMany) {
|
||||
t.Fatalf("List honored MaxRows and failed with %v; an honored cap has to answer with *ErrTooManyRows a caller can classify", err)
|
||||
|
|
@ -850,19 +842,14 @@ func RunReaderListMaxRowsIsHonoredOrRefused(t *testing.T, ctx context.Context, f
|
|||
// of them, so the knob demonstrably reached the query rather than being
|
||||
// accepted and dropped; and
|
||||
// - NOTHING ELSE MOVES. Same rows, same order, same Parent, same has-more
|
||||
// verdict as the identical request without the knob. This is a HYDRATION
|
||||
// opt-out, and the way it could go wrong is by changing which rows match —
|
||||
// the aggregates hang off outer joins, so an implementation that made one
|
||||
// of them inner would answer with a strict subset and still look like it
|
||||
// had "skipped the counts".
|
||||
//
|
||||
// The comparison is against the SAME request run both ways rather than against
|
||||
// a written-out expectation, so the case says exactly what the doc says: this
|
||||
// field changes what is hydrated and not what is returned.
|
||||
// verdict as the identical request without the knob. The aggregates hang
|
||||
// off outer joins, so an implementation that made one of them inner would
|
||||
// answer with a strict subset and still look like it had "skipped the
|
||||
// counts".
|
||||
//
|
||||
// Zero is asserted rather than "unknown" because zero is what the wire and the
|
||||
// struct can carry; the doc's instruction to READ it as unknown is a promise to
|
||||
// the caller, not something an implementation can express differently.
|
||||
// the caller.
|
||||
func RunReaderListSkipCountsDropsTheCardinalitiesAndNothingElse(t *testing.T, ctx context.Context, fixture ReaderFixture) {
|
||||
t.Helper()
|
||||
subject := readerID(fixture, "skipcounts", "subject")
|
||||
|
|
@ -874,9 +861,8 @@ func RunReaderListSkipCountsDropsTheCardinalitiesAndNothingElse(t *testing.T, ct
|
|||
}
|
||||
// One outgoing blocks edge, one incoming one, and a parent-child edge, so
|
||||
// the subject row carries a nonzero DependencyCount, DependentCount and
|
||||
// Parent at once. Parent rides the same mega-query as the counts and is
|
||||
// NOT a count, which is what makes it the tripwire for a knob that
|
||||
// suppressed too much.
|
||||
// Parent at once. Parent rides the same mega-query as the counts and is NOT
|
||||
// a count: it is the tripwire for a knob that suppressed too much.
|
||||
for _, edge := range []*types.Dependency{
|
||||
{IssueID: subject, DependsOnID: blocker, Type: types.DepBlocks},
|
||||
{IssueID: dependent, DependsOnID: subject, Type: types.DepBlocks},
|
||||
|
|
|
|||
|
|
@ -22,43 +22,35 @@ import (
|
|||
// apart than usual. dolt and embeddeddolt share internal/workapi/
|
||||
// storereadycounter, which is one indexed COUNT(*) per plane minus their
|
||||
// overlap; the unit-of-work provider runs the unbounded ready query and takes
|
||||
// its length. So the three wirings are one vote plus an engine check on the
|
||||
// cheap path, and a second, genuinely independent vote on the expensive one —
|
||||
// and the cases below are written to catch the arithmetic that only the first
|
||||
// of those does (the wisp merge, the overlap subtraction), which is exactly
|
||||
// where a COUNT can disagree with the page it claims to size.
|
||||
// its length. So the wirings are one vote plus an engine check on the cheap
|
||||
// path and a second, independent vote on the expensive one, and the cases below
|
||||
// aim at the arithmetic only the first of them does.
|
||||
//
|
||||
// EVERY CASE IS SCOPED BY A LABEL, for the reason the ready-claim contract
|
||||
// gives: the ready front is a property of the whole database, not of an id
|
||||
// prefix, so a row seeded by one assertion is inside the next one's answer
|
||||
// unless each asks through Filter.Labels.
|
||||
// EVERY CASE IS SCOPED BY A LABEL: the ready front is a property of the whole
|
||||
// database, not of an id prefix, so a row seeded by one assertion is inside the
|
||||
// next one's answer unless each asks through Filter.Labels.
|
||||
//
|
||||
// EVERY CASE NAMES A SORT POLICY even though a count has no order, and that is
|
||||
// deliberate rather than copied: ReadyRequest.Sort's empty value resolves to
|
||||
// hybrid at the storage layer, which the leaf says no front door may rely on
|
||||
// (issueops/reader.go:79-83), and a count whose request is not the listing's
|
||||
// request is not the count this role promises.
|
||||
// EVERY CASE NAMES A SORT POLICY even though a count has no order.
|
||||
// ReadyRequest.Sort's empty value resolves to hybrid at the storage layer, which
|
||||
// the leaf says no front door may rely on (issueops/reader.go:79-83), and a
|
||||
// count whose request is not the listing's request is not the count this role
|
||||
// promises.
|
||||
|
||||
// ReadyCounterFixture supplies adapter-specific storage access for the
|
||||
// ready-count assertions. Every field is named and typed exactly like the
|
||||
// per-backend roleFixtureKit hook it is filled from, so a wiring is kit plus
|
||||
// accessors plus prefix with no adapter in between.
|
||||
// ready-count assertions.
|
||||
type ReadyCounterFixture struct {
|
||||
// IssuePrefix namespaces the ids each assertion seeds, so several of them
|
||||
// can share one database.
|
||||
IssuePrefix string
|
||||
// ReadyCounter is the surface under test.
|
||||
ReadyCounter publicops.ReadyCounter
|
||||
// Reader is the SAME backend's reader accessor, and this fixture cannot do
|
||||
// without it: the role's central promise is an IDENTITY with
|
||||
// len(Reader.Ready(r with Limit=0).Items) (issueops/readycounter.go:60-70),
|
||||
// and the only way to observe an identity is to ask both surfaces.
|
||||
// Reader is the SAME backend's reader accessor. The role's central promise
|
||||
// is an IDENTITY with len(Reader.Ready(r with Limit=0).Items)
|
||||
// (issueops/readycounter.go:60-70), so both surfaces have to be asked.
|
||||
Reader publicops.Reader
|
||||
// CreateIssue seeds a durable issue in the issues plane.
|
||||
CreateIssue func(context.Context, *types.Issue, string) error
|
||||
// CreateWisp seeds an ephemeral issue in the wisps plane. It is a separate
|
||||
// field rather than an Ephemeral flag on CreateIssue because the three
|
||||
// adapters reach the two planes through different verbs.
|
||||
// CreateWisp seeds an ephemeral issue in the wisps plane.
|
||||
CreateWisp func(context.Context, *types.Issue, string) error
|
||||
// AddDependency seeds ONE edge, which is how a case takes a row OFF the
|
||||
// ready front without deleting or closing it.
|
||||
|
|
@ -74,20 +66,18 @@ type ReadyCounterFixture struct {
|
|||
// len(Reader.Ready(r with Limit=0).Items), for every request the method
|
||||
// accepts.
|
||||
//
|
||||
// The case asks the SAME question three ways — an unbounded page, a page
|
||||
// bounded well below the seeded set, and the count — because the failure this
|
||||
// exists to prevent is a total that describes a different set than the page it
|
||||
// is printed beside. `bd ready` publishes both numbers together as "showing 2
|
||||
// of 5", and a reader takes the second as "how much work is left".
|
||||
// The failure this exists to prevent is a total that describes a different set
|
||||
// than the page it is printed beside: `bd ready` publishes both numbers as
|
||||
// "showing 2 of 5", and a reader takes the second as "how much work is left".
|
||||
//
|
||||
// The bounded page is the half that matters. A count computed by re-running
|
||||
// the listing would pass an unbounded comparison trivially; a count computed
|
||||
// from a COUNT(*) over a predicate assembled somewhere else is where the two
|
||||
// come apart, and it only shows up once a limit makes the numbers differ.
|
||||
//
|
||||
// The high-priority OUTSIDER is what makes the equality mean something: it is
|
||||
// ready, it would be counted by any request whose label predicate went missing
|
||||
// between the two surfaces, and it is outside the scope both are asked about.
|
||||
// The high-priority OUTSIDER is ready and outside the scope both surfaces are
|
||||
// asked about, so it is counted by any request whose label predicate went
|
||||
// missing between them.
|
||||
func RunReadyCounterEqualsTheUnboundedPage(t *testing.T, ctx context.Context, fixture ReadyCounterFixture) {
|
||||
t.Helper()
|
||||
label := fixture.IssuePrefix + "-rceq"
|
||||
|
|
@ -122,16 +112,10 @@ func RunReadyCounterEqualsTheUnboundedPage(t *testing.T, ctx context.Context, fi
|
|||
// A bounded count would answer "how many of the first N", which is not a
|
||||
// cardinality and would make the identity above false; an offset would
|
||||
// subtract the rows it skipped from the size of a set that still holds them.
|
||||
// The refusal is the promise that neither is quietly dropped.
|
||||
//
|
||||
// The explicit zero is here for the reason the claim contract states it:
|
||||
// ReadyRequest.Limit is a pointer so "unset" and "explicitly unlimited" stay
|
||||
// distinguishable (issueops/reader.go:85-89), and only the first is what this
|
||||
// request permits — an unlimited count is the only kind there is.
|
||||
//
|
||||
// A countable row is seeded first so each refusal runs against a set that
|
||||
// WOULD have answered, which is what makes a refusal a refusal rather than an
|
||||
// empty front reported the hard way.
|
||||
func RunReadyCounterRejectsLimitAndOffset(t *testing.T, ctx context.Context, fixture ReadyCounterFixture) {
|
||||
t.Helper()
|
||||
label := fixture.IssuePrefix + "-rcrej"
|
||||
|
|
@ -164,10 +148,9 @@ func RunReadyCounterRejectsLimitAndOffset(t *testing.T, ctx context.Context, fix
|
|||
// with an open blocker is not in the count even though it is open, unclosed and
|
||||
// otherwise indistinguishable from the row beside it.
|
||||
//
|
||||
// It is asserted against the listing rather than against a literal alone, so
|
||||
// the case says the two agree ON THE SAME SET and not merely that both happen
|
||||
// to be 2 today. The literal is checked as well, because an identity between
|
||||
// two surfaces that both dropped the blocker predicate would still hold.
|
||||
// Both the listing and the literal are checked: the listing says the two agree
|
||||
// on the same set, and the literal catches an identity that holds because both
|
||||
// surfaces dropped the blocker predicate.
|
||||
func RunReadyCounterCountsTheBlockerAwareSet(t *testing.T, ctx context.Context, fixture ReadyCounterFixture) {
|
||||
t.Helper()
|
||||
label := fixture.IssuePrefix + "-rcblock"
|
||||
|
|
@ -205,14 +188,13 @@ func RunReadyCounterCountsTheBlockerAwareSet(t *testing.T, ctx context.Context,
|
|||
// rows counts them exactly as the listing lists them, and one that does not
|
||||
// counts neither.
|
||||
//
|
||||
// This is the case aimed at the cheap path specifically. The store-backed body
|
||||
// sizes the ready set as one COUNT(*) per plane MINUS their overlap
|
||||
// (internal/storage/issueops.CountReadyWorkInTx) while the listing merges the
|
||||
// two planes row by row, so the wisp tier is the one place where the count is
|
||||
// assembled by different arithmetic than the page. Both directions of the gate
|
||||
// are asserted because each fails on its own: a body that always merged the
|
||||
// wisp plane would over-count a default request, and one that never merged it
|
||||
// would under-count an opted-in one.
|
||||
// The store-backed body sizes the ready set as one COUNT(*) per plane MINUS
|
||||
// their overlap (internal/storage/issueops.CountReadyWorkInTx) while the
|
||||
// listing merges the two planes row by row, so the wisp tier is where the count
|
||||
// is assembled by different arithmetic than the page. Both directions of the
|
||||
// gate are asserted because each fails on its own: a body that always merged
|
||||
// the wisp plane over-counts a default request, one that never merged it
|
||||
// under-counts an opted-in one.
|
||||
func RunReadyCounterEphemeralGateMatchesTheListing(t *testing.T, ctx context.Context, fixture ReadyCounterFixture) {
|
||||
t.Helper()
|
||||
label := fixture.IssuePrefix + "-rcwisp"
|
||||
|
|
@ -235,11 +217,10 @@ func RunReadyCounterEphemeralGateMatchesTheListing(t *testing.T, ctx context.Con
|
|||
// "not found" story (issueops/readycounter.go:84-87): a predicate that matches
|
||||
// nothing is 0 with a NIL ERROR.
|
||||
//
|
||||
// The nil is the load-bearing half. An empty ready front is the steady state of
|
||||
// The nil is the load-bearing half: an empty ready front is the steady state of
|
||||
// a drained queue, and a poller that had to classify an error to read a zero
|
||||
// would be pattern-matching prose. The decoy makes the zero about the FILTER
|
||||
// rather than about an empty database: a ready, countable row exists
|
||||
// throughout, it simply does not match.
|
||||
// rather than about an empty database.
|
||||
func RunReadyCounterEmptyFrontIsZeroAndNil(t *testing.T, ctx context.Context, fixture ReadyCounterFixture) {
|
||||
t.Helper()
|
||||
label := fixture.IssuePrefix + "-rcempty"
|
||||
|
|
@ -269,9 +250,7 @@ func RunReadyCounterEmptyFrontIsZeroAndNil(t *testing.T, ctx context.Context, fi
|
|||
// is the observable both an accidental commit and an accidental write would
|
||||
// move: every versioned unit of work in this tree ends in a Dolt commit, so a
|
||||
// count that took a write transaction would show up here even though it changed
|
||||
// no column. That is not a hypothetical for this role — the unit-of-work body
|
||||
// runs a query the listing runs, and the listing's own transaction wrapper is
|
||||
// two characters away from the writing one.
|
||||
// no column.
|
||||
func RunReadyCounterWritesNothing(t *testing.T, ctx context.Context, fixture ReadyCounterFixture) {
|
||||
t.Helper()
|
||||
if fixture.CountHistory == nil {
|
||||
|
|
@ -313,11 +292,9 @@ func RunReadyCounterWritesNothing(t *testing.T, ctx context.Context, fixture Rea
|
|||
// Priority pointer. Every one is populated here with a value normalization
|
||||
// would want to touch — untrimmed, duplicated, comma-joined — and the
|
||||
// comparison is against a second copy built by the same function, so an
|
||||
// in-place trim, dedupe, sort, alias expansion or write-through fails.
|
||||
//
|
||||
// The filter matches nothing on purpose. The promise is about the request, not
|
||||
// about the answer, and an empty front is the one outcome that does not depend
|
||||
// on what the rest of the suite has seeded.
|
||||
// in-place trim, dedupe, sort, alias expansion or write-through fails. The
|
||||
// filter matches nothing on purpose: the promise is about the request, not the
|
||||
// answer.
|
||||
func RunReadyCounterDoesNotMutateTheCallerRequest(t *testing.T, ctx context.Context, fixture ReadyCounterFixture) {
|
||||
t.Helper()
|
||||
build := func() publicops.ReadyRequest {
|
||||
|
|
@ -345,11 +322,9 @@ func RunReadyCounterDoesNotMutateTheCallerRequest(t *testing.T, ctx context.Cont
|
|||
}
|
||||
}
|
||||
|
||||
// readyCounterSort is the order every case names, for the reason
|
||||
// readyClaimerSort is named: it is the policy whose SQL is a plain "ORDER BY
|
||||
// priority, created_at, id", so no case depends on when the fixture was seeded.
|
||||
// A count has no order of its own — the policy is here because the request has
|
||||
// to be the listing's request for the identity to mean anything.
|
||||
// readyCounterSort is the order every case names: the policy whose SQL is a
|
||||
// plain "ORDER BY priority, created_at, id", so no case depends on when the
|
||||
// fixture was seeded.
|
||||
const readyCounterSort = "priority"
|
||||
|
||||
func readyCounterIssue(id string, priority int, labels ...string) *types.Issue {
|
||||
|
|
@ -387,8 +362,7 @@ func seedReadyCounterWisp(t *testing.T, ctx context.Context, fixture ReadyCounte
|
|||
}
|
||||
}
|
||||
|
||||
// readyCounterTotal runs one count and fails the case on an error, because
|
||||
// every caller here has already established that the request is well-formed.
|
||||
// readyCounterTotal runs one count and fails the case on an error.
|
||||
func readyCounterTotal(t *testing.T, ctx context.Context, fixture ReadyCounterFixture, request publicops.ReadyRequest) int64 {
|
||||
t.Helper()
|
||||
result, err := fixture.ReadyCounter.CountReady(ctx, request)
|
||||
|
|
@ -418,8 +392,8 @@ func readyCounterPageIDs(t *testing.T, ctx context.Context, fixture ReadyCounter
|
|||
}
|
||||
|
||||
// assertReadyCounterAgreesWithTheListing checks the identity and the literal
|
||||
// together for one request. The literal is what says the two surfaces agree on
|
||||
// the RIGHT set; the identity is what says they agree at all.
|
||||
// together: the identity says the two surfaces agree, the literal says they
|
||||
// agree on the RIGHT set.
|
||||
func assertReadyCounterAgreesWithTheListing(t *testing.T, ctx context.Context, fixture ReadyCounterFixture, request publicops.ReadyRequest, want int64, because string) {
|
||||
t.Helper()
|
||||
listed := readyCounterPageIDs(t, ctx, fixture, request, 0)
|
||||
|
|
|
|||
|
|
@ -16,45 +16,31 @@ import (
|
|||
// wiring site with skipKnownDivergence so the case still runs on the ones that
|
||||
// agree.
|
||||
//
|
||||
// THREE WIRINGS, AND HERE THAT REALLY IS THREE VOTES — which is unusual in
|
||||
// this suite and worth saying out loud, because the sibling contracts say the
|
||||
// opposite. For most roles dolt and embeddeddolt share one body
|
||||
// (internal/workapi/store*) and "both stores agree" is one vote plus an engine
|
||||
// check. That is still true of the ROLE layer here: both stores hand back
|
||||
// internal/workapi/storestats. But the queries it delegates to are written out
|
||||
// THREE times — dolt/queries.go, embeddeddolt/statistics.go and
|
||||
// domain/db/issue.go each spell the blocked count and the ready subtraction
|
||||
// themselves, and the two Dolt stores do not even agree on how many
|
||||
// transactions to spend (dolt takes two read transactions, embeddeddolt one).
|
||||
// Only the status tally is shared, through
|
||||
// internal/storage/issueops.ScanIssueCountsInTx. So a disagreement between the
|
||||
// two stores is reachable here in a way it is not for Counter.
|
||||
//
|
||||
// (There is a FOURTH copy of that arithmetic, unreachable: package-level
|
||||
// issueops.GetStatisticsInTx has no callers at all. Nothing here runs it.)
|
||||
// THREE WIRINGS, AND HERE THAT REALLY IS THREE VOTES. For most roles dolt and
|
||||
// embeddeddolt share one body (internal/workapi/store*) and "both stores
|
||||
// agree" is one vote plus an engine check. That is still true of the ROLE
|
||||
// layer here: both stores hand back internal/workapi/storestats. But the
|
||||
// queries it delegates to are written out THREE times — dolt/queries.go,
|
||||
// embeddeddolt/statistics.go and domain/db/issue.go each spell the blocked
|
||||
// count and the ready subtraction themselves. Only the status tally is shared,
|
||||
// through internal/storage/issueops.ScanIssueCountsInTx. So a disagreement
|
||||
// between the two stores is reachable here in a way it is not for Counter.
|
||||
//
|
||||
// EVERY WORKSPACE-WIDE CASE ASSERTS A DELTA, never an absolute. The summary
|
||||
// takes no predicate — that is the point of the role — so there is no IDFilter
|
||||
// to scope it with the way the Counter contract scopes its cases, and the
|
||||
// three fixtures each share one database with the other role suites that ran
|
||||
// before them. A before/after pair around a known seed is the only assertion
|
||||
// that is about THIS case's rows. The assignee-scoped cases are the exception
|
||||
// and do assert absolutes: each takes an assignee namespaced by the fixture
|
||||
// prefix, which no other case can seed.
|
||||
// takes no predicate, and the three fixtures each share one database with the
|
||||
// other role suites that ran before them. The assignee-scoped cases are the
|
||||
// exception and do assert absolutes: each takes an assignee namespaced by the
|
||||
// fixture prefix, which no other case can seed.
|
||||
//
|
||||
// What is deliberately NOT here:
|
||||
// - the fold from an actor's rows to a summary, which is shared by all three
|
||||
// through internal/workapi.FoldStatsAssigneeSummary and pinned directly,
|
||||
// without a database, in internal/workapi/stats_test.go;
|
||||
// - the flag-to-request mapping, which is `bd status`'s job;
|
||||
// - whether the two halves of an assignee-scoped answer are one snapshot,
|
||||
// which statsreporter.go deliberately does not promise because the store
|
||||
// seam cannot offer it.
|
||||
// What is deliberately NOT here: the fold from an actor's rows to a summary,
|
||||
// pinned without a database in internal/workapi/stats_test.go; the
|
||||
// flag-to-request mapping, which is `bd status`'s job; and whether the two
|
||||
// halves of an assignee-scoped answer are one snapshot, which statsreporter.go
|
||||
// deliberately does not promise because the store seam cannot offer it.
|
||||
|
||||
// StatsReporterFixture supplies adapter-specific storage access for the
|
||||
// summary assertions. Every field is named and typed exactly like the
|
||||
// per-backend roleFixtureKit hook it is filled from, so a wiring is kit plus
|
||||
// accessor plus prefix with no adapter in between.
|
||||
// per-backend roleFixtureKit hook it is filled from.
|
||||
type StatsReporterFixture struct {
|
||||
// IssuePrefix namespaces the ids and the assignees each assertion seeds,
|
||||
// so several of them can share one database.
|
||||
|
|
@ -62,13 +48,12 @@ type StatsReporterFixture struct {
|
|||
StatsReporter publicops.StatsReporter
|
||||
// CreateIssue seeds a durable issue in the issues plane.
|
||||
CreateIssue func(context.Context, *types.Issue, string) error
|
||||
// CreateWisp seeds an ephemeral issue in the wisps plane. It is a separate
|
||||
// field rather than an Ephemeral flag on CreateIssue because the three
|
||||
// adapters reach the two planes through different verbs.
|
||||
// CreateWisp seeds an ephemeral issue in the wisps plane; it is separate
|
||||
// because the three adapters reach the two planes through different verbs.
|
||||
CreateWisp func(context.Context, *types.Issue, string) error
|
||||
// AddDependency seeds ONE edge, which is how a case makes a row blocked:
|
||||
// the blocked count reads the denormalized is_blocked flag the edge insert
|
||||
// maintains, and there is no other way to set it through a public seam.
|
||||
// maintains, and no public seam sets it any other way.
|
||||
AddDependency func(context.Context, *types.Dependency, string) error
|
||||
// CountHistory reports how many history entries the fixture's branch has.
|
||||
// A nil hook means "this backend cannot observe history", and the case
|
||||
|
|
@ -79,12 +64,8 @@ type StatsReporterFixture struct {
|
|||
// RunStatsReporterCountsEveryDurableRowByStatus pins statsreporter.go:92-98:
|
||||
// one scan of the durable plane, every row in Total including closed ones, and
|
||||
// PinnedIssues counting a flag that overlaps a status bucket rather than
|
||||
// naming a sixth status.
|
||||
//
|
||||
// The pinned row seeded here is OPEN, deliberately. A pinned row that was also
|
||||
// closed would leave "does pinned overlap or replace a status bucket"
|
||||
// unanswered, and that overlap is the clause a reader is most likely to get
|
||||
// wrong: the buckets do not sum to Total in either direction.
|
||||
// naming a sixth status. The pinned row seeded here is OPEN, deliberately: the
|
||||
// buckets do not sum to Total in either direction.
|
||||
func RunStatsReporterCountsEveryDurableRowByStatus(t *testing.T, ctx context.Context, fixture StatsReporterFixture) {
|
||||
t.Helper()
|
||||
before := statsReporterSummary(t, ctx, fixture, publicops.StatsRequest{})
|
||||
|
|
@ -106,12 +87,9 @@ func RunStatsReporterCountsEveryDurableRowByStatus(t *testing.T, ctx context.Con
|
|||
// RunStatsReporterExcludesTheWispTier pins statsreporter.go:116-119: the
|
||||
// workspace-wide answer counts the durable plane only.
|
||||
//
|
||||
// It is the same A/B the Counter contract runs on its own default, and for the
|
||||
// same reason: the storage seam MERGES the two planes unless told not to, so
|
||||
// "durable only" is an active decision on every summary rather than something
|
||||
// that falls out of doing nothing. The assignee-scoped case below is the other
|
||||
// half of the pair — the two methods answer differently here, and that is the
|
||||
// contract.
|
||||
// The storage seam MERGES the two planes unless told not to, so "durable only"
|
||||
// is an active decision on every summary. The assignee-scoped case below is the
|
||||
// other half of the pair: the two methods answer differently here.
|
||||
func RunStatsReporterExcludesTheWispTier(t *testing.T, ctx context.Context, fixture StatsReporterFixture) {
|
||||
t.Helper()
|
||||
before := statsReporterSummary(t, ctx, fixture, publicops.StatsRequest{})
|
||||
|
|
@ -128,13 +106,9 @@ func RunStatsReporterExcludesTheWispTier(t *testing.T, ctx context.Context, fixt
|
|||
// RunStatsReporterAStatusOutsideTheTalliesIsCountedOnlyInTotal pins the second
|
||||
// half of statsreporter.go:92-98 — the tallies are exact equality against the
|
||||
// stored status, so a row whose status is none of the four lands in Total and
|
||||
// in no bucket, and the buckets do not sum to Total.
|
||||
//
|
||||
// It uses the "blocked" STATUS to do it, which makes this case do double duty:
|
||||
// that row is also the control for the case below. It has no dependency edge,
|
||||
// so its is_blocked flag is 0 and it must NOT move BlockedIssues either. A
|
||||
// backend that counted the status instead of the flag fails here, at the seed
|
||||
// that looks least like a blocked issue.
|
||||
// in no bucket. It uses the "blocked" STATUS, so that row doubles as the
|
||||
// control for the case below: with no dependency edge its is_blocked flag is 0
|
||||
// and it must NOT move BlockedIssues either.
|
||||
func RunStatsReporterAStatusOutsideTheTalliesIsCountedOnlyInTotal(t *testing.T, ctx context.Context, fixture StatsReporterFixture) {
|
||||
t.Helper()
|
||||
before := statsReporterSummary(t, ctx, fixture, publicops.StatsRequest{})
|
||||
|
|
@ -148,11 +122,8 @@ func RunStatsReporterAStatusOutsideTheTalliesIsCountedOnlyInTotal(t *testing.T,
|
|||
// RunStatsReporterBlockedCountsTheGraphNotTheStatus pins
|
||||
// statsreporter.go:99-102: BlockedIssues counts rows whose transitive
|
||||
// is_blocked flag is set, and an open row with an unfinished blocker is one of
|
||||
// them while its status is still "open".
|
||||
//
|
||||
// Both seeded rows are OPEN, so the case fails in an unmistakable way if a
|
||||
// backend ever counted the status: the delta it would report is zero blocked
|
||||
// out of two open rows.
|
||||
// them while its status is still "open". Both seeded rows are OPEN, so a
|
||||
// backend that counted the status reports zero blocked out of two open rows.
|
||||
func RunStatsReporterBlockedCountsTheGraphNotTheStatus(t *testing.T, ctx context.Context, fixture StatsReporterFixture) {
|
||||
t.Helper()
|
||||
before := statsReporterSummary(t, ctx, fixture, publicops.StatsRequest{})
|
||||
|
|
@ -169,12 +140,9 @@ func RunStatsReporterBlockedCountsTheGraphNotTheStatus(t *testing.T, ctx context
|
|||
|
||||
// RunStatsReporterReadyIsOpenMinusBlocked pins statsreporter.go:103-108:
|
||||
// ReadyIssues is arithmetic over two numbers in the same answer, not a query.
|
||||
//
|
||||
// The identity is asserted on the ABSOLUTE summary rather than on a delta,
|
||||
// because it is a property of every answer this role gives and not of the rows
|
||||
// this case seeded. The seed is here so the three numbers are not trivially
|
||||
// equal: without a blocked row, Ready == Open would hold under an
|
||||
// implementation that never subtracted anything.
|
||||
// The identity is asserted on the ABSOLUTE summary because it is a property of
|
||||
// every answer this role gives; the seed is here so that without a blocked row
|
||||
// Ready == Open cannot hold vacuously.
|
||||
func RunStatsReporterReadyIsOpenMinusBlocked(t *testing.T, ctx context.Context, fixture StatsReporterFixture) {
|
||||
t.Helper()
|
||||
blocker := statsReporterSeed(fixture, "arith-blocker", types.StatusOpen)
|
||||
|
|
@ -200,10 +168,9 @@ func RunStatsReporterReadyIsOpenMinusBlocked(t *testing.T, ctx context.Context,
|
|||
}
|
||||
}
|
||||
|
||||
// RunStatsReporterSkipBlockedPairsTheTwoPointers pins the whole of the
|
||||
// SkipBlocked promise (statsreporter.go:138-154), which is stated from the
|
||||
// ANSWER's side because the backends genuinely differ on whether they can take
|
||||
// the hint:
|
||||
// RunStatsReporterSkipBlockedPairsTheTwoPointers pins the SkipBlocked promise
|
||||
// (statsreporter.go:138-154), stated from the ANSWER's side because the
|
||||
// backends differ on whether they can take the hint:
|
||||
//
|
||||
// - the two pointers are nil together or populated together, never one of
|
||||
// each — every front door renders on exactly that pairing;
|
||||
|
|
@ -211,12 +178,9 @@ func RunStatsReporterReadyIsOpenMinusBlocked(t *testing.T, ctx context.Context,
|
|||
// - a populated pair means the hint was not taken, which is a legal answer
|
||||
// and not a failure.
|
||||
//
|
||||
// So this case does NOT assert that the fast path was used. It asserts what a
|
||||
// caller may rely on regardless, on all three backends, with no park. Today
|
||||
// the two store backends take the hint (GetStatisticsNoBlocked) and the
|
||||
// unit-of-work backend does not (domain.IssueUseCase publishes no no-blocked
|
||||
// query); a reader wanting to know which is which reads the wiring, not this
|
||||
// case.
|
||||
// So this case does NOT assert that the fast path was used. Today the two
|
||||
// store backends take the hint (GetStatisticsNoBlocked) and the unit-of-work
|
||||
// backend does not (domain.IssueUseCase publishes no no-blocked query).
|
||||
func RunStatsReporterSkipBlockedPairsTheTwoPointers(t *testing.T, ctx context.Context, fixture StatsReporterFixture) {
|
||||
t.Helper()
|
||||
seedStatsReporterIssue(t, ctx, fixture, statsReporterSeed(fixture, "hint-open", types.StatusOpen))
|
||||
|
|
@ -237,20 +201,16 @@ func RunStatsReporterSkipBlockedPairsTheTwoPointers(t *testing.T, ctx context.Co
|
|||
}
|
||||
}
|
||||
|
||||
// Nothing else moves. Compared against the full call taken immediately
|
||||
// before, on a fixture only this suite writes to.
|
||||
// Nothing else moves, compared against the full call taken immediately
|
||||
// before.
|
||||
assertStatsReporterDelta(t, full, skipped, statsReporterCounts{})
|
||||
}
|
||||
|
||||
// RunStatsReporterExtendedFieldsAreAlwaysZero pins statsreporter.go:109-114:
|
||||
// EpicsEligibleForClosure and AverageLeadTime are always zero because no
|
||||
// implementation computes either.
|
||||
//
|
||||
// It is a tripwire rather than a behavior test, and it is worth a case
|
||||
// precisely because it can only fail on GOOD news: the day a backend starts
|
||||
// computing one of them, this fails and the doc that calls it always zero — and
|
||||
// the `bd status` render branch that has never fired — get revisited in the
|
||||
// same change rather than left saying something false.
|
||||
// implementation computes either. A tripwire that can only fail on good news —
|
||||
// the day a backend starts computing one, the doc that calls it always zero
|
||||
// and the `bd status` render branch that has never fired get revisited.
|
||||
func RunStatsReporterExtendedFieldsAreAlwaysZero(t *testing.T, ctx context.Context, fixture StatsReporterFixture) {
|
||||
t.Helper()
|
||||
summary := statsReporterSummary(t, ctx, fixture, publicops.StatsRequest{})
|
||||
|
|
@ -265,11 +225,9 @@ func RunStatsReporterExtendedFieldsAreAlwaysZero(t *testing.T, ctx context.Conte
|
|||
}
|
||||
|
||||
// RunStatsReporterWritesNothing pins statsreporter.go:121-125: reporting is a
|
||||
// read, so neither method records a history entry.
|
||||
//
|
||||
// The delta is taken around BOTH methods together. An absolute count would be
|
||||
// meaningless on a fixture other cases have already seeded, and the seeds this
|
||||
// case needs are taken before the first reading for the same reason.
|
||||
// read, so neither method records a history entry. The delta is taken around
|
||||
// BOTH methods together; an absolute count would be meaningless on a fixture
|
||||
// other cases have already seeded.
|
||||
func RunStatsReporterWritesNothing(t *testing.T, ctx context.Context, fixture StatsReporterFixture) {
|
||||
t.Helper()
|
||||
if fixture.CountHistory == nil {
|
||||
|
|
@ -301,11 +259,8 @@ func RunStatsReporterWritesNothing(t *testing.T, ctx context.Context, fixture St
|
|||
// RunStatsReporterAssigneeStatsScopesToOneActor pins the first and last
|
||||
// bullets of statsreporter.go:159-179: the answer is one actor's rows, and
|
||||
// PinnedIssues is always zero on this path along with the two fields that are
|
||||
// always zero everywhere.
|
||||
//
|
||||
// The assignee is namespaced by the fixture prefix, so this case can assert
|
||||
// ABSOLUTE numbers where the workspace-wide cases cannot: no other case in any
|
||||
// role suite can seed a row for it.
|
||||
// always zero everywhere. The assignee is namespaced by the fixture prefix, so
|
||||
// this case can assert ABSOLUTE numbers where the workspace-wide cases cannot.
|
||||
func RunStatsReporterAssigneeStatsScopesToOneActor(t *testing.T, ctx context.Context, fixture StatsReporterFixture) {
|
||||
t.Helper()
|
||||
mine := statsReporterAssignee(fixture, "scope-mine")
|
||||
|
|
@ -347,15 +302,12 @@ func RunStatsReporterAssigneeStatsScopesToOneActor(t *testing.T, ctx context.Con
|
|||
}
|
||||
|
||||
// RunStatsReporterAssigneeBlockedCountsTheStatusNotTheGraph pins the exact
|
||||
// INVERSE of the workspace-wide blocked clause, which is the sharpest
|
||||
// statement this contract makes: statsreporter.go:169-172 says an
|
||||
// assignee-scoped BlockedIssues counts rows whose STATUS is "blocked", where
|
||||
// the workspace-wide one counts the is_blocked flag.
|
||||
// INVERSE of the workspace-wide blocked clause: statsreporter.go:169-172 says
|
||||
// an assignee-scoped BlockedIssues counts rows whose STATUS is "blocked",
|
||||
// where the workspace-wide one counts the is_blocked flag.
|
||||
//
|
||||
// Both seeds belong to the same actor. One has the status and no edge; the
|
||||
// other has an edge and the status "open". The answer must be 1, and the two
|
||||
// backends' bodies can only get it right by using the fold rather than the
|
||||
// aggregate.
|
||||
// other has an edge and the status "open". The answer must be 1.
|
||||
func RunStatsReporterAssigneeBlockedCountsTheStatusNotTheGraph(t *testing.T, ctx context.Context, fixture StatsReporterFixture) {
|
||||
t.Helper()
|
||||
assignee := statsReporterAssignee(fixture, "abl")
|
||||
|
|
@ -383,8 +335,7 @@ func RunStatsReporterAssigneeBlockedCountsTheStatusNotTheGraph(t *testing.T, ctx
|
|||
|
||||
// RunStatsReporterAssigneeStatsMergesTheWispTier pins the first bullet of
|
||||
// statsreporter.go:163-168: this answer's set spans the durable plane AND the
|
||||
// ephemeral tier, where the workspace-wide answer is durable-only. It is the
|
||||
// other half of the A/B RunStatsReporterExcludesTheWispTier starts.
|
||||
// ephemeral tier, where the workspace-wide answer is durable-only.
|
||||
func RunStatsReporterAssigneeStatsMergesTheWispTier(t *testing.T, ctx context.Context, fixture StatsReporterFixture) {
|
||||
t.Helper()
|
||||
assignee := statsReporterAssignee(fixture, "amerge")
|
||||
|
|
@ -411,9 +362,9 @@ func RunStatsReporterAssigneeStatsMergesTheWispTier(t *testing.T, ctx context.Co
|
|||
// FoldStatsAssigneeSummary exists to guarantee: on this path BlockedIssues and
|
||||
// ReadyIssues are ALWAYS non-nil, including for an actor with no rows at all.
|
||||
//
|
||||
// The nil pointers are the workspace-wide answer's skipped-scan signal and
|
||||
// every front door renders them as "(skipped)". An assignee summary skips
|
||||
// nothing, so a nil here would print a lie about a query that ran.
|
||||
// A nil is the workspace-wide answer's skipped-scan signal, rendered as
|
||||
// "(skipped)". An assignee summary skips nothing, so a nil here would print a
|
||||
// lie about a query that ran.
|
||||
func RunStatsReporterAssigneeStatsPopulatesBothPointers(t *testing.T, ctx context.Context, fixture StatsReporterFixture) {
|
||||
t.Helper()
|
||||
summary := statsReporterAssigneeSummary(t, ctx, fixture, statsReporterAssignee(fixture, "nobody"))
|
||||
|
|
@ -432,11 +383,9 @@ func RunStatsReporterAssigneeStatsPopulatesBothPointers(t *testing.T, ctx contex
|
|||
// RunStatsReporterAssigneeStatsRefusesAnEmptyAssignee pins
|
||||
// statsreporter.go:46-51: an empty or whitespace-only assignee is
|
||||
// ErrValidation rather than a query for the rows whose assignee column is
|
||||
// empty.
|
||||
//
|
||||
// The whitespace case is the one that matters. An implementation that checked
|
||||
// `assignee == ""` would pass the first and answer the second with a summary
|
||||
// of nothing, which reads exactly like an actor who has no work.
|
||||
// empty. The whitespace case is the one that matters — an implementation that
|
||||
// checked `assignee == ""` would answer it with a summary of nothing, which
|
||||
// reads exactly like an actor who has no work.
|
||||
func RunStatsReporterAssigneeStatsRefusesAnEmptyAssignee(t *testing.T, ctx context.Context, fixture StatsReporterFixture) {
|
||||
t.Helper()
|
||||
for _, blank := range []string{"", " ", "\t"} {
|
||||
|
|
@ -447,9 +396,7 @@ func RunStatsReporterAssigneeStatsRefusesAnEmptyAssignee(t *testing.T, ctx conte
|
|||
}
|
||||
}
|
||||
|
||||
// statsReporterCounts is the delta a workspace-wide case expects. Every field
|
||||
// is named so a failure reads as "OpenIssues moved by 2, want 1" rather than
|
||||
// as two summaries a reader has to diff.
|
||||
// statsReporterCounts is the delta a workspace-wide case expects.
|
||||
type statsReporterCounts struct {
|
||||
total int
|
||||
open int
|
||||
|
|
@ -461,13 +408,10 @@ type statsReporterCounts struct {
|
|||
}
|
||||
|
||||
// assertStatsReporterDelta compares two summaries field by field against the
|
||||
// movement a case seeded.
|
||||
//
|
||||
// The blocked delta is only checked when BOTH summaries carry the number: a
|
||||
// skipped scan reports nil, and the pairing case above is where that is
|
||||
// asserted. Ready is not checked here at all — it is arithmetic over two
|
||||
// fields this function already compares, and
|
||||
// RunStatsReporterReadyIsOpenMinusBlocked pins the arithmetic itself.
|
||||
// movement a case seeded. The blocked delta is only checked when BOTH
|
||||
// summaries carry the number, because a skipped scan reports nil; Ready is not
|
||||
// checked here at all — RunStatsReporterReadyIsOpenMinusBlocked pins the
|
||||
// arithmetic itself.
|
||||
func assertStatsReporterDelta(t *testing.T, before, after types.Statistics, want statsReporterCounts) {
|
||||
t.Helper()
|
||||
for _, field := range []struct {
|
||||
|
|
@ -494,8 +438,7 @@ func assertStatsReporterDelta(t *testing.T, before, after types.Statistics, want
|
|||
}
|
||||
}
|
||||
|
||||
// statsReporterSeed builds one issue with the fixture's prefix on its id, so
|
||||
// several cases can share a database.
|
||||
// statsReporterSeed builds one issue with the fixture's prefix on its id.
|
||||
func statsReporterSeed(fixture StatsReporterFixture, suffix string, status types.Status) *types.Issue {
|
||||
id := fixture.IssuePrefix + "-" + suffix
|
||||
return &types.Issue{
|
||||
|
|
@ -507,8 +450,7 @@ func statsReporterSeed(fixture StatsReporterFixture, suffix string, status types
|
|||
}
|
||||
}
|
||||
|
||||
// statsReporterAssignee namespaces an actor to this fixture, which is what
|
||||
// lets the assignee-scoped cases assert absolute numbers.
|
||||
// statsReporterAssignee namespaces an actor to this fixture.
|
||||
func statsReporterAssignee(fixture StatsReporterFixture, suffix string) string {
|
||||
return fixture.IssuePrefix + "-actor-" + suffix
|
||||
}
|
||||
|
|
@ -527,9 +469,7 @@ func seedStatsReporterWisp(t *testing.T, ctx context.Context, fixture StatsRepor
|
|||
}
|
||||
}
|
||||
|
||||
// blockStatsReporterIssue makes issueID blocked by dependsOnID. The edge is
|
||||
// the only public way to set the denormalized flag the workspace-wide blocked
|
||||
// count reads.
|
||||
// blockStatsReporterIssue makes issueID blocked by dependsOnID.
|
||||
func blockStatsReporterIssue(t *testing.T, ctx context.Context, fixture StatsReporterFixture, issueID, dependsOnID string) {
|
||||
t.Helper()
|
||||
if err := fixture.AddDependency(ctx, &types.Dependency{
|
||||
|
|
@ -560,9 +500,7 @@ func statsReporterAssigneeSummary(t *testing.T, ctx context.Context, fixture Sta
|
|||
}
|
||||
|
||||
// statsReporterPointer reads one of the two nullable counts, failing loudly
|
||||
// when it is absent. A case that dereferenced it directly would panic on a
|
||||
// backend that answered nil, and the panic would name this file rather than
|
||||
// the clause that was broken.
|
||||
// when it is absent rather than panicking on the dereference.
|
||||
func statsReporterPointer(t *testing.T, name string, value *int) int {
|
||||
t.Helper()
|
||||
if value == nil {
|
||||
|
|
|
|||
|
|
@ -20,20 +20,17 @@ import (
|
|||
//
|
||||
// THERE ARE TWO BODIES BEHIND THE THREE WIRINGS. dolt and embeddeddolt share
|
||||
// internal/storage/issueops.SweepInTx and differ only in how they reach a
|
||||
// transaction; the unit-of-work provider reaches the same four questions
|
||||
// through the domain use cases and is genuinely separate code. So the wirings
|
||||
// are one vote plus an engine check, and a second independent vote — and the
|
||||
// selection half of both votes runs through the SAME internal/workapi
|
||||
// functions, which is why the cases below spend their assertions on what only
|
||||
// a real backend can show: which rows are actually gone, what a dry run left
|
||||
// alone, and whether the version-control plane recorded anything.
|
||||
// transaction; the unit-of-work provider goes through the domain use cases and
|
||||
// is genuinely separate code. So the wirings are one vote plus an engine check,
|
||||
// and a second independent vote — and the selection half of both votes runs
|
||||
// through the SAME internal/workapi functions. The cases below therefore spend
|
||||
// their assertions on what only a real backend can show: which rows are gone,
|
||||
// what a dry run left alone, what the version-control plane recorded.
|
||||
//
|
||||
// EVERY CASE SCOPES ITSELF WITH AN ID PATTERN, and here that is not hygiene
|
||||
// but a precondition. A sweep is asked of a whole TIER, so a case that swept
|
||||
// without a pattern would delete the rows the next case seeded — and, on the
|
||||
// ephemeral tier, would be a legal unfiltered request that the role does not
|
||||
// refuse. Each Run therefore seeds under fixture.IssuePrefix + its own tag and
|
||||
// passes that tag as SweepRequest.IDPattern.
|
||||
// EVERY CASE SCOPES ITSELF WITH AN ID PATTERN, which is a precondition rather
|
||||
// than hygiene. A sweep is asked of a whole TIER, so a case that swept without
|
||||
// a pattern would delete the rows the next case seeded — and on the ephemeral
|
||||
// tier that is a legal unfiltered request the role does not refuse.
|
||||
//
|
||||
// EVERY CASE PINS closed_at EXPLICITLY. The recheck the role performs is
|
||||
// against a cutoff, and a seeded row whose closed_at defaulted to "now" would
|
||||
|
|
@ -41,8 +38,7 @@ import (
|
|||
|
||||
// SweeperFixture supplies adapter-specific storage access for the
|
||||
// bulk-clearance assertions. Every field is named and typed exactly like the
|
||||
// per-backend roleFixtureKit hook it is filled from, so a wiring is kit plus
|
||||
// accessor plus prefix with no adapter in between.
|
||||
// per-backend roleFixtureKit hook it is filled from.
|
||||
type SweeperFixture struct {
|
||||
// IssuePrefix namespaces the ids each assertion seeds, so several of them
|
||||
// can share one database.
|
||||
|
|
@ -56,8 +52,7 @@ type SweeperFixture struct {
|
|||
// adapters reach the two planes through different verbs.
|
||||
CreateWisp func(context.Context, *types.Issue, string) error
|
||||
// QueryScalar runs a single-row query and scans it. It is how these cases
|
||||
// observe the ONE thing a sweep result cannot be trusted to report about
|
||||
// itself: whether the rows are really gone.
|
||||
// observe whether the rows are really gone.
|
||||
QueryScalar func(context.Context, string, []any, ...any) error
|
||||
// CountHistory reports how many history entries the fixture's branch has.
|
||||
// A nil hook means "this backend cannot observe history", and the case
|
||||
|
|
@ -66,9 +61,8 @@ type SweeperFixture struct {
|
|||
}
|
||||
|
||||
// sweeperClosedAt is the stamp every seeded candidate carries, and
|
||||
// sweeperCutoff is an instant strictly after it. Fixed values rather than
|
||||
// offsets from time.Now so the cutoff cases assert an interval rather than
|
||||
// race the clock.
|
||||
// sweeperCutoff is an instant strictly after it. Fixed rather than offsets from
|
||||
// time.Now so the cutoff cases do not race the clock.
|
||||
var (
|
||||
sweeperClosedAt = time.Date(2026, 3, 1, 12, 0, 0, 0, time.UTC)
|
||||
sweeperCutoff = time.Date(2026, 4, 1, 12, 0, 0, 0, time.UTC)
|
||||
|
|
@ -76,13 +70,11 @@ var (
|
|||
|
||||
// RunSweeperRefusesAnUnfilteredDurableSweep pins the safety invariant the role
|
||||
// took off the CLI (issueops/sweeper.go:59-73): a durable sweep with neither a
|
||||
// cutoff nor a pattern is ErrValidation, and it is the WHOLE POINT of the
|
||||
// guard living below the front doors that this is asserted at the role rather
|
||||
// than at a handler.
|
||||
// cutoff nor a pattern is ErrValidation, asserted at the role rather than at a
|
||||
// handler so a second front door inherits it.
|
||||
//
|
||||
// It asserts the refusal AND its effect. A guard that returned an error after
|
||||
// deleting would satisfy an errors.Is assertion perfectly, and on this
|
||||
// operation that is the failure worth spending a seeded row to rule out.
|
||||
// It asserts the refusal AND its effect: a guard that returned an error after
|
||||
// deleting would satisfy an errors.Is assertion perfectly.
|
||||
func RunSweeperRefusesAnUnfilteredDurableSweep(t *testing.T, ctx context.Context, fixture SweeperFixture) {
|
||||
t.Helper()
|
||||
id := sweeperSeedClosedIssue(t, ctx, fixture, "gate", false)
|
||||
|
|
@ -98,8 +90,8 @@ func RunSweeperRefusesAnUnfilteredDurableSweep(t *testing.T, ctx context.Context
|
|||
sweeperAssertIssueRows(t, ctx, fixture, 1, id)
|
||||
|
||||
// The ephemeral tier carries no such gate: an unfiltered sweep of closed
|
||||
// wisps is the ordinary use of `bd purge`. Asked with a pattern that
|
||||
// matches nothing so the case does not clear another case's seeds.
|
||||
// wisps is the ordinary use of `bd purge`. Asked with a pattern that matches
|
||||
// nothing so the case does not clear another case's seeds.
|
||||
if _, err := fixture.Sweeper.Sweep(ctx, publicops.SweepRequest{
|
||||
Tier: publicops.SweepEphemeral,
|
||||
IDPattern: fixture.IssuePrefix + "-gate-nothing-*",
|
||||
|
|
@ -112,10 +104,9 @@ func RunSweeperRefusesAnUnfilteredDurableSweep(t *testing.T, ctx context.Context
|
|||
// (issueops/sweeper.go): an unset or unrecognized Tier, and an IDPattern that
|
||||
// is not a well-formed glob.
|
||||
//
|
||||
// The pattern case is a DEFECT FIX with teeth. Both front doors used to
|
||||
// discard filepath.Match's error, so `--pattern '['` reported "nothing to
|
||||
// prune" — indistinguishable from a correct pattern over an empty set, on a
|
||||
// command whose entire job is to delete what it matched.
|
||||
// The pattern case is a DEFECT FIX: both front doors used to discard
|
||||
// filepath.Match's error, so `--pattern '['` reported "nothing to prune",
|
||||
// indistinguishable from a correct pattern over an empty set.
|
||||
func RunSweeperRefusesAMalformedRequest(t *testing.T, ctx context.Context, fixture SweeperFixture) {
|
||||
t.Helper()
|
||||
for _, test := range []struct {
|
||||
|
|
@ -136,12 +127,9 @@ func RunSweeperRefusesAMalformedRequest(t *testing.T, ctx context.Context, fixtu
|
|||
|
||||
// RunSweeperClearsOneTierAndLeavesTheOther pins the disjointness that makes
|
||||
// `bd purge` and `bd prune` ONE capability with a tier parameter
|
||||
// (issueops/sweeper.go, SweepTier): a sweep of one tier can never touch a row
|
||||
// of the other.
|
||||
//
|
||||
// Both planes are seeded with ids the SAME pattern admits, so a body that
|
||||
// forgot the tier — or that let the pattern do the work the filter should do —
|
||||
// deletes the wrong rows rather than merely reporting a wrong number.
|
||||
// (issueops/sweeper.go, SweepTier). Both planes are seeded with ids the SAME
|
||||
// pattern admits, so a body that forgot the tier deletes the wrong rows rather
|
||||
// than merely reporting a wrong number.
|
||||
func RunSweeperClearsOneTierAndLeavesTheOther(t *testing.T, ctx context.Context, fixture SweeperFixture) {
|
||||
t.Helper()
|
||||
issueID := sweeperSeedClosedIssue(t, ctx, fixture, "tier", false)
|
||||
|
|
@ -194,11 +182,9 @@ func RunSweeperProtectsPinnedRows(t *testing.T, ctx context.Context, fixture Swe
|
|||
|
||||
// RunSweeperHonorsTheCutoffAndThePattern pins the two narrowing fields.
|
||||
//
|
||||
// The CUTOFF is HALF-OPEN, and that is asserted rather than assumed: a row
|
||||
// closed exactly at the cutoff is KEPT (issueops.SweepRequest.ClosedBefore,
|
||||
// "strictly before"). An off-by-one there deletes a bead closed the instant a
|
||||
// scheduled sweep names, which is the one row a caller reasoning about the
|
||||
// boundary is thinking of.
|
||||
// The CUTOFF is HALF-OPEN: a row closed exactly at the cutoff is KEPT
|
||||
// (issueops.SweepRequest.ClosedBefore, "strictly before"). An off-by-one there
|
||||
// deletes a bead closed the instant a scheduled sweep names.
|
||||
//
|
||||
// The PATTERN is matched in Go rather than translated to SQL, so the case
|
||||
// includes a character class — the construct a LIKE translation would get
|
||||
|
|
@ -237,14 +223,11 @@ func RunSweeperHonorsTheCutoffAndThePattern(t *testing.T, ctx context.Context, f
|
|||
sweeperAssertIssueRows(t, ctx, fixture, 1, outOfClass)
|
||||
}
|
||||
|
||||
// RunSweeperDryRunChangesNothing pins the promise a preview is worth reading
|
||||
// for (issueops.Sweeper.Sweep, "A DRY RUN CHANGES NOTHING"): the preview
|
||||
// reports the same counts the real sweep goes on to report, and leaves every
|
||||
// row where it was.
|
||||
//
|
||||
// The two are compared against EACH OTHER rather than against a literal,
|
||||
// because that is the property a caller relies on — a preview whose number
|
||||
// differs from the run it precedes is worse than no preview.
|
||||
// RunSweeperDryRunChangesNothing pins issueops.Sweeper.Sweep's "A DRY RUN
|
||||
// CHANGES NOTHING": the preview reports the same counts the real sweep goes on
|
||||
// to report, and leaves every row where it was. The two are compared against
|
||||
// EACH OTHER rather than against a literal, because that is the property a
|
||||
// caller relies on.
|
||||
func RunSweeperDryRunChangesNothing(t *testing.T, ctx context.Context, fixture SweeperFixture) {
|
||||
t.Helper()
|
||||
ids := []string{
|
||||
|
|
@ -265,8 +248,8 @@ func RunSweeperDryRunChangesNothing(t *testing.T, ctx context.Context, fixture S
|
|||
}
|
||||
sweeperAssertIssueRows(t, ctx, fixture, 2, ids...)
|
||||
|
||||
// A second preview: a dry run that had deleted anything would report a
|
||||
// smaller number here, which is the failure this repetition rules out.
|
||||
// A second preview: a dry run that had deleted anything reports a smaller
|
||||
// number here.
|
||||
if again := sweeperSweep(t, ctx, fixture, sweeperWithDryRun(request, true)); again.Swept != preview.Swept {
|
||||
t.Fatalf("second preview Swept = %d, first = %d: the first preview changed the store", again.Swept, preview.Swept)
|
||||
}
|
||||
|
|
@ -287,13 +270,11 @@ func RunSweeperDryRunChangesNothing(t *testing.T, ctx context.Context, fixture S
|
|||
// not-done bead's description is held back, counted, and named in the bounded
|
||||
// sample — and the SAME request without the protection deletes it.
|
||||
//
|
||||
// The two halves matter together. Asserting only the protection would pass for
|
||||
// an implementation that skipped every candidate; asserting only the
|
||||
// unprotected sweep would pass for one that never scanned at all.
|
||||
//
|
||||
// The citation is at a WORD BOUNDARY and there is a near-miss beside it, so an
|
||||
// implementation that fell back to a bare substring search protects a row
|
||||
// nothing cites.
|
||||
// The two halves matter together: asserting only the protection would pass for
|
||||
// an implementation that skipped every candidate, and asserting only the
|
||||
// unprotected sweep would pass for one that never scanned at all. The citation
|
||||
// is at a WORD BOUNDARY with a near-miss beside it, so an implementation that
|
||||
// fell back to a bare substring search protects a row nothing cites.
|
||||
func RunSweeperProtectsCitedRows(t *testing.T, ctx context.Context, fixture SweeperFixture) {
|
||||
t.Helper()
|
||||
cited := sweeperSeed(t, ctx, fixture, sweeperIssue(fixture, "ref", "cited", false), nil)
|
||||
|
|
@ -302,12 +283,12 @@ func RunSweeperProtectsCitedRows(t *testing.T, ctx context.Context, fixture Swee
|
|||
citing := sweeperIssue(fixture, "ref", "live", false)
|
||||
citing.Status = types.StatusOpen
|
||||
citing.ClosedAt = nil
|
||||
// The near-miss: `<cited>x` must NOT protect anything, and the parenthesised
|
||||
// The near-miss `<free>x` must NOT protect anything; the parenthesised
|
||||
// occurrence must.
|
||||
citing.Description = fmt.Sprintf("superseded by (%s). unrelated: %sx", cited, free)
|
||||
// The citing bead is OPEN, so the pattern below must not admit it as a
|
||||
// candidate — it would be skipped by the closed recheck either way, but a
|
||||
// case that relied on that would be asserting the wrong protection.
|
||||
// candidate: the closed recheck would skip it either way, but a case relying
|
||||
// on that would be asserting the wrong protection.
|
||||
sweeperSeedOpen(t, ctx, fixture, citing)
|
||||
|
||||
request := publicops.SweepRequest{
|
||||
|
|
@ -331,7 +312,7 @@ func RunSweeperProtectsCitedRows(t *testing.T, ctx context.Context, fixture Swee
|
|||
|
||||
// Without the protection the same candidate goes, and nothing is reported
|
||||
// as protected — a caller reading Referenced=0 without having asked has
|
||||
// learned nothing, which the field doc says out loud.
|
||||
// learned nothing.
|
||||
request.ProtectReferenced = false
|
||||
result = sweeperSweep(t, ctx, fixture, request)
|
||||
if result.Skipped.Referenced != 0 {
|
||||
|
|
@ -345,8 +326,7 @@ func RunSweeperProtectsCitedRows(t *testing.T, ctx context.Context, fixture Swee
|
|||
|
||||
// RunSweeperEmptyMatchIsZeroAndNil pins the not-found story
|
||||
// (issueops.Sweeper.Sweep, "A REQUEST THAT MATCHES NOTHING"): a zero result and
|
||||
// a nil error, which is the answer a scheduled sweep gets every time it runs
|
||||
// after the first.
|
||||
// a nil error.
|
||||
func RunSweeperEmptyMatchIsZeroAndNil(t *testing.T, ctx context.Context, fixture SweeperFixture) {
|
||||
t.Helper()
|
||||
for _, tier := range []publicops.SweepTier{publicops.SweepDurable, publicops.SweepEphemeral} {
|
||||
|
|
@ -376,8 +356,7 @@ func RunSweeperEmptyMatchIsZeroAndNil(t *testing.T, ctx context.Context, fixture
|
|||
// "AT MOST" rather than "exactly" is the honest promise across these backends:
|
||||
// the server-backed store records a Dolt commit, the embedded one commits
|
||||
// outside the SQL transaction and records none here, and an ephemeral sweep
|
||||
// touches only tables the version-control plane ignores. A case demanding
|
||||
// exactly one would be asserting a property of one wiring.
|
||||
// touches only tables the version-control plane ignores.
|
||||
func RunSweeperRecordsAtMostOneHistoryEntry(t *testing.T, ctx context.Context, fixture SweeperFixture) {
|
||||
t.Helper()
|
||||
if fixture.CountHistory == nil {
|
||||
|
|
@ -448,8 +427,8 @@ func RunSweeperDoesNotMutateTheCallerRequest(t *testing.T, ctx context.Context,
|
|||
|
||||
// --- fixture helpers -------------------------------------------------------
|
||||
|
||||
// sweeperPattern is the glob that scopes one case's ids, and the reason every
|
||||
// case has one: a sweep is asked of a whole tier.
|
||||
// sweeperPattern is the glob that scopes one case's ids: a sweep is asked of a
|
||||
// whole tier, so every case needs one.
|
||||
func sweeperPattern(fixture SweeperFixture, tag string) string {
|
||||
return fixture.IssuePrefix + "-" + tag + "-*"
|
||||
}
|
||||
|
|
@ -468,8 +447,8 @@ func sweeperIssue(fixture SweeperFixture, tag, name string, ephemeral bool) *typ
|
|||
}
|
||||
|
||||
// sweeperSeed writes one issue through the plane its Ephemeral flag names and
|
||||
// returns its id. mutate runs on the issue before it is written, which is how
|
||||
// a case seeds a pinned row or moves a closed_at.
|
||||
// returns its id. mutate runs before the write, which is how a case seeds a
|
||||
// pinned row or moves a closed_at.
|
||||
func sweeperSeed(t *testing.T, ctx context.Context, fixture SweeperFixture, issue *types.Issue, mutate func(*types.Issue)) string {
|
||||
t.Helper()
|
||||
if mutate != nil {
|
||||
|
|
@ -517,8 +496,7 @@ func sweeperSweep(t *testing.T, ctx context.Context, fixture SweeperFixture, req
|
|||
|
||||
// sweeperAssertIssueRows counts the named ids in the ISSUES plane. It is the
|
||||
// only assertion in this file that does not trust the result the sweep
|
||||
// reported about itself, which on a destructive operation is the assertion
|
||||
// that matters.
|
||||
// reported about itself.
|
||||
func sweeperAssertIssueRows(t *testing.T, ctx context.Context, fixture SweeperFixture, want int, ids ...string) {
|
||||
t.Helper()
|
||||
sweeperAssertRows(t, ctx, fixture, "issues", want, ids...)
|
||||
|
|
|
|||
|
|
@ -15,60 +15,42 @@ import (
|
|||
// wiring site with skipKnownDivergence so the case still runs on the ones that
|
||||
// agree.
|
||||
//
|
||||
// THIS CONTRACT HAS A DIFFERENT SHAPE FROM THE ISSUE CONTRACTS, and copying one
|
||||
// of those wholesale would have produced the wrong test. The issue roles assert
|
||||
// ISSUE STATE: seed rows, run the operation, read the rows back. Nothing here
|
||||
// has rows to seed. What this plane promises is PRECEDENCE — which of two
|
||||
// writes a later read sees, and whether a refusal leaves the earlier value
|
||||
// standing — and SIDE EFFECTS: two of its keys are PROJECTED into normalized
|
||||
// lookup tables that reads consult before the key itself, so "the write
|
||||
// succeeded" and "the write took effect" are separate facts and the second one
|
||||
// is the one that was broken. Every projection case therefore reads the TABLE
|
||||
// through QueryScalar rather than reading the setting back through the role,
|
||||
// because reading it back through the role is exactly the check that passed on
|
||||
// a backend where nothing took effect.
|
||||
// THIS CONTRACT HAS A DIFFERENT SHAPE FROM THE ISSUE CONTRACTS: there are no
|
||||
// rows to seed. What this plane promises is PRECEDENCE and SIDE EFFECTS — two
|
||||
// of its keys are PROJECTED into normalized lookup tables that reads consult
|
||||
// before the key itself, so "the write succeeded" and "the write took effect"
|
||||
// are separate facts. Every projection case therefore reads the TABLE through
|
||||
// QueryScalar; reading the setting back through the role is exactly the check
|
||||
// that passed on a backend where nothing took effect.
|
||||
//
|
||||
// There are three wirings — the server-backed store, the embedded store and the
|
||||
// unit-of-work provider — and only TWO independent bodies between them: dolt
|
||||
// and embeddeddolt both hand back internal/workapi/storeworkspaceconfig and
|
||||
// project through their own SetConfig, so they are one vote plus an engine
|
||||
// check; the unit-of-work provider is the second, and it projects in the config
|
||||
// repository its use case sits on. All three share the refusals, which come
|
||||
// from workapi.ValidateSettingWrite, so what these cases can catch below that
|
||||
// and embeddeddolt both hand back internal/workapi/storeworkspaceconfig, so
|
||||
// they are one vote plus an engine check. All three share the refusals, which
|
||||
// come from workapi.ValidateSettingWrite, so what these cases catch below that
|
||||
// validator is the EXECUTION half.
|
||||
//
|
||||
// KEYS ARE NAMESPACED WITH THE FIXTURE PREFIX wherever they can be. Config keys
|
||||
// are global to a workspace — there is no per-test plane — so an unscoped probe
|
||||
// key would be an assertion about state a sibling case wrote. The two keys that
|
||||
// CANNOT be namespaced are status.custom and types.custom: their whole point is
|
||||
// that those exact names are projected, so the projection cases write the real
|
||||
// keys and each one asserts the EXACT resulting table content rather than a
|
||||
// delta. That is safe because a write rewrites the table outright, which is
|
||||
// itself one of the promises under test.
|
||||
// KEYS ARE NAMESPACED WITH THE FIXTURE PREFIX wherever they can be, because
|
||||
// config keys are global to a workspace. status.custom and types.custom cannot
|
||||
// be: their whole point is that those exact names are projected, so those cases
|
||||
// write the real keys and assert the EXACT resulting table content rather than
|
||||
// a delta — safe because a write rewrites the table outright.
|
||||
//
|
||||
// What is deliberately NOT here:
|
||||
// - which SOURCE owns a key (config.yaml, git config, this plane). That is
|
||||
// front-door routing over files on the client's machine and the role says
|
||||
// so; cmd/bd/config.go performs it and cmd/bd/config_test.go pins it.
|
||||
// - the multi-source views (`bd config show`, `drift`, `apply`, `validate`),
|
||||
// which are not on this role at all.
|
||||
// - the process-local caches the store backends drop on a write. They are one
|
||||
// backend's optimization, not a promise of the plane, and a second process
|
||||
// cannot observe them.
|
||||
// NOT here: which SOURCE owns a key, and the multi-source views over it
|
||||
// (`bd config show`, `drift`, `apply`, `validate`). That is front-door routing
|
||||
// over files on the client's machine; cmd/bd/config_test.go pins it.
|
||||
|
||||
// WorkspaceConfigFixture supplies adapter-specific storage access for the
|
||||
// settings assertions. Every field is named and typed exactly like the
|
||||
// per-backend roleFixtureKit hook it is filled from, so a wiring is kit plus
|
||||
// accessor plus prefix with no adapter in between.
|
||||
// per-backend roleFixtureKit hook it is filled from.
|
||||
type WorkspaceConfigFixture struct {
|
||||
// IssuePrefix namespaces the keys each assertion writes, so several of them
|
||||
// can share one database.
|
||||
IssuePrefix string
|
||||
WorkspaceConfig publicops.WorkspaceConfig
|
||||
// SetConfig writes one workspace config key OUT OF BAND, past the role. It
|
||||
// is how the one case that removes the protected key puts it back, since
|
||||
// the role refuses to write it — the same seam a workspace's own
|
||||
// initialization uses.
|
||||
// SetConfig writes one workspace config key OUT OF BAND, past the role —
|
||||
// the same seam a workspace's own initialization uses. It is how the case
|
||||
// that removes the protected key puts it back.
|
||||
SetConfig func(context.Context, string, string) error
|
||||
// QueryScalar runs a single-row query and scans it, and RETURNS the error
|
||||
// rather than failing the test. It is how the projection cases read the
|
||||
|
|
@ -81,15 +63,11 @@ type WorkspaceConfigFixture struct {
|
|||
}
|
||||
|
||||
// RunWorkspaceConfigStoresAValueVerbatim pins workspaceconfig.go:93-100: a
|
||||
// successful write stores the value as given, and the result says so, so a
|
||||
// caller may treat SetSetting as "what I sent is what is stored" without
|
||||
// re-reading it.
|
||||
// successful write stores the value as given, and the result says so.
|
||||
//
|
||||
// The value carries surrounding space and an inner comma on purpose. Both are
|
||||
// characters this plane's other keys give meaning to — the comma separates
|
||||
// entries in status.custom and types.custom — so a body that reached for a
|
||||
// splitter or a trimmer on the general path would be caught here rather than on
|
||||
// the one key where the behavior is correct.
|
||||
// The value carries surrounding space and an inner comma on purpose: the comma
|
||||
// separates entries in status.custom and types.custom, so a body that reached
|
||||
// for a splitter or a trimmer on the general path is caught here.
|
||||
func RunWorkspaceConfigStoresAValueVerbatim(t *testing.T, ctx context.Context, fixture WorkspaceConfigFixture) {
|
||||
t.Helper()
|
||||
key := workspaceConfigKey(fixture, "verbatim")
|
||||
|
|
@ -103,8 +81,8 @@ func RunWorkspaceConfigStoresAValueVerbatim(t *testing.T, ctx context.Context, f
|
|||
}
|
||||
|
||||
// RunWorkspaceConfigReplacesAnExistingValue pins workspaceconfig.go's "Set
|
||||
// stores one setting, REPLACING any value already there": the plane holds one
|
||||
// value per key, and a second write is not an append and not a refusal.
|
||||
// stores one setting, REPLACING any value already there": one value per key, so
|
||||
// a second write is not an append and not a refusal.
|
||||
func RunWorkspaceConfigReplacesAnExistingValue(t *testing.T, ctx context.Context, fixture WorkspaceConfigFixture) {
|
||||
t.Helper()
|
||||
key := workspaceConfigKey(fixture, "replace")
|
||||
|
|
@ -119,9 +97,8 @@ func RunWorkspaceConfigReplacesAnExistingValue(t *testing.T, ctx context.Context
|
|||
// for BOTH a key nothing ever wrote and a key written as the empty string, and
|
||||
// there is no ErrNotFound on this role.
|
||||
//
|
||||
// It is asserted rather than left implicit because it is the promise a caller
|
||||
// is most likely to assume the other way round, and because the conflation is
|
||||
// what lets `bd config get` print "(not set)" for a key that was in fact set.
|
||||
// The conflation is what lets `bd config get` print "(not set)" for a key that
|
||||
// was in fact set.
|
||||
func RunWorkspaceConfigConflatesAnUnsetKeyWithAnEmptyValue(t *testing.T, ctx context.Context, fixture WorkspaceConfigFixture) {
|
||||
t.Helper()
|
||||
never := workspaceConfigKey(fixture, "never-written")
|
||||
|
|
@ -131,10 +108,9 @@ func RunWorkspaceConfigConflatesAnUnsetKeyWithAnEmptyValue(t *testing.T, ctx con
|
|||
setWorkspaceConfigSetting(t, ctx, fixture, emptied, "")
|
||||
assertWorkspaceConfigValue(t, ctx, fixture, emptied, "")
|
||||
|
||||
// The two are the same ANSWER, but they are not the same row: the written
|
||||
// one is present in the enumeration and the never-written one is not. That
|
||||
// is the only way a caller can tell them apart on this role, so it is
|
||||
// pinned here beside the conflation it qualifies.
|
||||
// The two are the same ANSWER, but not the same row: the written one is
|
||||
// present in the enumeration and the never-written one is not. That is the
|
||||
// only way a caller can tell them apart on this role.
|
||||
settings := listWorkspaceConfigSettings(t, ctx, fixture)
|
||||
if _, ok := settings[emptied]; !ok {
|
||||
t.Fatalf("ListSettings omits %q, which was written as the empty string", emptied)
|
||||
|
|
@ -183,8 +159,7 @@ func RunWorkspaceConfigUnsetRemovesTheSetting(t *testing.T, ctx context.Context,
|
|||
|
||||
// RunWorkspaceConfigUnsetOfAnAbsentKeySucceeds pins workspaceconfig.go's
|
||||
// "Removing a key nothing set SUCCEEDS": UnsetSetting states an intended end
|
||||
// state, so a caller clearing configuration it is not sure was ever written
|
||||
// does not have to classify an error to learn it was already absent.
|
||||
// state, not a fact about the row it found.
|
||||
func RunWorkspaceConfigUnsetOfAnAbsentKeySucceeds(t *testing.T, ctx context.Context, fixture WorkspaceConfigFixture) {
|
||||
t.Helper()
|
||||
key := workspaceConfigKey(fixture, "absent")
|
||||
|
|
@ -204,9 +179,8 @@ func RunWorkspaceConfigUnsetOfAnAbsentKeySucceeds(t *testing.T, ctx context.Cont
|
|||
}
|
||||
|
||||
// RunWorkspaceConfigRefusesAnEmptyKey pins the empty-key refusal on all three
|
||||
// verbs that take one, and pins it as ErrValidation rather than as any error:
|
||||
// the front doors classify on that sentinel to tell a caller's mistake from a
|
||||
// storage failure.
|
||||
// verbs that take one, as ErrValidation rather than as any error: the front
|
||||
// doors classify on that sentinel to tell a mistake from a storage failure.
|
||||
func RunWorkspaceConfigRefusesAnEmptyKey(t *testing.T, ctx context.Context, fixture WorkspaceConfigFixture) {
|
||||
t.Helper()
|
||||
for _, blank := range []string{"", " "} {
|
||||
|
|
@ -226,19 +200,16 @@ func RunWorkspaceConfigRefusesAnEmptyKey(t *testing.T, ctx context.Context, fixt
|
|||
// will not write, in BOTH spellings, and pins that the refusal leaves the
|
||||
// stored prefix standing.
|
||||
//
|
||||
// The second half is the half that matters. A refusal that had already written
|
||||
// would be worse than no refusal at all: the workspace would be re-prefixed AND
|
||||
// the caller told it had not been. Every fixture is initialized with a prefix,
|
||||
// so this reads the value back rather than asserting absence.
|
||||
// A refusal that had already written would be worse than no refusal at all: the
|
||||
// workspace would be re-prefixed AND the caller told it had not been.
|
||||
func RunWorkspaceConfigRefusesTheProtectedKeyOnSet(t *testing.T, ctx context.Context, fixture WorkspaceConfigFixture) {
|
||||
t.Helper()
|
||||
before := getWorkspaceConfigSetting(t, ctx, fixture, publicops.SettingKeyIssuePrefix)
|
||||
|
||||
for _, test := range []struct{ key, want string }{
|
||||
// The underscored spelling keeps whatever the workspace was
|
||||
// initialized with; the dashed one is a key nothing has ever written,
|
||||
// so a write that slipped through would show up as a value where there
|
||||
// was none.
|
||||
// The underscored spelling keeps whatever the workspace was initialized
|
||||
// with; the dashed one was never written, so a write that slipped
|
||||
// through shows up as a value where there was none.
|
||||
{publicops.SettingKeyIssuePrefix, before},
|
||||
{"issue-prefix", ""},
|
||||
} {
|
||||
|
|
@ -253,11 +224,9 @@ func RunWorkspaceConfigRefusesTheProtectedKeyOnSet(t *testing.T, ctx context.Con
|
|||
// workspaceconfig.go's UnsetSetting doc records as bd-yby99.34: Set refuses the
|
||||
// prefix and Unset does not.
|
||||
//
|
||||
// It is pinned rather than fixed because refusing it is a user-visible change
|
||||
// this slice was not approved to make, and pinning is what keeps the asymmetry
|
||||
// from being read as an accident — or from being closed on one backend and not
|
||||
// the others while the owner decides. The prefix is restored afterwards, since
|
||||
// every later case in the suite shares the workspace.
|
||||
// It is pinned rather than fixed because refusing it is a user-visible change,
|
||||
// and pinning keeps it from being closed on one backend and not the others. The
|
||||
// prefix is restored afterwards, since the suite shares the workspace.
|
||||
func RunWorkspaceConfigUnsetDoesNotRefuseTheProtectedKey(t *testing.T, ctx context.Context, fixture WorkspaceConfigFixture) {
|
||||
t.Helper()
|
||||
before := getWorkspaceConfigSetting(t, ctx, fixture, publicops.SettingKeyIssuePrefix)
|
||||
|
|
@ -268,8 +237,7 @@ func RunWorkspaceConfigUnsetDoesNotRefuseTheProtectedKey(t *testing.T, ctx conte
|
|||
unsetWorkspaceConfigSetting(t, ctx, fixture, publicops.SettingKeyIssuePrefix)
|
||||
assertWorkspaceConfigValue(t, ctx, fixture, publicops.SettingKeyIssuePrefix, "")
|
||||
|
||||
// Restored out of band, through the same seam a workspace's own
|
||||
// initialization uses, because the role refuses to write it back.
|
||||
// Restored out of band, because the role refuses to write it back.
|
||||
if err := fixture.SetConfig(ctx, publicops.SettingKeyIssuePrefix, before); err != nil {
|
||||
t.Fatalf("restore %s to %q: %v", publicops.SettingKeyIssuePrefix, before, err)
|
||||
}
|
||||
|
|
@ -279,20 +247,18 @@ func RunWorkspaceConfigUnsetDoesNotRefuseTheProtectedKey(t *testing.T, ctx conte
|
|||
// RunWorkspaceConfigRefusesAnUnparseableCustomStatus pins the one value-shape
|
||||
// refusal this plane makes, and pins that NOTHING is written when it fires.
|
||||
//
|
||||
// "Nothing" is two things here, and they are asserted separately because a body
|
||||
// could get one right and the other wrong: the config row keeps its previous
|
||||
// value, AND the custom_statuses table keeps its previous contents. The
|
||||
// projection is what makes the second one possible to break — a body that wrote
|
||||
// the row first and parsed while projecting would leave a stored status set
|
||||
// that no read agrees with.
|
||||
// "Nothing" is two things, asserted separately: the config row keeps its
|
||||
// previous value, AND custom_statuses keeps its previous contents. A body that
|
||||
// wrote the row first and parsed while projecting would leave a stored status
|
||||
// set that no read agrees with.
|
||||
func RunWorkspaceConfigRefusesAnUnparseableCustomStatus(t *testing.T, ctx context.Context, fixture WorkspaceConfigFixture) {
|
||||
t.Helper()
|
||||
const good = "awaiting_review:active"
|
||||
setWorkspaceConfigSetting(t, ctx, fixture, publicops.SettingKeyStatusCustom, good)
|
||||
assertWorkspaceConfigTableCount(t, ctx, fixture, "custom_statuses", 1)
|
||||
|
||||
// A built-in name: refused by the parser, and refused for a reason a caller
|
||||
// could plausibly hit rather than a syntactic accident.
|
||||
// A built-in name: refused by the parser, for a reason a caller could
|
||||
// plausibly hit rather than a syntactic accident.
|
||||
if _, err := fixture.WorkspaceConfig.SetSetting(ctx, publicops.SetSettingRequest{
|
||||
Key: publicops.SettingKeyStatusCustom, Value: "open",
|
||||
}); !errors.Is(err, publicops.ErrValidation) {
|
||||
|
|
@ -314,16 +280,14 @@ func RunWorkspaceConfigProjectsCustomStatuses(t *testing.T, ctx context.Context,
|
|||
}
|
||||
|
||||
// RunWorkspaceConfigProjectsCustomTypes is the same pin for types.custom, and
|
||||
// it is the case that FAILED on the unit-of-work backend before this role
|
||||
// existed: that route wrote the string and left custom_types holding the
|
||||
// previous set, so `bd config set types.custom` reported success and
|
||||
// `bd create -t <the new type>` kept answering "invalid issue type" forever —
|
||||
// with doctor re-verifying against the string and reporting all-OK.
|
||||
// it FAILED on the unit-of-work backend before this role existed: that route
|
||||
// wrote the string and left custom_types holding the previous set, so
|
||||
// `bd config set types.custom` reported success while `bd create -t <the new
|
||||
// type>` kept answering "invalid issue type" and doctor reported all-OK.
|
||||
//
|
||||
// The three-stage sequence pins the REWRITE rather than an insert: a second
|
||||
// write replaces the first set instead of adding to it, and the empty value
|
||||
// clears the table. A body that appended would pass an assertion that only ever
|
||||
// grew the set.
|
||||
// clears the table.
|
||||
func RunWorkspaceConfigProjectsCustomTypes(t *testing.T, ctx context.Context, fixture WorkspaceConfigFixture) {
|
||||
t.Helper()
|
||||
setWorkspaceConfigSetting(t, ctx, fixture, publicops.SettingKeyTypesCustom, "research")
|
||||
|
|
@ -343,9 +307,8 @@ func RunWorkspaceConfigProjectsCustomTypes(t *testing.T, ctx context.Context, fi
|
|||
// key that configured a projection does NOT undo the projection, so the custom
|
||||
// types keep applying after the setting that named them is gone.
|
||||
//
|
||||
// All three implementations agree, so this is the plane's behavior rather than
|
||||
// a divergence, and pinning it is what keeps it from being quietly fixed on one
|
||||
// backend — which would leave a workspace's answer depending on which route
|
||||
// All three implementations agree, so pinning it keeps it from being quietly
|
||||
// fixed on one backend, which would make the answer depend on which route
|
||||
// removed the key.
|
||||
func RunWorkspaceConfigUnsetLeavesTheProjectionBehind(t *testing.T, ctx context.Context, fixture WorkspaceConfigFixture) {
|
||||
t.Helper()
|
||||
|
|
@ -356,8 +319,7 @@ func RunWorkspaceConfigUnsetLeavesTheProjectionBehind(t *testing.T, ctx context.
|
|||
assertWorkspaceConfigValue(t, ctx, fixture, publicops.SettingKeyTypesCustom, "")
|
||||
assertWorkspaceConfigTableCount(t, ctx, fixture, "custom_types", 1)
|
||||
|
||||
// Left as this case found it, so a later case in the shared suite reads the
|
||||
// plane rather than this one's residue.
|
||||
// Left as this case found it: the suite shares the workspace.
|
||||
setWorkspaceConfigSetting(t, ctx, fixture, publicops.SettingKeyTypesCustom, "")
|
||||
assertWorkspaceConfigTableCount(t, ctx, fixture, "custom_types", 0)
|
||||
unsetWorkspaceConfigSetting(t, ctx, fixture, publicops.SettingKeyTypesCustom)
|
||||
|
|
@ -368,8 +330,7 @@ func RunWorkspaceConfigUnsetLeavesTheProjectionBehind(t *testing.T, ctx context.
|
|||
// history entry behind either.
|
||||
//
|
||||
// The delta is taken around the refusal rather than read off the top of the
|
||||
// log, for the reason the kit's CountHistory doc gives: two commits made inside
|
||||
// one second tie on date and their order is not something to rely on.
|
||||
// log: two commits made inside one second tie on date.
|
||||
func RunWorkspaceConfigARefusedWriteRecordsNoHistory(t *testing.T, ctx context.Context, fixture WorkspaceConfigFixture) {
|
||||
t.Helper()
|
||||
if fixture.CountHistory == nil {
|
||||
|
|
@ -399,9 +360,7 @@ func RunWorkspaceConfigARefusedWriteRecordsNoHistory(t *testing.T, ctx context.C
|
|||
}
|
||||
}
|
||||
|
||||
// workspaceConfigKey namespaces a probe key under the fixture's prefix. Config
|
||||
// keys are global to a workspace, so an unscoped one would be an assertion
|
||||
// about whatever a sibling case last wrote.
|
||||
// workspaceConfigKey namespaces a probe key under the fixture's prefix.
|
||||
func workspaceConfigKey(fixture WorkspaceConfigFixture, name string) string {
|
||||
return "custom." + fixture.IssuePrefix + "-" + name
|
||||
}
|
||||
|
|
@ -451,9 +410,8 @@ func listWorkspaceConfigSettings(t *testing.T, ctx context.Context, fixture Work
|
|||
}
|
||||
|
||||
// assertWorkspaceConfigTableCount reads a normalized projection table directly.
|
||||
// The role gives no way to read one, deliberately — it is a projection, not a
|
||||
// setting — so this is the only assertion that can tell "the value was stored"
|
||||
// from "the value took effect".
|
||||
// The role deliberately gives no way to read one, so this is the only assertion
|
||||
// that can tell "the value was stored" from "the value took effect".
|
||||
//
|
||||
// The table name is interpolated because a table name cannot be a bind
|
||||
// parameter; both call sites pass a literal from this file.
|
||||
|
|
|
|||
|
|
@ -160,11 +160,10 @@ func runPruneSweep(t *testing.T, r cascadeRunner) pruneSweepOutcome {
|
|||
// the two shapes it actually runs — wh-gate-sweep's gate purge, and the
|
||||
// wisp-decay close+purge pair.
|
||||
//
|
||||
// It was written while the answer was YES. Proxied `bd delete` used to pass
|
||||
// Cascade:true unconditionally and refuse the --cascade flag outright, so each
|
||||
// scenario pinned two different outcomes and the gate case characterized live
|
||||
// data loss. bd-x82so put both routes on issueops.Deleter with the flag the
|
||||
// caller typed, so every scenario here now pins ONE outcome for both modes.
|
||||
// It was written while the answer was YES: proxied `bd delete` passed
|
||||
// Cascade:true unconditionally and refused the --cascade flag outright.
|
||||
// bd-x82so put both routes on issueops.Deleter with the flag the caller typed,
|
||||
// so every scenario here now pins ONE outcome for both modes.
|
||||
//
|
||||
// Both scenarios are still replayed against a classic embedded workspace and a
|
||||
// proxied one and the outcomes compared, so a re-divergence is reported as a
|
||||
|
|
@ -174,11 +173,9 @@ func TestProxiedServerCascadeParity(t *testing.T) {
|
|||
t.Parallel()
|
||||
bd := buildEmbeddedBD(t)
|
||||
|
||||
// THE CUTOVER BLOCKER THIS FILE WAS WRITTEN FOR, now closed.
|
||||
//
|
||||
// Proxied `bd delete <gate> --force` used to delete the bead the gate was
|
||||
// gating and everything downstream of it, because the proxied route passed
|
||||
// Cascade:true unconditionally. On wh-gate-sweep's fixture that was not a
|
||||
// THE CUTOVER BLOCKER THIS FILE WAS WRITTEN FOR, now closed. Proxied
|
||||
// `bd delete <gate> --force` used to delete the bead the gate was gating and
|
||||
// everything downstream of it. On wh-gate-sweep's fixture that was not a
|
||||
// nuance: the sweep's third step is `bd delete <gate> --force`, and
|
||||
// `bd gate create --blocks <target>` makes the gated bead a DEPENDENT of the
|
||||
// gate, so that step destroyed the work it had just unblocked.
|
||||
|
|
|
|||
|
|
@ -8,15 +8,11 @@ import (
|
|||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// The closed-candidate recheck used to live here in full, shared by `bd gc`,
|
||||
// `bd purge` and `bd prune`. purge and prune are behind issueops.Sweeper now
|
||||
// and the role applies it below both front doors; `bd gc` is not, so what is
|
||||
// left here is a thin call into the SAME pure function
|
||||
// (workapi.FilterSweepCandidates) plus gc's own warning line.
|
||||
//
|
||||
// One definition, two callers: gc and the role cannot come to disagree about
|
||||
// what "a closed bead safe to delete" means, which is exactly the drift this
|
||||
// file existed to prevent between purge and prune in the first place.
|
||||
// `bd gc` is the one caller left that is not behind issueops.Sweeper, so what
|
||||
// is here is a thin call into the SAME pure function
|
||||
// (workapi.FilterSweepCandidates) the role applies below both front doors,
|
||||
// plus gc's own warning line. One definition, two callers: gc and the role
|
||||
// cannot come to disagree about what "a closed bead safe to delete" means.
|
||||
|
||||
type closedDeletionCandidateStats = issueops.SweepSkips
|
||||
|
||||
|
|
|
|||
|
|
@ -216,10 +216,8 @@ var configSetCmd = &cobra.Command{
|
|||
|
||||
// Everything above this line is FRONT-DOOR routing: which source owns
|
||||
// the key, and whether writing it to a file on this machine would leak
|
||||
// a secret into git. None of it is answerable from a substrate, because
|
||||
// two of the three sources are files this process can see and a server
|
||||
// cannot. From here the key is known to belong to the workspace
|
||||
// database, and the write is the role's.
|
||||
// a secret into git. From here the key is known to belong to the
|
||||
// workspace database, and the write is the role's.
|
||||
settings, err := openWorkspaceConfig("config set requires direct database access")
|
||||
if err != nil {
|
||||
return HandleError("%v", err)
|
||||
|
|
@ -250,8 +248,8 @@ var configSetCmd = &cobra.Command{
|
|||
// store's for the direct route and the provider's for the proxied one.
|
||||
//
|
||||
// directRequirement is the message `ensureDirectMode` reports when a workspace
|
||||
// is reachable by neither route; it is per-verb because the shipped text names
|
||||
// the verb, and those strings are what a user sees.
|
||||
// is reachable by neither route. It is per-verb because the shipped text names
|
||||
// the verb.
|
||||
func openWorkspaceConfig(directRequirement string) (issueops.WorkspaceConfig, error) {
|
||||
if usesProxiedServer() {
|
||||
return proxiedWorkspaceConfig()
|
||||
|
|
@ -265,11 +263,9 @@ func openWorkspaceConfig(directRequirement string) (issueops.WorkspaceConfig, er
|
|||
// noteDirectConfigWrite marks the invocation as having written, which is what
|
||||
// the auto-commit epilogue in main.go keys on.
|
||||
//
|
||||
// It is DIRECT-ROUTE ONLY, and that is preserved rather than tidied: a proxied
|
||||
// write already committed inside the role's own unit of work, so flagging it
|
||||
// here would ask the epilogue to commit a second time on a route that has
|
||||
// nothing outstanding. The two routes genuinely differ here, which is why this
|
||||
// is the one line of the config commands that still asks which route it is on.
|
||||
// It is DIRECT-ROUTE ONLY: a proxied write already committed inside the role's
|
||||
// own unit of work, so flagging it here would ask the epilogue to commit a
|
||||
// second time on a route that has nothing outstanding.
|
||||
func noteDirectConfigWrite() {
|
||||
if !usesProxiedServer() {
|
||||
commandDidWrite.Store(true)
|
||||
|
|
@ -382,8 +378,7 @@ var configGetCmd = &cobra.Command{
|
|||
})
|
||||
}
|
||||
// "(not set)" also prints for a key stored as the empty string: the
|
||||
// role answers "" for both and issueops.SettingResult.Value says why it
|
||||
// does not distinguish them. This is the shipped wording, kept.
|
||||
// role answers "" for both, and issueops.SettingResult.Value says why.
|
||||
if result.Value == "" {
|
||||
fmt.Printf("%s (not set)\n", result.Key)
|
||||
} else {
|
||||
|
|
@ -476,9 +471,8 @@ var configListCmd = &cobra.Command{
|
|||
}
|
||||
|
||||
// The OTHER sources, reported beside the stored ones rather than merged
|
||||
// into them. This is the boundary the role stops at: it answers for the
|
||||
// database, and config.yaml and the environment are read here because
|
||||
// they are files and variables of THIS process.
|
||||
// into them: the role answers for the database, and config.yaml and the
|
||||
// environment are files and variables of THIS process.
|
||||
showConfigYAMLOverrides(stored)
|
||||
return nil
|
||||
},
|
||||
|
|
@ -834,13 +828,10 @@ Examples:
|
|||
|
||||
for _, p := range pairs {
|
||||
// The same refusal `bd config set` makes, and it was MISSING here:
|
||||
// this command partitions its pairs by source and wrote the database
|
||||
// ones straight through, so `bd config set-many issue_prefix=x`
|
||||
// re-prefixed the workspace behind the guard the single-key verb
|
||||
// enforces. issueops.WorkspaceConfig refuses it at the substrate for
|
||||
// every caller that goes through the role; this verb does not (see
|
||||
// the write below), so it makes the refusal itself, with the same
|
||||
// message and before any pair is written.
|
||||
// `bd config set-many issue_prefix=x` re-prefixed the workspace
|
||||
// behind the guard the single-key verb enforces. This verb does not
|
||||
// go through issueops.WorkspaceConfig (see the write below), so it
|
||||
// makes the refusal itself, before any pair is written.
|
||||
if msg, rejected := rejectProtectedConfigKey(p.key); rejected {
|
||||
fmt.Fprintln(os.Stderr, msg)
|
||||
return SilentExit()
|
||||
|
|
@ -905,16 +896,8 @@ Examples:
|
|||
// property TestProxiedServerConfigSetMany pins: the whole batch is ONE
|
||||
// Dolt commit, which is the entire point of the verb ("faster and less
|
||||
// noisy than separate calls, especially in CI"). The role writes one
|
||||
// setting per call and commits each — that is what its contract says —
|
||||
// so routing this through it would turn a three-key batch into three
|
||||
// commits. A batched write is a different capability and gets a role of
|
||||
// its own if it ever needs one, exactly as `bd create --file` stays off
|
||||
// issueops.Lifecycle.Create.
|
||||
//
|
||||
// What it DOES borrow from the role is the refusal, applied above at
|
||||
// the front door: before that, `bd config set-many issue_prefix=x`
|
||||
// walked past the guard `bd config set` enforces and re-prefixed the
|
||||
// workspace.
|
||||
// setting per call and commits each, so routing this through it would
|
||||
// turn a three-key batch into three commits.
|
||||
if len(dbPairs) > 0 {
|
||||
if usesProxiedServer() {
|
||||
keys := make([]string, len(dbPairs))
|
||||
|
|
|
|||
|
|
@ -11,18 +11,13 @@ import (
|
|||
|
||||
// proxiedWorkspaceConfig hands back the guarded workspace-settings surface for
|
||||
// the proxied-server provider, through the provider's OWN capability accessor —
|
||||
// the same two-step proxiedCounter performs, and for the same reason: the
|
||||
// accessor is where each layer is added.
|
||||
// the same two-step proxiedCounter performs.
|
||||
//
|
||||
// This file used to hold a second copy of the four single-key `bd config`
|
||||
// verbs: each one opened its own unit of work, called the config use case and
|
||||
// then printed the same lines the direct route prints a hundred lines away.
|
||||
// One of those copies had drifted in a way no reader could see. The proxied
|
||||
// `set` validated `status.custom` and stored it, but nothing on this route
|
||||
// re-synchronized the custom_statuses and custom_types tables that reads
|
||||
// consult FIRST — so a proxied `bd config set types.custom` reported success
|
||||
// and never took effect. That duplication is gone: the route now differs by
|
||||
// which accessor answers.
|
||||
// Routing the four single-key `bd config` verbs through the role fixed a copy
|
||||
// that had drifted: the proxied `set` stored `status.custom` without
|
||||
// re-synchronizing the custom_statuses and custom_types tables that reads
|
||||
// consult FIRST, so a proxied `bd config set types.custom` reported success and
|
||||
// never took effect.
|
||||
func proxiedWorkspaceConfig() (issueops.WorkspaceConfig, error) {
|
||||
if uowProvider == nil {
|
||||
return nil, errors.New("proxied-server UOW provider not initialized")
|
||||
|
|
@ -41,9 +36,7 @@ func proxiedWorkspaceConfig() (issueops.WorkspaceConfig, error) {
|
|||
// rather than N, which is what makes it usable in CI — and
|
||||
// TestProxiedServerConfigSetMany pins it. issueops.WorkspaceConfig writes one
|
||||
// setting per call and commits each, as its contract says, so routing this
|
||||
// through it would turn a three-key batch into three commits. A batched write
|
||||
// is a different capability and would get a role of its own, exactly as
|
||||
// `bd create --file` stays off issueops.Lifecycle.Create.
|
||||
// through it would turn a three-key batch into three commits.
|
||||
//
|
||||
// It does NOT re-implement the role's refusals: cmd/bd/config.go applies them
|
||||
// to every pair, before any of them is written.
|
||||
|
|
|
|||
|
|
@ -56,10 +56,8 @@ Examples:
|
|||
}
|
||||
|
||||
// openCounter hands back the count role for whichever route this invocation is
|
||||
// on, each through its OWN capability accessor — the store's for the direct
|
||||
// route and the provider's for the proxied one. Neither branch builds a
|
||||
// filter, loads config or opens a unit of work: that is the whole of what
|
||||
// moved behind the role, and it used to be written out twice, once per route.
|
||||
// on, each through its own capability accessor. Neither branch builds a filter,
|
||||
// loads config or opens a unit of work.
|
||||
func openCounter() (issueops.Counter, error) {
|
||||
if usesProxiedServer() {
|
||||
return proxiedCounter()
|
||||
|
|
@ -67,10 +65,9 @@ func openCounter() (issueops.Counter, error) {
|
|||
return store.Counter()
|
||||
}
|
||||
|
||||
// parseCountRequest turns the flag set into the role's request. It is flag
|
||||
// parsing and nothing else: normalization of labels and ids, the wisp-tier
|
||||
// policy and the workspace's infra vocabulary all live behind the role, so the
|
||||
// two routes cannot come to disagree about them.
|
||||
// parseCountRequest turns the flag set into the role's request. Normalization
|
||||
// of labels and ids, the wisp-tier policy and the workspace's infra vocabulary
|
||||
// all live behind the role, so the two routes cannot come to disagree.
|
||||
func parseCountRequest(cmd *cobra.Command) (issueops.CountRequest, issueops.CountGroup, error) {
|
||||
groupBy, err := countGroupFlag(cmd)
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -11,20 +11,15 @@ import (
|
|||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// The filter semantics of `bd count` no longer live in this package: the
|
||||
// Counter role owns them, they are built once in workapi.BuildCountFilter, and
|
||||
// the cardinality-parity assertions that used to be here moved to
|
||||
// internal/workapi/count_test.go where they can compare the two SHARED
|
||||
// builders instead of a CLI helper against one of them.
|
||||
//
|
||||
// What is left here is what is still this package's job: turning flags into
|
||||
// the role's request, and refusing a flag combination the request cannot
|
||||
// express.
|
||||
// The filter semantics of `bd count` live in the Counter role now, built once
|
||||
// in workapi.BuildCountFilter, with the cardinality-parity assertions in
|
||||
// internal/workapi/count_test.go. What is left here is turning flags into the
|
||||
// role's request and refusing a combination the request cannot express.
|
||||
|
||||
// TestCountIncludeInfraFlagShape pins the flag's existence and default so
|
||||
// scripted callers keep byte-identical behavior (GH#4387). The no-flag path
|
||||
// carries IncludeInfra=false into the role, which is where the durable-only
|
||||
// default is now decided.
|
||||
// carries IncludeInfra=false into the role, where the durable-only default is
|
||||
// now decided.
|
||||
func TestCountIncludeInfraFlagShape(t *testing.T) {
|
||||
flag := countCmd.Flags().Lookup("include-infra")
|
||||
if flag == nil {
|
||||
|
|
@ -43,10 +38,10 @@ func TestCountIncludeInfraFlagShape(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestParseCountRequestCarriesEveryFilterFlag is the tripwire for the one
|
||||
// failure mode this seam has left: a flag that is registered, documented and
|
||||
// silently dropped on the way into the request. Every filter flag is set to a
|
||||
// value distinguishable from its zero and read back off the request.
|
||||
// TestParseCountRequestCarriesEveryFilterFlag is the tripwire for a flag that
|
||||
// is registered, documented and silently dropped on the way into the request.
|
||||
// Every filter flag is set to a value distinguishable from its zero and read
|
||||
// back off the request.
|
||||
func TestParseCountRequestCarriesEveryFilterFlag(t *testing.T) {
|
||||
flags := newCountFlagSet(t)
|
||||
for flag, value := range map[string]string{
|
||||
|
|
@ -90,7 +85,7 @@ func TestParseCountRequestCarriesEveryFilterFlag(t *testing.T) {
|
|||
// parseTimeFlag resolves a bare date in the LOCAL zone, which is what a
|
||||
// user typing --created-after 2026-01-01 means. The expectation says so
|
||||
// rather than normalizing to UTC, so a change to that resolution shows up
|
||||
// here instead of shifting every date bound by the test machine's offset.
|
||||
// here instead of shifting every bound by the test machine's offset.
|
||||
day := func(d int) *time.Time {
|
||||
stamp := time.Date(2026, 1, d, 0, 0, 0, 0, time.Local)
|
||||
return &stamp
|
||||
|
|
@ -128,8 +123,7 @@ func TestParseCountRequestCarriesEveryFilterFlag(t *testing.T) {
|
|||
|
||||
// TestParseCountRequestResolvesTheGroupingFlags pins each --by-* flag to its
|
||||
// dimension and the refusal for two at once. The exclusivity check cannot live
|
||||
// behind the role — by the time a request reaches it only one dimension is
|
||||
// left — so it is checked here, beside the flags it is about.
|
||||
// behind the role — by then only one dimension is left — so it is checked here.
|
||||
func TestParseCountRequestResolvesTheGroupingFlags(t *testing.T) {
|
||||
for flag, want := range map[string]issueops.CountGroup{
|
||||
"by-status": issueops.CountGroupStatus,
|
||||
|
|
@ -175,10 +169,8 @@ func TestParseCountRequestRejectsAnUnparseableDate(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// newCountFlagSet returns a command carrying `bd count`'s flags with every one
|
||||
// at its default, so a case can set exactly the flags it is about.
|
||||
//
|
||||
// It REGISTERS the flags rather than copying countCmd's set: cobra's
|
||||
// newCountFlagSet returns a command carrying `bd count`'s flags at their
|
||||
// defaults. It REGISTERS them rather than copying countCmd's set: cobra's
|
||||
// AddFlagSet shares the underlying *Flag values, so a case that set a flag on
|
||||
// the copy would leak it into the real command and into every later case.
|
||||
func newCountFlagSet(t *testing.T) *cobra.Command {
|
||||
|
|
|
|||
|
|
@ -1,12 +1,9 @@
|
|||
package main
|
||||
|
||||
// End-to-end cover for `bd create --file` on the DIRECT route, which is where
|
||||
// this command's behaviour actually changed when it moved onto
|
||||
// issueops.BatchCreator.
|
||||
//
|
||||
// They run the real bd binary against an isolated embedded-Dolt workspace, the
|
||||
// same way create_deps_atomic_test.go does, and reuse that file's hermetic
|
||||
// environment and output helpers.
|
||||
// this command's behaviour changed when it moved onto issueops.BatchCreator.
|
||||
// They run the real bd binary against an isolated embedded-Dolt workspace and
|
||||
// reuse create_deps_atomic_test.go's hermetic environment and output helpers.
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
|
@ -62,11 +59,10 @@ Second body.
|
|||
}
|
||||
})
|
||||
|
||||
// The Q11 change this commit exists for. The direct route used to hand the
|
||||
// whole slice to the store's batch create with no create-only guard and no
|
||||
// per-item content validation; a file the workspace refuses now refuses
|
||||
// WHOLE, so a caller can fix the file and re-run it without first working
|
||||
// out which half landed.
|
||||
// The direct route used to hand the whole slice to the store's batch create
|
||||
// with no create-only guard and no per-item content validation. A file the
|
||||
// workspace refuses now refuses WHOLE, so a caller can fix the file and
|
||||
// re-run it without working out which half landed.
|
||||
t.Run("a_refused_template_leaves_nothing_behind", func(t *testing.T) {
|
||||
plan := writeMarkdownPlan(t, dir, "half-bad.md", `## Lands before the refusal
|
||||
|
||||
|
|
@ -93,9 +89,8 @@ test-nosuchissue
|
|||
})
|
||||
|
||||
// --ephemeral is not in singleIssueOnlyFlags, so this route has always
|
||||
// ACCEPTED it. It used to build the issues without ever reading it, so a
|
||||
// caller who asked for scratch work got durable rows and no warning; the
|
||||
// proxied route has honoured it all along.
|
||||
// ACCEPTED it while building the issues without reading it: a caller who
|
||||
// asked for scratch work got durable rows and no warning.
|
||||
t.Run("ephemeral_is_honoured_rather_than_accepted_and_ignored", func(t *testing.T) {
|
||||
plan := writeMarkdownPlan(t, dir, "scratch.md", `## Scratch from file
|
||||
|
||||
|
|
@ -114,8 +109,7 @@ Ephemeral body.
|
|||
})
|
||||
|
||||
// The edges the file declares are written with the issues, in the same
|
||||
// transaction — including an edge onto an issue created EARLIER in the same
|
||||
// file, which a loop over single creates cannot do.
|
||||
// transaction — including an edge onto an issue created EARLIER in the file.
|
||||
t.Run("writes_the_edges_the_file_declares", func(t *testing.T) {
|
||||
blocker := strings.TrimSpace(runCreateDepsBD(t, bd, dir, "create", "file edge blocker", "--silent"))
|
||||
if blocker == "" {
|
||||
|
|
|
|||
|
|
@ -102,22 +102,12 @@ func runCreateProxiedSingle(_ *cobra.Command, ctx context.Context, in createInpu
|
|||
|
||||
issue := buildCreateIssueFromInput(in)
|
||||
// Labels ride on the issue because that is where the contract reads them:
|
||||
// CreateRequest.Issue documents them as authoritative, and the request's
|
||||
// own InheritLabelsFromParent adds the parent's inside the write
|
||||
// transaction rather than from a second read out here.
|
||||
// CreateRequest.Issue documents them as authoritative.
|
||||
issue.Labels = append([]string(nil), in.labels...)
|
||||
if err := inheritProxiedSourceRepo(ctx, issue, deps); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// THE CREATE IS NOT IMPLEMENTED HERE, and that is the point. Type and
|
||||
// status validation against the workspace's configured vocabulary, the
|
||||
// explicit-id prefix guard, infra-type wisp routing, child-id minting,
|
||||
// label inheritance, edge creation and the create-only refusal all belong
|
||||
// to the contract, which reads its create context inside the same
|
||||
// transaction it writes in. What stays is this command's own protocol: the
|
||||
// lint pass, the id-format check, --deps parsing and the dry-run preview.
|
||||
//
|
||||
// SPEC-GAP bd-yby99.32: Lifecycle.Create promises nothing about the
|
||||
// version-control entry a create records and CreateRequest carries no
|
||||
// Provenance to spell one, so this route's commit message moves from
|
||||
|
|
@ -134,8 +124,7 @@ func runCreateProxiedSingle(_ *cobra.Command, ctx context.Context, in createInpu
|
|||
if err != nil {
|
||||
// RULING R1, reported the same way the direct route reports it: an
|
||||
// occupied --id is a refusal, not a silent full-row upsert dressed up
|
||||
// as success. The proxied route used to upsert, because it asked the
|
||||
// use case for a plain create without the create-only guard.
|
||||
// as success.
|
||||
if errors.Is(err, storage.ErrAlreadyExists) && in.explicitID != "" {
|
||||
return HandleErrorRespectJSON("%s already exists; use bd update, or bd import for upsert semantics", in.explicitID)
|
||||
}
|
||||
|
|
@ -165,9 +154,7 @@ func runCreateProxiedSingle(_ *cobra.Command, ctx context.Context, in createInpu
|
|||
|
||||
// inheritProxiedSourceRepo copies a discovered-from parent's source repo onto
|
||||
// the new issue, which is what the direct route does before it calls the role
|
||||
// (cmd/bd/create.go). CreateRequest has no field for the derivation — the
|
||||
// contract takes the issue's own SourceRepo — so deriving one from an edge
|
||||
// stays this command's policy on both routes.
|
||||
// (cmd/bd/create.go).
|
||||
//
|
||||
// A failed lookup is not a verdict. The direct route ignores one and creates
|
||||
// with the default source repo; a genuinely absent target is refused by the
|
||||
|
|
@ -268,9 +255,7 @@ func runCreateProxiedMarkdown(_ *cobra.Command, ctx context.Context, in createIn
|
|||
}
|
||||
|
||||
// proxiedBatchCreator reaches the batch-create role through the provider's own
|
||||
// capability accessor, the way proxiedIssueLifecycle reaches the lifecycle: the
|
||||
// accessor is where each decorator adds its layer, so a constructor call here
|
||||
// would get the role stripped of them.
|
||||
// capability accessor, which is where each decorator adds its layer.
|
||||
func proxiedBatchCreator() (issueops.BatchCreator, error) {
|
||||
if uowProvider == nil {
|
||||
return nil, errors.New("proxied-server UOW provider not initialized")
|
||||
|
|
|
|||
|
|
@ -101,10 +101,10 @@ Force: Delete and orphan dependents
|
|||
|
||||
issueID := issueIDs[0]
|
||||
ctx := rootCtx
|
||||
// Get the issue to be deleted, using prefix-based routing. Resolution is
|
||||
// the FRONT DOOR'S job and stays here: issueops.DeleteRequest.IDs are
|
||||
// exact, because resolving an ambiguous prefix to a row and then deleting
|
||||
// it is the one place a convenience is not one.
|
||||
// Get the issue to be deleted, using prefix-based routing. Resolution
|
||||
// stays in the front door: issueops.DeleteRequest.IDs are exact, because
|
||||
// resolving an ambiguous prefix and then deleting the row it hit is the
|
||||
// one place a convenience is not.
|
||||
routedResult, err := resolveAndGetIssueForMutation(ctx, store, issueID)
|
||||
if err != nil {
|
||||
if isNotFoundErr(err) {
|
||||
|
|
@ -122,13 +122,9 @@ Force: Delete and orphan dependents
|
|||
return HandleError("%v", err)
|
||||
}
|
||||
// --force is this command's CONFIRMATION as well as its orphan mode, so an
|
||||
// unconfirmed run asks the role the same question a --dry-run does.
|
||||
// Everything else is the request the user typed: the guard, the deletion
|
||||
// and the reference rewrite are all the role's, and none of them is
|
||||
// written here any more. This path used to hold its own transaction that
|
||||
// removed each edge by hand and rewrote the neighbors' text; the whole of
|
||||
// it is issueops.Deleter now, which is also what puts the rewrite INSIDE
|
||||
// the transaction that deletes.
|
||||
// unconfirmed run asks the role the same question a --dry-run does. The
|
||||
// rewrite runs INSIDE the transaction that deletes, because it is the
|
||||
// role's.
|
||||
request := issueops.DeleteRequest{
|
||||
Actor: actor,
|
||||
IDs: []string{issueID},
|
||||
|
|
@ -159,8 +155,7 @@ Force: Delete and orphan dependents
|
|||
|
||||
if jsonOutput {
|
||||
// The single-issue keys, unchanged: `deleted` is the id rather than a
|
||||
// list here, and this is the shape every `bd delete <one-id> --json`
|
||||
// consumer already parses.
|
||||
// list here, which is what every `bd delete <one-id> --json` parses.
|
||||
if err := outputJSON(map[string]interface{}{
|
||||
"deleted": issueID,
|
||||
"dependencies_removed": result.Dependencies,
|
||||
|
|
@ -177,13 +172,10 @@ Force: Delete and orphan dependents
|
|||
},
|
||||
}
|
||||
|
||||
// renderSingleDeletePreview prints the human preview for a one-issue delete.
|
||||
//
|
||||
// It is PRESENTATION ONLY. The counts come from the role's dry run; the edge
|
||||
// listing and the "which neighbors cite this id" lines are reads this handler
|
||||
// makes to say WHICH links and WHICH issues, which no result carries and which
|
||||
// the role deliberately does not return - a delete answers with an effect, not
|
||||
// with rows.
|
||||
// renderSingleDeletePreview prints the human preview for a one-issue delete. The
|
||||
// counts come from the role's dry run; the edge listing and the "which neighbors
|
||||
// cite this id" lines are reads this handler makes, because a delete answers
|
||||
// with an effect rather than with rows.
|
||||
func renderSingleDeletePreview(
|
||||
ctx context.Context, activeStore storage.DoltStorage,
|
||||
issueID string, issue *types.Issue, dryRun bool, result issueops.DeleteResult,
|
||||
|
|
@ -207,9 +199,8 @@ func renderSingleDeletePreview(
|
|||
if err != nil {
|
||||
return HandleError("getting dependency records: %v", err)
|
||||
}
|
||||
// The role's own citation rule, not a second copy of it: a preview that
|
||||
// named a different set of neighbors than the deletion rewrites would be
|
||||
// worse than no preview.
|
||||
// The role's own citation rule, not a second copy: a preview naming a
|
||||
// different set of neighbors than the deletion rewrites is worse than none.
|
||||
re := storeissueops.DeletedReferencePattern(issueID)
|
||||
|
||||
fmt.Printf("\n%s\n", ui.RenderFail("⚠️ DELETE PREVIEW"))
|
||||
|
|
@ -266,10 +257,7 @@ func deleteIssue(ctx context.Context, issueID string) error {
|
|||
//
|
||||
// It resolves the ids the way this front door always has - prefix matching and
|
||||
// cross-repository routing, which issueops.DeleteRequest deliberately does not
|
||||
// do - and then hands the RESOLVED ids to the role. Everything below that line
|
||||
// used to live here: the orphan guard, the cascade expansion, the deletion, and
|
||||
// a text-reference rewrite that ran OUTSIDE the delete transaction and threw
|
||||
// away every update error it got.
|
||||
// do - and hands the RESOLVED ids to the role.
|
||||
//
|
||||
//nolint:unparam // cmd parameter required for potential future use
|
||||
func deleteBatch(_ *cobra.Command, issueIDs []string, force bool, dryRun bool, cascade bool, jsonOutput bool, _ bool, _ ...string) error {
|
||||
|
|
@ -386,9 +374,9 @@ func deleteBatch(_ *cobra.Command, issueIDs []string, force bool, dryRun bool, c
|
|||
// outputDeletionPreview renders a deletion preview without exposing issue
|
||||
// payloads in machine-readable or quiet output.
|
||||
//
|
||||
// result is the ROLE's dry run, or nil when the role refused - a refusal has
|
||||
// no counts, and printing zeros beside the refusal would read as "nothing
|
||||
// would have been deleted" rather than "we did not get that far".
|
||||
// result is the ROLE's dry run, or nil when the role refused: printing zeros
|
||||
// beside a refusal would read as "nothing would have been deleted" rather than
|
||||
// "we did not get that far".
|
||||
func outputDeletionPreview(issueIDs []string, issues map[string]*types.Issue, cascade bool, dryRun bool, result *issueops.DeleteResult, depError error, jsonOutput bool) error {
|
||||
if jsonOutput {
|
||||
preview := map[string]interface{}{
|
||||
|
|
|
|||
|
|
@ -14,10 +14,9 @@ import (
|
|||
// TestProxiedServerDelete pins the CONVERGED semantics on a team server.
|
||||
//
|
||||
// This route used to hardcode cascade at both of its call sites and refuse the
|
||||
// --cascade flag outright, so `bd delete X --force` deleted X's whole subtree
|
||||
// and there was no way to ask for anything else. The three modes below are the
|
||||
// direct route's, unchanged, and this test is what says so from the far side
|
||||
// of a real Dolt sql-server.
|
||||
// --cascade flag outright, so `bd delete X --force` deleted X's whole subtree.
|
||||
// The three modes below are the direct route's, unchanged, checked from the far
|
||||
// side of a real Dolt sql-server.
|
||||
func TestProxiedServerDelete(t *testing.T) {
|
||||
requireSharedProxiedServer(t)
|
||||
t.Parallel()
|
||||
|
|
|
|||
|
|
@ -39,10 +39,9 @@ func gatherDeleteInput(cmd *cobra.Command, args []string) (*deleteInput, error)
|
|||
in.force, _ = cmd.Flags().GetBool("force")
|
||||
in.dryRun, _ = cmd.Flags().GetBool("dry-run")
|
||||
// --cascade IS SUPPORTED HERE NOW. This route used to refuse the flag
|
||||
// outright ("delete always cascades") and hardcode Cascade: true at both of
|
||||
// its call sites, so on a team server there was no way to delete an issue
|
||||
// without taking its dependents and asking for the safer behavior was an
|
||||
// error. Both routes now mean the same three things by the same two flags.
|
||||
// outright ("delete always cascades") and hardcode Cascade: true, so on a
|
||||
// team server there was no way to delete an issue without taking its
|
||||
// dependents. Both routes now mean the same three things by the same flags.
|
||||
in.cascade, _ = cmd.Flags().GetBool("cascade")
|
||||
in.jsonOutput = jsonOutput
|
||||
in.quiet = isQuiet()
|
||||
|
|
@ -50,8 +49,7 @@ func gatherDeleteInput(cmd *cobra.Command, args []string) (*deleteInput, error)
|
|||
}
|
||||
|
||||
// proxiedDeleter hands back the named-row erasure surface for the proxied
|
||||
// route, through the provider's OWN capability accessor rather than a
|
||||
// constructor — the accessor is where a decorator would add its layer.
|
||||
// route, through the provider's OWN capability accessor.
|
||||
func proxiedDeleter() (issueops.Deleter, error) {
|
||||
if uowProvider == nil {
|
||||
return nil, fmt.Errorf("proxied-server UOW provider not initialized")
|
||||
|
|
@ -63,15 +61,10 @@ func proxiedDeleter() (issueops.Deleter, error) {
|
|||
return source.Deleter()
|
||||
}
|
||||
|
||||
// runDeleteProxiedServer is `bd delete` against a team server.
|
||||
//
|
||||
// WHAT IT NO LONGER DOES is most of what it used to. It held its own copy of
|
||||
// the whole flow — a preview unit of work, a committing unit of work, its own
|
||||
// not-found check, and Cascade hardcoded true at both call sites — and the two
|
||||
// routes disagreed about what `--force` MEANS on a destructive command. The
|
||||
// selection, the guard and the deletion are issueops.Deleter now, the same
|
||||
// library surface the direct route calls; what is left here is this route's
|
||||
// output, which is not the direct route's and is pinned separately.
|
||||
// runDeleteProxiedServer is `bd delete` against a team server. The selection,
|
||||
// the guard and the deletion are issueops.Deleter, the same library surface the
|
||||
// direct route calls; what is left here is this route's own output, which is
|
||||
// not the direct route's and is pinned separately.
|
||||
func runDeleteProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error {
|
||||
in, err := gatherDeleteInput(cmd, args)
|
||||
if err != nil {
|
||||
|
|
@ -104,8 +97,7 @@ func runDeleteProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri
|
|||
if request.DryRun {
|
||||
// The role answered WHAT WOULD HAPPEN; this read answers WHICH ROWS,
|
||||
// which is presentation this route has always printed and which no
|
||||
// result carries. It runs only after the role accepted the request, so
|
||||
// a refusal costs it nothing.
|
||||
// result carries. It runs only after the role accepted the request.
|
||||
preview, err := runDeleteProxiedPreviewTx(ctx, in)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
|
|
|
|||
|
|
@ -698,15 +698,10 @@ type depListAnchor struct {
|
|||
// readDepListEdges asks each anchor's OWN store for its stored edges and
|
||||
// reassembles the answers into the order the arguments named.
|
||||
//
|
||||
// The grouping is what keeps the answer on ONE shape. Before the role, three
|
||||
// different conditions fell through to the hydrated neighbor listing, so
|
||||
// `bd dep list a b c --json` silently emitted an array of ISSUES where it
|
||||
// documents an array of dependency records: a batch whose anchors routed to
|
||||
// different stores, a batch whose single batched read simply failed, and — the
|
||||
// one that outlived the other two — a batch in which enough anchors failed to
|
||||
// RESOLVE that only one survivor was left. All three are gone: a failure is now
|
||||
// a failure, a split batch is N role calls merged back into one answer, and the
|
||||
// caller's argument count picks the shape (see batchMode at the call site).
|
||||
// The grouping is what keeps the answer on ONE shape: a failure is a failure, a
|
||||
// split batch is N role calls merged back into one answer, and the caller's
|
||||
// argument count picks the shape (see batchMode at the call site). `bd dep list
|
||||
// a b c --json` documents an array of dependency records, not of issues.
|
||||
func readDepListEdges(ctx context.Context, anchors []depListAnchor, typeFilter string) ([]issueops.AnchorEdges, error) {
|
||||
var depTypes []types.DependencyType
|
||||
if typeFilter != "" {
|
||||
|
|
@ -755,10 +750,9 @@ func readDepListEdges(ctx context.Context, anchors []depListAnchor, typeFilter s
|
|||
// printDepListEdges renders the role's per-anchor answer, and is shared by both
|
||||
// routes so the two cannot drift apart in what they print.
|
||||
//
|
||||
// A GHOST ANCHOR goes to stderr in both modes, in the same words the direct
|
||||
// route already uses for an argument that would not resolve. Keeping it off
|
||||
// stdout is what leaves `--json` a flat array of dependency records, which is
|
||||
// the shape the command documents.
|
||||
// A GHOST ANCHOR goes to stderr in both modes. Keeping it off stdout is what
|
||||
// leaves `--json` a flat array of dependency records, which is the shape the
|
||||
// command documents.
|
||||
func printDepListEdges(anchors []issueops.AnchorEdges) error {
|
||||
for _, anchor := range anchors {
|
||||
if anchor.Missing {
|
||||
|
|
@ -873,24 +867,19 @@ Examples:
|
|||
}
|
||||
}()
|
||||
|
||||
// The multi-id edge listing is a different question from the neighbor
|
||||
// query below — raw edge records keyed by source, printed per source,
|
||||
// with a per-anchor miss — and it is on the EdgeReader role. Relations
|
||||
// cannot answer it: it is anchored on ONE issue, it answers with the
|
||||
// issues on the far end of its edges rather than the edges themselves,
|
||||
// and it drops every edge whose target this database has no row for.
|
||||
// The multi-id edge listing is on the EdgeReader role, not Relations:
|
||||
// Relations is anchored on ONE issue, answers with the issues on the far
|
||||
// end of its edges rather than the edges themselves, and drops every
|
||||
// edge whose target this database has no row for.
|
||||
//
|
||||
// The accessor is taken PER STORE rather than once for the command,
|
||||
// like the neighbor query below: a routed anchor answers from its own
|
||||
// store, carrying its own decorator stack.
|
||||
// The accessor is taken PER STORE rather than once for the command: a
|
||||
// routed anchor answers from its own store, carrying its own decorator
|
||||
// stack.
|
||||
//
|
||||
// The shape is chosen on batchMode — the count the CALLER TYPED — and
|
||||
// not on len(resolved). Those differ exactly when an anchor did not
|
||||
// resolve, and deciding on the survivors meant `bd dep list <good>
|
||||
// <typo> --json` printed the neighbor shape (RelatedIssue objects) on
|
||||
// this route while the proxied route printed the documented flat array
|
||||
// of dependency records. The help text promises the records shape "with
|
||||
// --json ... across all requested issues", so a skipped anchor must not
|
||||
// resolve, and the help text promises the records shape "with --json
|
||||
// ... across all requested issues", so a skipped anchor must not
|
||||
// silently change what a script is parsing.
|
||||
if batchMode && direction == "down" {
|
||||
anchors, err := readDepListEdges(ctx, resolved, typeFilter)
|
||||
|
|
@ -1115,9 +1104,8 @@ honored on the --proxied-server route too, which it was not before.`,
|
|||
}
|
||||
}()
|
||||
|
||||
// Both routes, one body: the only differences between them are which
|
||||
// accessor answers and how the root id is resolved, and both are inside
|
||||
// resolveTreeTarget.
|
||||
// Both routes, one body: which accessor answers and how the root id is
|
||||
// resolved are both inside resolveTreeTarget.
|
||||
return runDepTree(cmd, rootCtx, args)
|
||||
},
|
||||
}
|
||||
|
|
@ -1420,12 +1408,9 @@ func init() {
|
|||
depAddCmd.Flags().String("file", "", "Read dependency edges from JSONL file, or '-' for stdin")
|
||||
depAddCmd.Flags().Bool("no-cycle-check", false, "Skip per-edge cycle checks for speed (bulk wiring); bulk --file adds still run one final whole-graph check before commit")
|
||||
|
||||
// DEPRECATED NO-OP, and it always was one: nothing has ever read this flag.
|
||||
// It was accepted and threaded down to the walk, which never looked at it,
|
||||
// so a diamond has always been rendered under one parent only. Implementing
|
||||
// it now would be a feature wearing a refactor's clothes — nobody has
|
||||
// specified what "all paths" means for a DAG with shared subtrees — so the
|
||||
// role's contract states the first-visit rule as a promise
|
||||
// DEPRECATED NO-OP, and it always was one: nothing has ever read this flag,
|
||||
// so a diamond has always been rendered under one parent only. The role's
|
||||
// contract states the first-visit rule as a promise
|
||||
// (issueops/treewalker.go, TreeResult.Nodes) and this flag stays accepted so
|
||||
// no script breaks. Same story as TreeNode.Truncated.
|
||||
depTreeCmd.Flags().Bool("show-all-paths", false, "Deprecated no-op: accepted and ignored. A node reached by two paths is shown once, under the first.")
|
||||
|
|
@ -1435,8 +1420,7 @@ func init() {
|
|||
depTreeCmd.Flags().String("status", "", "Filter to only show issues with this status (open, in_progress, blocked, deferred, closed)")
|
||||
depTreeCmd.Flags().String("format", "", "Output format: 'mermaid' for Mermaid.js flowchart")
|
||||
// Defensive row cap (be-x42v): applied to the node count after the walk, by
|
||||
// the role, on BOTH routes — which is why it is the routed variant of the
|
||||
// flag and why depTreeCmd no longer calls rejectMaxRowsUnderProxiedServer.
|
||||
// the role, on BOTH routes — hence the routed variant of the flag.
|
||||
addRoutedMaxRowsFlag(depTreeCmd)
|
||||
// Note: --type flag intentionally omitted from depTreeCmd — TreeNode lacks
|
||||
// dependency type info so filtering is not possible. Use 'bd dep list --type' instead.
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ import (
|
|||
// prints, on ONE role and ONE renderer.
|
||||
|
||||
// openCycleDetector hands back the cycle role for whichever route this
|
||||
// invocation is on, each through its OWN capability accessor.
|
||||
// invocation is on.
|
||||
func openCycleDetector() (issueops.CycleDetector, error) {
|
||||
if usesProxiedServer() {
|
||||
return proxiedCycleDetector()
|
||||
|
|
@ -24,9 +24,7 @@ func openCycleDetector() (issueops.CycleDetector, error) {
|
|||
}
|
||||
|
||||
// proxiedCycleDetector hands back the guarded cycle-report surface for the
|
||||
// proxied-server provider, through the provider's own capability accessor — the
|
||||
// same two-step proxiedCounter performs, and for the same reason: the accessor
|
||||
// is where each layer is added.
|
||||
// proxied-server provider, through the provider's own capability accessor.
|
||||
func proxiedCycleDetector() (issueops.CycleDetector, error) {
|
||||
if uowProvider == nil {
|
||||
return nil, errors.New("proxied-server UOW provider not initialized")
|
||||
|
|
@ -78,9 +76,6 @@ func runDepCycles() error {
|
|||
|
||||
// cycleMemberTitle renders a member's description, naming the absence rather
|
||||
// than printing a blank line after the id.
|
||||
//
|
||||
// The absence is worth a phrase because it is the whole point of carrying the
|
||||
// member: this used to be the case where the member vanished from the path.
|
||||
func cycleMemberTitle(member issueops.CycleMember) string {
|
||||
if member.Issue == nil {
|
||||
return ui.RenderMuted("(no record in this database)")
|
||||
|
|
@ -132,9 +127,8 @@ func printCycleDetectionError(err error) {
|
|||
// closed by repeating the first member.
|
||||
//
|
||||
// The path is spelled from the role's MEMBER IDS, which are complete whether or
|
||||
// not each member has a row behind it. That is the visible half of the honest
|
||||
// partial: a cycle whose middle node has no record used to print as a shorter
|
||||
// path, or — when no member had one — not at all.
|
||||
// not each member has a row behind it: a cycle whose middle node has no record
|
||||
// used to print as a shorter path, or not at all.
|
||||
func printCycleWarnings(cycles []issueops.Cycle) {
|
||||
if len(cycles) == 0 {
|
||||
return
|
||||
|
|
|
|||
|
|
@ -16,10 +16,10 @@ import (
|
|||
// The rendering half of `bd dep cycles` and of the post-add warning, driven
|
||||
// directly with a report rather than through a database.
|
||||
//
|
||||
// These need no store and no server: what they pin is the one thing the
|
||||
// conformance contract and the HTTP tests cannot see, which is what a human
|
||||
// reads. The partial phrasing in particular exists only here — a member with no
|
||||
// row behind it used to be dropped, so there was nothing to print.
|
||||
// These need no store and no server: they pin the one thing the conformance
|
||||
// contract and the HTTP tests cannot see, which is what a human reads. The
|
||||
// partial phrasing exists only here — a member with no row behind it used to be
|
||||
// dropped, so there was nothing to print.
|
||||
|
||||
func TestDepCyclesNamesTheMembersItCannotDescribe(t *testing.T) {
|
||||
out := captureCycleStdout(t, func() {
|
||||
|
|
@ -63,8 +63,7 @@ func TestDepCyclesSaysNothingIsWrongForACleanWorkspace(t *testing.T) {
|
|||
|
||||
// TestCycleWarningSpellsTheWholePathIncludingUndescribableMembers pins the
|
||||
// post-add warning both dep-add routes and `bd link` print. It is spelled from
|
||||
// the member IDS, so a node with no row behind it still appears — the visible
|
||||
// half of the honest partial.
|
||||
// the member IDS, so a node with no row behind it still appears.
|
||||
func TestCycleWarningSpellsTheWholePathIncludingUndescribableMembers(t *testing.T) {
|
||||
origStderr := os.Stderr
|
||||
r, w, err := os.Pipe()
|
||||
|
|
@ -88,8 +87,8 @@ func TestCycleWarningSpellsTheWholePathIncludingUndescribableMembers(t *testing.
|
|||
_ = r.Close()
|
||||
|
||||
out := buf.String()
|
||||
// The closing edge is drawn by repeating the first member, which is how the
|
||||
// path reads as a cycle rather than as a chain.
|
||||
// The closing edge is drawn by repeating the first member, so the path
|
||||
// reads as a cycle rather than as a chain.
|
||||
if !strings.Contains(out, "bd-a → bd-ghost → bd-c → bd-a") {
|
||||
t.Errorf("cycle path is not the whole rotated path closed on itself:\n%s", out)
|
||||
}
|
||||
|
|
@ -144,11 +143,9 @@ func printCycleReportForTest(t *testing.T, report issueops.CycleReport) {
|
|||
// fixedCycleStore is a store whose only real method is the cycle accessor. It
|
||||
// embeds the interface, so any other method the command reached for would panic
|
||||
// rather than quietly answering zero — which is the assertion that `bd dep
|
||||
// cycles` opens nothing but the role.
|
||||
// The detector is a separate type rather than the store answering for itself,
|
||||
// because the store's LEGACY surface already carries a DetectCycles with a
|
||||
// different signature — which is the clearest statement available that the role
|
||||
// and the old seam are two different questions.
|
||||
// cycles` opens nothing but the role. The detector is a separate type because
|
||||
// the store's LEGACY surface already carries a DetectCycles with a different
|
||||
// signature.
|
||||
type fixedCycleStore struct {
|
||||
storage.DoltStorage
|
||||
report issueops.CycleReport
|
||||
|
|
|
|||
|
|
@ -17,9 +17,7 @@ import (
|
|||
|
||||
// These cover `bd dep list a b c`'s two halves above the role: which store each
|
||||
// resolved anchor is asked, and what the shared printer emits. Everything below
|
||||
// them — what Missing means, the edge order, the type filter — is the role's,
|
||||
// and is pinned by backend/conformance/edge_reader_contract.go at all three
|
||||
// backends.
|
||||
// them is the role's, pinned by backend/conformance/edge_reader_contract.go.
|
||||
|
||||
// edgeReaderStore is a DoltStorage whose only real method is the accessor under
|
||||
// test. Every other call is a nil panic, which is the assertion: this path must
|
||||
|
|
@ -68,14 +66,10 @@ func edgeReaderAnchorFor(id string, reader issueops.EdgeReader) depListAnchor {
|
|||
return depListAnchor{fullID: id, store: &edgeReaderStore{reader: reader}}
|
||||
}
|
||||
|
||||
// TestDepListEdgesReportsTheReadFailure is the regression for the shipped
|
||||
// defect this role's adoption fixes.
|
||||
//
|
||||
// The pre-role code called GetDependencyRecordsForIssues and, on ANY error,
|
||||
// fell through to the hydrated neighbor listing — so a transient failure
|
||||
// turned `bd dep list a b --json` from an array of dependency records into an
|
||||
// array of ISSUES, with no error and no warning. A caller parsing the first
|
||||
// shape read an empty result from the second.
|
||||
// TestDepListEdgesReportsTheReadFailure is the regression for a shipped defect:
|
||||
// the pre-role code fell through to the hydrated neighbor listing on ANY error,
|
||||
// so a transient failure turned `bd dep list a b --json` from an array of
|
||||
// dependency records into an array of ISSUES, with no error and no warning.
|
||||
func TestDepListEdgesReportsTheReadFailure(t *testing.T) {
|
||||
want := errors.New("dependency table is unreachable")
|
||||
reader := &fakeEdgeReader{err: want}
|
||||
|
|
@ -89,13 +83,12 @@ func TestDepListEdgesReportsTheReadFailure(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestDepListEdgesAsksEachAnchorsOwnStore pins the routed case, which is the
|
||||
// second half of the same defect: a batch whose anchors resolved to different
|
||||
// stores also fell through to the neighbor listing, so a cross-rig
|
||||
// `bd dep list` emitted a different document from a same-rig one.
|
||||
//
|
||||
// It also pins that no store is asked for another store's ids — an id sent to
|
||||
// the wrong database would come back Missing, which reads as "no such issue".
|
||||
// TestDepListEdgesAsksEachAnchorsOwnStore pins the routed half of the same
|
||||
// defect: a batch whose anchors resolved to different stores also fell through
|
||||
// to the neighbor listing, so a cross-rig `bd dep list` emitted a different
|
||||
// document from a same-rig one. It also pins that no store is asked for another
|
||||
// store's ids — an id sent to the wrong database comes back Missing, which
|
||||
// reads as "no such issue".
|
||||
func TestDepListEdgesAsksEachAnchorsOwnStore(t *testing.T) {
|
||||
home := &fakeEdgeReader{edges: map[string][]*types.Dependency{
|
||||
"hq-1": {{IssueID: "hq-1", DependsOnID: "hq-2", Type: types.DepBlocks}},
|
||||
|
|
@ -186,12 +179,10 @@ func (r *recordingTypeEdgeReader) ReadEdges(_ context.Context, req issueops.Edge
|
|||
}
|
||||
|
||||
// TestDepListPrintsGhostAnchorsToStderr pins the Q11-approved user-visible
|
||||
// change, and the reason it is on stderr.
|
||||
//
|
||||
// A ghost used to print "<id> has no dependencies" on the proxied route, which
|
||||
// reads as a clean graph. It now prints the warning the direct route has always
|
||||
// printed for an argument it could not resolve. Keeping it off stdout is what
|
||||
// leaves --json a flat array of dependency records.
|
||||
// change. A ghost used to print "<id> has no dependencies" on the proxied
|
||||
// route, which reads as a clean graph; it now prints the warning the direct
|
||||
// route has always printed for an argument it could not resolve. Keeping it off
|
||||
// stdout is what leaves --json a flat array of dependency records.
|
||||
func TestDepListPrintsGhostAnchorsToStderr(t *testing.T) {
|
||||
anchors := []issueops.AnchorEdges{
|
||||
{ID: "bd-1", Edges: []*types.Dependency{{IssueID: "bd-1", DependsOnID: "bd-2", Type: types.DepBlocks}}},
|
||||
|
|
|
|||
|
|
@ -51,8 +51,7 @@ func proxiedIssueRelations() (issueops.Relations, error) {
|
|||
}
|
||||
|
||||
// proxiedEdgeReader hands back the guarded stored-edge surface for the
|
||||
// proxied-server provider, through the provider's OWN capability accessor —
|
||||
// the same two-step a direct command performs on a store.
|
||||
// proxied-server provider, through the provider's own capability accessor.
|
||||
func proxiedEdgeReader() (issueops.EdgeReader, error) {
|
||||
if uowProvider == nil {
|
||||
return nil, errors.New("proxied-server UOW provider not initialized")
|
||||
|
|
@ -90,13 +89,11 @@ func addDependencyEdgesProxied(ctx context.Context, edges []issueops.DependencyE
|
|||
// Neither belongs in the write. The role's request IS the transaction, and a
|
||||
// cycle warning computed inside a transaction that has not committed describes
|
||||
// a graph nobody else can see; a title is presentation. Failing here cannot
|
||||
// fail the command either — the edges are already durable — so both halves
|
||||
// report the way a failed sweep already did.
|
||||
// fail the command either — the edges are already durable.
|
||||
//
|
||||
// THE SWEEP IS RESOLVED FIRST AND ASKED FOR SECOND. The role is only requested
|
||||
// when checkCycles is set, so an invocation that wants titles alone never
|
||||
// touches the cycle accessor: a provider that does not offer it must fail on
|
||||
// the sweep it was asked for, not on the two lookups beside it.
|
||||
// THE SWEEP IS RESOLVED FIRST AND ASKED FOR SECOND, and only when checkCycles
|
||||
// is set: a provider that does not offer the cycle accessor must fail on the
|
||||
// sweep it was asked for, not on the two lookups beside it.
|
||||
func depEdgeFeedback(ctx context.Context, fromID, toID string, checkCycles bool) depAddResult {
|
||||
var res depAddResult
|
||||
if fromID == "" && toID == "" && !checkCycles {
|
||||
|
|
@ -371,8 +368,8 @@ func runDepListProxiedServer(cmd *cobra.Command, ctx context.Context, args []str
|
|||
}
|
||||
|
||||
// The multi-id edge listing is a different question with a different
|
||||
// answer shape — raw edge records keyed by source, printed per source,
|
||||
// with a per-anchor miss — and it is on the EdgeReader role.
|
||||
// answer shape — raw edge records keyed by source — and it is on the
|
||||
// EdgeReader role.
|
||||
if len(args) > 1 && direction == "down" {
|
||||
return runDepListRecordsProxiedServer(ctx, args, typeFilter)
|
||||
}
|
||||
|
|
@ -445,21 +442,15 @@ func runDepListProxiedServer(cmd *cobra.Command, ctx context.Context, args []str
|
|||
}
|
||||
|
||||
// runDepListRecordsProxiedServer answers `bd dep list a b c` with raw edge
|
||||
// records grouped by source, on the EdgeReader role. It is off the Relations
|
||||
// role deliberately: that one answers with the ISSUES on the far end of ONE
|
||||
// anchor's edges, and this prints the edges themselves, per source, for several
|
||||
// sources at once.
|
||||
// records grouped by source, on the EdgeReader role.
|
||||
//
|
||||
// THIS ROUTE NOW REPORTS GHOST ANCHORS. It used to hand the raw arguments to
|
||||
// the dependency use case, which keys its answer by source and simply has no
|
||||
// entry for an id that names nothing — so a typo printed "<id> has no
|
||||
// dependencies" and a script read a clean graph. The role probes each anchor,
|
||||
// so the same typo now prints the warning the direct route has always printed
|
||||
// for an argument it could not resolve.
|
||||
// THIS ROUTE NOW REPORTS GHOST ANCHORS. It used to have no entry for an id
|
||||
// that names nothing, so a typo printed "<id> has no dependencies" and a script
|
||||
// read a clean graph. The role probes each anchor, so the same typo now prints
|
||||
// the warning the direct route has always printed.
|
||||
//
|
||||
// It still resolves NOTHING: an id is passed exactly as the caller spelled it,
|
||||
// because this route has never done partial-id resolution and the role's ids
|
||||
// are exact.
|
||||
// because this route has never done partial-id resolution.
|
||||
func runDepListRecordsProxiedServer(ctx context.Context, args []string, typeFilter string) error {
|
||||
reader, err := proxiedEdgeReader()
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -15,19 +15,13 @@ import (
|
|||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// `bd dep tree` on ONE role and ONE body.
|
||||
//
|
||||
// What is left here is the front door's own work: flag vocabulary, id
|
||||
// resolution, and rendering. The walk, the depth bound, the cycle policy, the
|
||||
// prune and the defensive cap are issueops.TreeWalker's.
|
||||
// `bd dep tree` on ONE role and ONE body. What is left here is the front door's
|
||||
// own work: flag vocabulary, id resolution, and rendering.
|
||||
|
||||
// treeTarget is a resolved root and the walker that can answer about it.
|
||||
//
|
||||
// The two travel together because on the DIRECT route they are one decision:
|
||||
// resolveIDWithRouting may resolve the id against a prefix-ROUTED database, and
|
||||
// the walk then has to be asked of that store rather than of the local one. A
|
||||
// helper that returned only the id would have left the caller holding a resolved
|
||||
// id and the wrong store.
|
||||
// treeTarget is a resolved root and the walker that can answer about it. The two
|
||||
// travel together because on the DIRECT route resolveIDWithRouting may resolve
|
||||
// the id against a prefix-ROUTED database, and the walk then has to be asked of
|
||||
// that store rather than of the local one.
|
||||
type treeTarget struct {
|
||||
rootID string
|
||||
walker issueops.TreeWalker
|
||||
|
|
@ -35,13 +29,11 @@ type treeTarget struct {
|
|||
}
|
||||
|
||||
// resolveTreeTarget resolves the argument to an exact id and hands back the tree
|
||||
// role for whichever route this invocation is on, each through its OWN
|
||||
// capability accessor.
|
||||
// role for whichever route this invocation is on.
|
||||
//
|
||||
// RESOLUTION HAPPENS FIRST, AND THE ROLE IS ASKED FOR ONLY AFTER IT SUCCEEDS.
|
||||
// That order is deliberate: a lookup that finds nothing must report the lookup
|
||||
// failure, not a provider that cannot offer a surface the command never got to
|
||||
// use.
|
||||
// RESOLUTION HAPPENS FIRST, AND THE ROLE IS ASKED FOR ONLY AFTER IT SUCCEEDS: a
|
||||
// lookup that finds nothing must report the lookup failure, not a missing
|
||||
// surface the command never got to use.
|
||||
func resolveTreeTarget(ctx context.Context, arg string) (treeTarget, error) {
|
||||
if usesProxiedServer() {
|
||||
return proxiedTreeTarget(ctx, arg)
|
||||
|
|
@ -61,11 +53,9 @@ func resolveTreeTarget(ctx context.Context, arg string) (treeTarget, error) {
|
|||
// proxiedTreeTarget resolves the argument against the proxied server and hands
|
||||
// back the provider's tree surface.
|
||||
//
|
||||
// THIS ROUTE GAINS PARTIAL-ID RESOLUTION HERE, which it has never had: it passed
|
||||
// the argument to the use case verbatim, so `bd dep tree a1b2` worked on a
|
||||
// direct workspace and failed on a team server. The resolution runs in its own
|
||||
// short-lived read unit of work — the walk opens its own inside the role — and
|
||||
// the id it produces is exact, which is what the role's contract requires.
|
||||
// THIS ROUTE GAINS PARTIAL-ID RESOLUTION, which it has never had: it passed the
|
||||
// argument to the use case verbatim, so `bd dep tree a1b2` worked on a direct
|
||||
// workspace and failed on a team server.
|
||||
func proxiedTreeTarget(ctx context.Context, arg string) (treeTarget, error) {
|
||||
uw, err := proxiedOpenReadUOW(ctx)
|
||||
if err != nil {
|
||||
|
|
@ -110,12 +100,10 @@ func runDepTree(cmd *cobra.Command, ctx context.Context, args []string) error {
|
|||
directionFlag = string(issueops.TreeDown)
|
||||
}
|
||||
|
||||
// The flag vocabulary is checked HERE rather than left to the role, for the
|
||||
// reason internal/httpapi/edges.go checks its own bounds: these refusals name
|
||||
// a FLAG and are worded for the person who typed one, while the role's name a
|
||||
// request field and are worded for a library caller. The role refuses the
|
||||
// same two things independently, so a caller that is not this command still
|
||||
// cannot walk with a bad direction or a zero depth.
|
||||
// The flag vocabulary is checked HERE rather than left to the role: these
|
||||
// refusals name a FLAG and are worded for the person who typed one, while
|
||||
// the role's name a request field. The role refuses the same two things
|
||||
// independently.
|
||||
direction := issueops.TreeDirection(directionFlag)
|
||||
switch direction {
|
||||
case issueops.TreeDown, issueops.TreeUp, issueops.TreeBoth:
|
||||
|
|
@ -126,11 +114,9 @@ func runDepTree(cmd *cobra.Command, ctx context.Context, args []string) error {
|
|||
return HandleErrorRespectJSON("--max-depth must be >= 1")
|
||||
}
|
||||
|
||||
// The cap is resolved here and CARRIED ON THE REQUEST, which is the change
|
||||
// for the proxied route: it used to refuse --max-rows outright, because the
|
||||
// unit-of-work path threaded no cap. It threads one now — the shared walk
|
||||
// body enforces it for all three backends — so the flag means the same thing
|
||||
// wherever the command runs.
|
||||
// The cap is resolved here and CARRIED ON THE REQUEST: the proxied route
|
||||
// used to refuse --max-rows outright because it threaded no cap. It threads
|
||||
// one now, so the flag means the same thing wherever the command runs.
|
||||
maxRows, maxRowsSource, err := resolveMaxRows(cmd)
|
||||
if err != nil {
|
||||
return err
|
||||
|
|
@ -161,8 +147,7 @@ func runDepTree(cmd *cobra.Command, ctx context.Context, args []string) error {
|
|||
// Handle format presets (json handled earlier, near the flag read).
|
||||
if formatStr == "mermaid" {
|
||||
// The raw argument, not the resolved id: this is only read when the tree
|
||||
// is empty, and changing which spelling that one line prints is not
|
||||
// something this commit was asked for.
|
||||
// is empty.
|
||||
outputMermaidTree(tree, args[0])
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -91,11 +91,9 @@ func applyInitGatewayCredential(ctx context.Context, beadsDir string, doltCfg *d
|
|||
// not consult the server, so it is surfaced as the transient failure it is
|
||||
// rather than misdiagnosed as an unprovisioned database.
|
||||
//
|
||||
// It used to also return WHETHER to write. That half is gone: whether the prefix
|
||||
// may be written is the same question as whether the substrate is unidentified,
|
||||
// and issueops.Bootstrapper answers it inside the transaction it writes in
|
||||
// rather than here, several hundred lines earlier. A "" value means what it
|
||||
// always meant — nothing for init to set.
|
||||
// Whether the prefix may be WRITTEN is not decided here: that is the same
|
||||
// question as whether the substrate is unidentified, and issueops.Bootstrapper
|
||||
// answers it inside the transaction it writes in.
|
||||
func resolveInitIssuePrefix(gateway bool, existing, dbName, prefix string, readErr error) (value string, err error) {
|
||||
if existing != "" {
|
||||
return "", nil
|
||||
|
|
@ -230,11 +228,10 @@ func shouldInitSharedGlobalDB(sharedServer, sharedServerMode, gateway bool) bool
|
|||
// issueops.Bootstrapper, or adopts the one already on the substrate.
|
||||
//
|
||||
// VERIFY, THEN BOOTSTRAP OR ADOPT. The role REFUSES an already-identified
|
||||
// substrate, which is Q8's ruling and the guard that now sits below both front
|
||||
// doors rather than only in front of one; asking first is how a front door tells
|
||||
// a workspace it may identify from one it must leave alone. That refusal is what
|
||||
// makes `bd init` safe to run against a database another rig is already minting
|
||||
// ids in: before this, the proxied route rewrote both markers every time.
|
||||
// substrate, so asking first is how a front door tells a workspace it may
|
||||
// identify from one it must leave alone. That refusal is what makes `bd init`
|
||||
// safe to run against a database another rig is already minting ids in: before
|
||||
// this, the proxied route rewrote both markers every time.
|
||||
//
|
||||
// found is the identity the caller already read with InitVerifier, in the same
|
||||
// snapshot it read the prefix in. projectID is "" only when init composed no
|
||||
|
|
@ -251,14 +248,13 @@ func seedInitWorkspaceIdentity(
|
|||
}
|
||||
if found.Prefix != "" || found.ProjectID != "" {
|
||||
// Adopt. The caller has already reconciled metadata.json against
|
||||
// found.ProjectID; re-stamping the substrate with the value it gave us
|
||||
// would be a write with nothing to say.
|
||||
// found.ProjectID; re-stamping the substrate would say nothing new.
|
||||
return nil
|
||||
}
|
||||
if projectID == "" {
|
||||
// No metadata.json was composed on this path. Take the id the workspace
|
||||
// already records so the substrate and the file agree, and mint one only
|
||||
// when neither exists — a prefix without an identity is exactly the
|
||||
// when neither exists: a prefix without an identity is the
|
||||
// half-bootstrapped state the role refuses to complete later.
|
||||
if existing, err := configfile.Load(beadsDir); err == nil && existing != nil {
|
||||
projectID = existing.ProjectID
|
||||
|
|
@ -1417,15 +1413,11 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
|
|||
// These settings define fundamental behavior (issue IDs, sync workflow).
|
||||
// Failure here indicates a serious problem that prevents normal operation.
|
||||
|
||||
// Read the workspace's identity ONCE, through issueops.InitVerifier.
|
||||
//
|
||||
// It used to be two reads at two places — the prefix here and
|
||||
// _project_id four hundred lines down — each with its own error
|
||||
// handling. The role reads the pair in one snapshot, so the prefix this
|
||||
// init adopts and the project id it reconciles against cannot come from
|
||||
// either side of another rig's write, and an UNREADABLE identity is an
|
||||
// error rather than an empty one the gateway paths would misdiagnose as
|
||||
// an unprovisioned database.
|
||||
// Read the workspace's identity ONCE, through issueops.InitVerifier. The
|
||||
// prefix this init adopts and the project id it reconciles against come
|
||||
// from ONE SNAPSHOT, so they cannot land either side of another rig's
|
||||
// write, and an UNREADABLE identity is an error rather than an empty one
|
||||
// the gateway paths would misdiagnose as an unprovisioned database.
|
||||
initVerifier, err := store.InitVerifier()
|
||||
if err != nil {
|
||||
_ = store.Close()
|
||||
|
|
@ -1489,8 +1481,8 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
|
|||
// bootstrapProjectID is the identity seedInitWorkspaceIdentity will
|
||||
// record, resolved inside the metadata.json block below because that is
|
||||
// where local and database identities are reconciled. It stays "" when
|
||||
// that block does not run, and the seeding step reads the workspace's
|
||||
// own metadata.json for it instead.
|
||||
// that block does not run, and the seeding step falls back to the
|
||||
// workspace's own metadata.json.
|
||||
bootstrapProjectID := ""
|
||||
|
||||
// Create or preserve metadata.json for database metadata (bd-zai fix)
|
||||
|
|
@ -1536,12 +1528,8 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
|
|||
// Gateway skip, init would save the stale id as success and every later
|
||||
// normal open would hard-fail with PROJECT IDENTITY MISMATCH.
|
||||
//
|
||||
// The id itself comes from the single InitVerifier read taken
|
||||
// beside the prefix, rather than from a second GetMetadata here.
|
||||
// shouldConsultInitProjectID still decides whether to USE it, so
|
||||
// which identities init adopts is unchanged; what changed is that
|
||||
// the two halves of one identity can no longer be read either side
|
||||
// of another rig's write.
|
||||
// The id comes from the single InitVerifier read taken beside the
|
||||
// prefix; shouldConsultInitProjectID still decides whether to USE it.
|
||||
adoptedFromDB := ""
|
||||
if store != nil && shouldConsultInitProjectID(doltCfg.Gateway, cfg.ProjectID, database, bootstrappedFromRemote) {
|
||||
adoptedFromDB = dbIdentity.ProjectID
|
||||
|
|
@ -1637,9 +1625,8 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
|
|||
// Non-fatal - continue anyway
|
||||
}
|
||||
|
||||
// The identity write itself happens once, below this block, through
|
||||
// issueops.Bootstrapper — see seedInitWorkspaceIdentity. This is
|
||||
// where the id it uses is decided.
|
||||
// The write itself happens once, below this block, through
|
||||
// seedInitWorkspaceIdentity; this is where its id is decided.
|
||||
bootstrapProjectID = cfg.ProjectID
|
||||
|
||||
// Create config.yaml template (prefix is stored in DB, not config.yaml)
|
||||
|
|
@ -1714,8 +1701,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1):
|
|||
//
|
||||
// It is NOT part of the bootstrap, and neither are the fingerprints
|
||||
// above: those four values are refreshed on EVERY init, adopt or not,
|
||||
// while the identity is written once and adopted forever. See
|
||||
// issueops.Bootstrapper.
|
||||
// while the identity is written once and adopted forever.
|
||||
if shouldWriteInitStateToDB(doltCfg.Gateway) {
|
||||
if err := store.SetMetadata(ctx, "last_import_time", time.Now().Format(time.RFC3339)); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: failed to initialize last_import_time: %v\n", err)
|
||||
|
|
|
|||
|
|
@ -178,11 +178,8 @@ func runInitProxiedServer(cmd *cobra.Command, ctx context.Context, in initProxie
|
|||
fmt.Fprintf(os.Stderr, "Warning: could not compute clone ID: %v\n", err)
|
||||
}
|
||||
|
||||
// The identity goes through the two roles, so this route and the direct one
|
||||
// share one definition of what a workspace's identity is and one rule about
|
||||
// when it may be written. The order is VERIFY, then bootstrap or adopt:
|
||||
// Bootstrapper REFUSES an already-identified substrate, which is the guard
|
||||
// below both front doors, and asking first is how a front door tells a
|
||||
// The order is VERIFY, then bootstrap or adopt: Bootstrapper REFUSES an
|
||||
// already-identified substrate, and asking first is how a front door tells a
|
||||
// re-init from the collision that guard exists for.
|
||||
verifier, err := proxiedInitVerifier(initUOWProvider)
|
||||
if err != nil {
|
||||
|
|
@ -207,10 +204,9 @@ func runInitProxiedServer(cmd *cobra.Command, ctx context.Context, in initProxie
|
|||
switch {
|
||||
case existing.Prefix != "" || existing.ProjectID != "":
|
||||
// Another rig — or an earlier init — already identified this
|
||||
// database. ADOPT it. Before this went through the roles, this
|
||||
// route rewrote the prefix and the project id every time, which is
|
||||
// what renamed the ids a co-tenant was about to mint; the direct
|
||||
// route has adopted here since it was written.
|
||||
// database. ADOPT it: this route used to rewrite the prefix and the
|
||||
// project id every time, which renamed the ids a co-tenant was
|
||||
// about to mint.
|
||||
adoptedPrefix, adoptedProjectID = existing.Prefix, existing.ProjectID
|
||||
if !in.quiet {
|
||||
fmt.Printf(" %s Adopted project identity from existing database\n", ui.RenderPass("✓"))
|
||||
|
|
@ -239,10 +235,9 @@ func runInitProxiedServer(cmd *cobra.Command, ctx context.Context, in initProxie
|
|||
}
|
||||
|
||||
// The Dolt remote is configured SEPARATELY from the identity, the way
|
||||
// the direct route has always configured it. They are different facts
|
||||
// with different lifetimes — where this database syncs to, versus what
|
||||
// it is — and folding them into one call is what let a remote that could
|
||||
// not be created fail a bootstrap that had already succeeded.
|
||||
// the direct route has always configured it: folding them into one call
|
||||
// is what let a remote that could not be created fail a bootstrap that
|
||||
// had already succeeded.
|
||||
if remoteURL != "" {
|
||||
if err := configureProxiedInitDoltRemote(ctx, initUOWProvider, remoteURL); err != nil {
|
||||
return HandleError("%v", err)
|
||||
|
|
@ -313,14 +308,11 @@ func resolveProxiedInitRemoteURL(ctx context.Context, gitUC domain.GitUseCase, i
|
|||
}
|
||||
|
||||
// proxiedInitVerifier and proxiedBootstrapper hand back the two identity
|
||||
// surfaces through the provider's OWN capability accessors — the same two-step
|
||||
// proxiedCounter performs, and for the same reason: the accessor is where each
|
||||
// layer is added.
|
||||
// surfaces through the provider's own capability accessors.
|
||||
//
|
||||
// They are asked for SEPARATELY rather than as one surface because the roles are
|
||||
// separate, and team-server mode is what that separation is for: it holds a
|
||||
// verifier and never obtains a bootstrapper, so the path bd must not write on
|
||||
// cannot reach the write.
|
||||
// They are asked for SEPARATELY, and team-server mode is what that separation
|
||||
// is for: it holds a verifier and never obtains a bootstrapper, so the path bd
|
||||
// must not write on cannot reach the write.
|
||||
func proxiedInitVerifier(provider uow.UnitOfWorkProvider) (issueops.InitVerifier, error) {
|
||||
src, ok := provider.(uow.InitVerifierSource)
|
||||
if !ok {
|
||||
|
|
@ -337,15 +329,14 @@ func proxiedBootstrapper(provider uow.UnitOfWorkProvider) (issueops.Bootstrapper
|
|||
return src.Bootstrapper()
|
||||
}
|
||||
|
||||
// recordProxiedInitTrackingState seeds the per-clone bookkeeping that used to
|
||||
// ride along inside BootstrapProject: the repository and clone fingerprints,
|
||||
// the synced-at marker and the recorded binary version.
|
||||
// recordProxiedInitTrackingState seeds the per-clone bookkeeping: the
|
||||
// repository and clone fingerprints, the synced-at marker and the recorded
|
||||
// binary version.
|
||||
//
|
||||
// It is separate from the identity because its LIFETIME is: the identity is
|
||||
// written once and then adopted forever, while these four describe the clone
|
||||
// running init and are refreshed every time it runs. Keeping them in the
|
||||
// refusable one-time write would have meant a re-init on a shared database
|
||||
// silently stopped recording them.
|
||||
// running init and are refreshed every time it runs. In the refusable one-time
|
||||
// write, a re-init on a shared database would silently stop recording them.
|
||||
func recordProxiedInitTrackingState(ctx context.Context, provider uow.UnitOfWorkProvider, repoID, cloneID string) error {
|
||||
return uow.RunTx(ctx, provider, func(ctx context.Context, uw uow.UnitOfWork) (string, error) {
|
||||
cfg := uw.ConfigUseCase()
|
||||
|
|
@ -373,8 +364,7 @@ func recordProxiedInitTrackingState(ctx context.Context, provider uow.UnitOfWork
|
|||
}
|
||||
|
||||
// configureProxiedInitDoltRemote adds the sync remote, skipping a name that is
|
||||
// already taken. It is the remote half of what BootstrapProject used to do in
|
||||
// one call with the identity; the direct route has always kept the two apart.
|
||||
// already taken.
|
||||
func configureProxiedInitDoltRemote(ctx context.Context, provider uow.UnitOfWorkProvider, remoteURL string) error {
|
||||
return uow.RunTx(ctx, provider, func(ctx context.Context, uw uow.UnitOfWork) (string, error) {
|
||||
remotes, err := uw.DoltRemoteUseCase().ListRemotes(ctx)
|
||||
|
|
@ -397,13 +387,10 @@ func configureProxiedInitDoltRemote(ctx context.Context, provider uow.UnitOfWork
|
|||
// database, following the gateway contract: adopt if present, hard error if
|
||||
// absent — bd never writes identity in team-server mode.
|
||||
//
|
||||
// It takes an issueops.InitVerifier rather than a config reader of its own
|
||||
// because the distinction it is built around — an ABSENT identity means
|
||||
// "unprovisioned, tell them to run bts init", an UNREADABLE one means "the
|
||||
// connection failed, say so" — is now the role's promise rather than this
|
||||
// function's care. The two markers also arrive as ONE snapshot, so the prefix it
|
||||
// adopts and the project id it adopts cannot come from either side of a
|
||||
// concurrent write.
|
||||
// ABSENT means "unprovisioned, tell them to run bts init" and UNREADABLE means
|
||||
// "the connection failed, say so"; keeping those apart is the InitVerifier
|
||||
// role's promise. The two markers arrive as ONE snapshot, so the prefix and the
|
||||
// project id cannot come from either side of a concurrent write.
|
||||
func adoptTeamServerIdentity(ctx context.Context, verifier issueops.InitVerifier, dbName, localPrefix string, prefixIsExplicit bool, localProjectID string) (prefix, projectID string, err error) {
|
||||
identity, readErr := verifier.VerifyIdentity(ctx, issueops.VerifyIdentityRequest{})
|
||||
if _, err := resolveInitIssuePrefix(true, identity.Prefix, dbName, localPrefix, readErr); err != nil {
|
||||
|
|
|
|||
|
|
@ -16,10 +16,7 @@ import (
|
|||
//
|
||||
// It answers with the PAIR and one error, because that is the shape of the role:
|
||||
// the two markers are read in one snapshot, so there is no longer a state where
|
||||
// the prefix read succeeded and the project-id read did not. The two subtests
|
||||
// that asserted those separately are one subtest now, and it is a stronger
|
||||
// statement than the two it replaces — a caller cannot see half an identity
|
||||
// from a connection that dropped.
|
||||
// the prefix read succeeded and the project-id read did not.
|
||||
type fakeIdentityReader struct {
|
||||
prefix string
|
||||
projectID string
|
||||
|
|
|
|||
|
|
@ -204,16 +204,12 @@ func runListCore(cmd *cobra.Command, _ []string) error {
|
|||
return HandleError("--offset is only supported under --proxied-server")
|
||||
}
|
||||
|
||||
// `bd list`'s PAGE is on issueops.Reader. What is still built here is the
|
||||
// filter --watch and the hierarchical --parent tree consume as a VALUE:
|
||||
// `bd list`'s PAGE is on issueops.Reader. The filter is still built here
|
||||
// because --watch and the hierarchical --parent tree consume it as a VALUE:
|
||||
// the poll loop re-runs it on a ticker and the tree walk re-parents a copy
|
||||
// of it at every level, neither of which a page can express.
|
||||
//
|
||||
// The filter is therefore built unconditionally and used by two modes. That
|
||||
// is one wasted build on the modes that reach the role instead, and it buys
|
||||
// the order below: the page query still runs before the tree branch, so
|
||||
// `--parent --pretty --max-rows N` still refuses on the cap exactly where it
|
||||
// refused before this commit.
|
||||
// of it at every level, neither of which a page can express. Building it
|
||||
// unconditionally also keeps the page query ahead of the tree branch, so
|
||||
// `--parent --pretty --max-rows N` still refuses on the cap where it did.
|
||||
cfg, err := workapi.LoadStoreListConfig(rootCtx, store)
|
||||
if err != nil {
|
||||
return HandleError("%v", err)
|
||||
|
|
@ -248,21 +244,17 @@ func runListCore(cmd *cobra.Command, _ []string) error {
|
|||
|
||||
// The accessor on the ROUTED store, not on the global one: a contributor
|
||||
// listing is answered from the repository the routing rule picked, and a
|
||||
// reader taken off `store` would read the wrong database. It is also where
|
||||
// each storage decorator adds its layer, which is why no command builds the
|
||||
// shared implementation itself.
|
||||
// reader taken off `store` would read the wrong database.
|
||||
reader, err := activeStore.IssueReader()
|
||||
if err != nil {
|
||||
return HandleError("%v", err)
|
||||
}
|
||||
|
||||
// FIRST FLIP: --json. The role's List runs the same LoadStoreListConfig,
|
||||
// the same BuildListFilter and the same workapi.FinishPage this branch ran
|
||||
// longhand, over the same request, and the --ready arm is its ReadyFlag —
|
||||
// so the page, its order, its trim and its has-more verdict are unchanged
|
||||
// bytes. The cap still arrives as *ErrTooManyRows, which is why
|
||||
// handleMaxRowsError still wraps the call: it rides the filter the builder
|
||||
// produces, so the role trip does not move it.
|
||||
// --json. The role's List runs the same LoadStoreListConfig, the same
|
||||
// BuildListFilter and the same workapi.FinishPage this branch ran longhand,
|
||||
// and the --ready arm is its ReadyFlag, so the page, its order, its trim and
|
||||
// its has-more verdict are unchanged bytes. The cap still arrives as
|
||||
// *ErrTooManyRows, which is why handleMaxRowsError still wraps the call.
|
||||
if jsonOutput {
|
||||
page, err := reader.List(ctx, in.ListRequest)
|
||||
if err != nil {
|
||||
|
|
@ -285,11 +277,9 @@ func runListCore(cmd *cobra.Command, _ []string) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
// SECOND FLIP: every text rendering. They print no cardinality, and the
|
||||
// query this branch used to run projected none, so the request carries
|
||||
// SkipCounts — stage 1 added that field for exactly this arrival
|
||||
// (issueops.ListRequest.SkipCounts). Without it the flip would trade a
|
||||
// plain scan for three aggregate joins on the most-run command in the tree.
|
||||
// The text renderings print no cardinality, so the request carries SkipCounts
|
||||
// (issueops.ListRequest.SkipCounts). Without it this would trade a plain scan
|
||||
// for three aggregate joins on the most-run command in the tree.
|
||||
textRequest := in.ListRequest
|
||||
textRequest.SkipCounts = true
|
||||
page, err := reader.List(ctx, textRequest)
|
||||
|
|
@ -352,14 +342,11 @@ func runListCore(cmd *cobra.Command, _ []string) error {
|
|||
}
|
||||
}
|
||||
|
||||
// THIRD FLIP: the decoration, onto issueops.BlockingAnnotator. The failure
|
||||
// is still swallowed, and deliberately: this route has always rendered the
|
||||
// page undecorated rather than failing on it. The proxied route fails
|
||||
// instead, which is a difference between the two CALLERS rather than one
|
||||
// between two answers — recorded for the owner in AMBIGUITIES.md (A-blk-1)
|
||||
// rather than converged here, because deciding what a listing does when its
|
||||
// decoration is unavailable is a behavior question this commit was not
|
||||
// given.
|
||||
// The decoration goes through issueops.BlockingAnnotator. Its failure is
|
||||
// still swallowed: this route has always rendered the page undecorated
|
||||
// rather than failing on it, while the proxied route fails — a difference
|
||||
// between the two CALLERS, recorded for the owner in AMBIGUITIES.md
|
||||
// (A-blk-1) rather than converged here.
|
||||
blocking := annotateListBlocking(ctx, activeStore, issueIDs)
|
||||
|
||||
var buf strings.Builder
|
||||
|
|
|
|||
|
|
@ -31,8 +31,7 @@ func runListProxiedServer(cmd *cobra.Command, ctx context.Context, in listInput)
|
|||
default:
|
||||
// The --ready arm is not a case of its own any more: it is
|
||||
// ListRequest.ReadyFlag, and choosing the ready query from it is the
|
||||
// ROLE's job on both routes. Two functions that differed only in which
|
||||
// use-case method they called is exactly the drift this replaces.
|
||||
// ROLE's job on both routes.
|
||||
return runListProxiedPage(ctx, in)
|
||||
}
|
||||
}
|
||||
|
|
@ -69,11 +68,9 @@ func runListProxiedTree(ctx context.Context, in listInput) error {
|
|||
// it is the same two in the same order: --json first, then every text
|
||||
// rendering, both over issueops.Reader.
|
||||
//
|
||||
// It opens no unit of work of its own. The role opens one per call, which is
|
||||
// It opens no unit of work of its own — the role opens one per call, which is
|
||||
// one more than this route used to for a listing that also loads dependency
|
||||
// records — the price of the page and the decoration each being one question
|
||||
// asked through one seam rather than several methods sharing a caller's
|
||||
// transaction. Nothing here was atomic across those reads before either: the
|
||||
// records. Nothing here was atomic across those reads before either: the
|
||||
// renderings ran after the query returned.
|
||||
func runListProxiedPage(ctx context.Context, in listInput) error {
|
||||
rd, err := proxiedIssueReader()
|
||||
|
|
@ -222,9 +219,8 @@ func loadDepsForIssues(ctx context.Context, uw uow.UnitOfWork, issues []*types.I
|
|||
func renderProxiedListText(ctx context.Context, issues []*types.Issue, in listInput, truncated bool) error {
|
||||
// --format and the pretty tree want the WHOLE dependency record set for the
|
||||
// page — every edge type, no status rule — which is neither role's
|
||||
// question: it is not a page and it is not the blocking decoration. They
|
||||
// open their own unit of work for it, which is what lets every other
|
||||
// rendering below reach its roles without one.
|
||||
// question. They open their own unit of work for it, which is what lets
|
||||
// every other rendering below reach its roles without one.
|
||||
if in.formatStr != "" || in.prettyFormat {
|
||||
uw, err := openProxiedListUOW(ctx)
|
||||
if err != nil {
|
||||
|
|
@ -258,10 +254,9 @@ func renderProxiedListText(ctx context.Context, issues []*types.Issue, in listIn
|
|||
}
|
||||
|
||||
// The decoration, onto issueops.BlockingAnnotator. This route FAILS on the
|
||||
// read where the direct one swallows it, and this commit keeps both exactly
|
||||
// as they were: the difference is what each CALLER does with a failure, not
|
||||
// what the two answers are, and converging it is a behavior decision
|
||||
// recorded for the owner (AMBIGUITIES.md, A-blk-1) rather than taken here.
|
||||
// read where the direct one swallows it, and both are kept exactly as they
|
||||
// were: converging them is a behavior decision recorded for the owner
|
||||
// (AMBIGUITIES.md, A-blk-1) rather than taken here.
|
||||
annotator, err := proxiedBlockingAnnotator()
|
||||
if err != nil {
|
||||
return err
|
||||
|
|
|
|||
|
|
@ -12,17 +12,12 @@ import (
|
|||
)
|
||||
|
||||
// The two seams `bd list` reaches its roles through, and the one projection its
|
||||
// text renderings need. Both routes call these, which is what keeps "the page
|
||||
// comes from Reader.List and the decoration from BlockingAnnotator" a single
|
||||
// statement rather than two that happen to agree.
|
||||
// text renderings need. Both routes call these, so the page and its decoration
|
||||
// come from one statement rather than two that happen to agree.
|
||||
|
||||
// listPageIssues projects a counted page onto the plain rows the text
|
||||
// renderings take.
|
||||
//
|
||||
// It is a projection and not a second query: IssueWithCounts embeds the issue,
|
||||
// so this shares everything under the header and keeps the page's ORDER, which
|
||||
// the role's epilogue already decided. A nil row is dropped rather than
|
||||
// dereferenced — the role promises none for a successful call, and a listing is
|
||||
// renderings take, keeping the page's ORDER. A nil row is dropped rather than
|
||||
// dereferenced: the role promises none for a successful call, and a listing is
|
||||
// not where a broken implementation should become a panic.
|
||||
func listPageIssues(page issueops.IssuePage) ([]*types.Issue, bool) {
|
||||
issues := make([]*types.Issue, 0, len(page.Items))
|
||||
|
|
@ -38,10 +33,9 @@ func listPageIssues(page issueops.IssuePage) ([]*types.Issue, bool) {
|
|||
// listBlocking is the decoration keyed the way the two formatters read it.
|
||||
//
|
||||
// The role answers with a SLICE in request order, because that is what an HTTP
|
||||
// body needs and what makes the answer zippable against the ids that were sent.
|
||||
// The formatters index by id, so the three maps are rebuilt here — at the front
|
||||
// door, once per route, rather than in a role that would then have to promise
|
||||
// three separate containers can never disagree.
|
||||
// body needs. The formatters index by id, so the three maps are rebuilt at the
|
||||
// front door, once per route, rather than in a role that would then have to
|
||||
// promise three separate containers can never disagree.
|
||||
type listBlocking struct {
|
||||
blockedBy map[string][]string
|
||||
blocks map[string][]string
|
||||
|
|
@ -71,7 +65,6 @@ func newListBlocking(result issueops.BlockingResult) listBlocking {
|
|||
// annotateListBlocking is the DIRECT route's decoration read. It swallows every
|
||||
// failure, including the accessor's, because that is what this route has always
|
||||
// done: `bd list` renders the page undecorated rather than refusing to print it.
|
||||
// See the note at the call site for why that is recorded rather than converged.
|
||||
func annotateListBlocking(ctx context.Context, store storage.DoltStorage, ids []string) listBlocking {
|
||||
annotator, err := store.BlockingAnnotator()
|
||||
if err != nil {
|
||||
|
|
@ -85,8 +78,7 @@ func annotateListBlocking(ctx context.Context, store storage.DoltStorage, ids []
|
|||
}
|
||||
|
||||
// proxiedBlockingAnnotator hands back the guarded blocking-decoration surface
|
||||
// for the proxied-server provider, through the provider's OWN capability
|
||||
// accessor — the same two-step a direct command performs on a store.
|
||||
// for the proxied-server provider, through the provider's own accessor.
|
||||
func proxiedBlockingAnnotator() (issueops.BlockingAnnotator, error) {
|
||||
if uowProvider == nil {
|
||||
return nil, errors.New("proxied-server UOW provider not initialized")
|
||||
|
|
|
|||
|
|
@ -8,14 +8,12 @@ import (
|
|||
)
|
||||
|
||||
// The two projections `bd list` performs between its roles and its formatters.
|
||||
// Both routes call them, so a regression here is one that shows up on both at
|
||||
// once — which is exactly why they are pinned somewhere ungated rather than only
|
||||
// in the embedded and proxied suites.
|
||||
// Both routes call them, so a regression here shows up on both at once.
|
||||
|
||||
// TestListPageIssuesKeepsThePageOrder pins the one thing the projection must not
|
||||
// do: reorder. The page's order is issueops.Reader.List's epilogue's decision,
|
||||
// and a projection that rebuilt the slice from a map would silently replace it
|
||||
// with map-iteration order.
|
||||
// do: reorder. The page's order is issueops.Reader.List's decision, and a
|
||||
// projection that rebuilt the slice from a map would replace it with
|
||||
// map-iteration order.
|
||||
func TestListPageIssuesKeepsThePageOrder(t *testing.T) {
|
||||
page := issueops.IssuePage{
|
||||
Items: []*types.IssueWithCounts{
|
||||
|
|
@ -41,9 +39,9 @@ func TestListPageIssuesKeepsThePageOrder(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestListPageIssuesDropsANilRowRatherThanPanicking pins the defensive half. The
|
||||
// role promises no nil row for a successful call; a listing is not where a
|
||||
// broken implementation of it should become a panic in front of a user.
|
||||
// TestListPageIssuesDropsANilRowRatherThanPanicking pins the defensive half: the
|
||||
// role promises no nil row, and a listing is not where a broken implementation
|
||||
// of it should become a panic in front of a user.
|
||||
func TestListPageIssuesDropsANilRowRatherThanPanicking(t *testing.T) {
|
||||
page := issueops.IssuePage{Items: []*types.IssueWithCounts{
|
||||
{Issue: &types.Issue{ID: "bd-1"}},
|
||||
|
|
@ -61,11 +59,10 @@ func TestListPageIssuesDropsANilRowRatherThanPanicking(t *testing.T) {
|
|||
// TestNewListBlockingKeysTheDecorationByID pins the other projection: the role
|
||||
// answers with a slice in request order, and the formatters index by id.
|
||||
//
|
||||
// The empty entry is the case worth having. formatDependencyInfo prints nothing
|
||||
// when all three are empty, and it reaches that decision through
|
||||
// `len(blockedBy) == 0 && len(blocks) == 0 && parent == ""` on the values these
|
||||
// maps hand back — so an absent key and an empty slice have to read the same,
|
||||
// which is what leaving the key out establishes.
|
||||
// The empty entry is the case worth having: formatDependencyInfo decides
|
||||
// through `len(blockedBy) == 0 && len(blocks) == 0 && parent == ""` on the
|
||||
// values these maps hand back, so an absent key and an empty slice have to read
|
||||
// the same.
|
||||
func TestNewListBlockingKeysTheDecorationByID(t *testing.T) {
|
||||
blocking := newListBlocking(issueops.BlockingResult{Items: []issueops.IssueBlocking{
|
||||
{ID: "bd-1", BlockedBy: []string{"bd-2", "bd-3"}, Blocks: []string{}, Parent: "bd-9"},
|
||||
|
|
|
|||
|
|
@ -304,14 +304,8 @@ func parseMarkdownFile(path string) ([]*IssueTemplate, error) {
|
|||
}
|
||||
|
||||
// createIssuesFromMarkdown creates every issue in a markdown file as ONE act,
|
||||
// through issueops.BatchCreator.
|
||||
//
|
||||
// THE BATCH IS NOT IMPLEMENTED HERE, and that is the point. Which rows land
|
||||
// together, what an occupied explicit id does, what an edge onto an absent
|
||||
// target does, the create-only guard, the wisp routing and the history entry
|
||||
// all belong to the contract; this function parses a file, lints it, builds one
|
||||
// request and prints what came back. The proxied route builds the SAME request
|
||||
// and the only difference between the two is which accessor answers.
|
||||
// through issueops.BatchCreator. It parses the file, lints it, builds one
|
||||
// request and prints what came back; the proxied route builds the SAME request.
|
||||
func createIssuesFromMarkdown(ctx context.Context, in createInput) error {
|
||||
templates, err := parseMarkdownFile(in.markdownFile)
|
||||
if err != nil {
|
||||
|
|
@ -359,13 +353,11 @@ func createIssuesFromMarkdown(ctx context.Context, in createInput) error {
|
|||
}
|
||||
|
||||
// buildMarkdownBatchRequest is the ONE projection of a parsed markdown file
|
||||
// onto the role's request, shared by both front doors. Every rule about what a
|
||||
// `--file` create MEANS lives here or below it, so the two routes cannot answer
|
||||
// differently.
|
||||
// onto the role's request, shared by both front doors, so the two routes cannot
|
||||
// answer differently.
|
||||
//
|
||||
// It lints first, because the lint is about the FILE the user wrote — a
|
||||
// template with no acceptance criteria is worth refusing before anything is
|
||||
// created, and refusing it here costs no transaction.
|
||||
// It lints first, because the lint is about the FILE the user wrote and
|
||||
// refusing it here costs no transaction.
|
||||
func buildMarkdownBatchRequest(templates []*IssueTemplate, in createInput) (issueops.CreateBatchRequest, error) {
|
||||
if err := lintMarkdownTemplates(templates, in); err != nil {
|
||||
return issueops.CreateBatchRequest{}, err
|
||||
|
|
|
|||
|
|
@ -29,9 +29,8 @@ type purgeScope struct {
|
|||
// (e.g. "closed ephemeral bead", "closed bead"). "(s)" is appended by
|
||||
// the printer when multiple items are involved.
|
||||
subjectNoun string
|
||||
// tier is the plane this command sweeps. The two are DISJOINT, which is
|
||||
// what makes purge and prune one capability rather than two: `prune` never
|
||||
// touches a wisp that `purge` would handle, and vice versa.
|
||||
// tier is the plane this command sweeps. The two are DISJOINT: `prune`
|
||||
// never touches a wisp that `purge` would handle, and vice versa.
|
||||
tier issueops.SweepTier
|
||||
// protectReferenced asks the role to skip candidates cited by a bead that
|
||||
// is not done. `bd prune` asks unless --ignore-references; `bd purge`
|
||||
|
|
@ -89,8 +88,7 @@ EXAMPLES:
|
|||
}
|
||||
|
||||
// openSweeper hands back the bulk-clearance role for whichever route this
|
||||
// invocation is on, each through its OWN capability accessor — the store's for
|
||||
// the direct route and the provider's for the proxied one.
|
||||
// invocation is on.
|
||||
func openSweeper() (issueops.Sweeper, error) {
|
||||
if usesProxiedServer() {
|
||||
return proxiedSweeper()
|
||||
|
|
@ -104,12 +102,7 @@ func openSweeper() (issueops.Sweeper, error) {
|
|||
}
|
||||
|
||||
// runPurgeOrPrune implements the shared delete-closed-beads flow used by both
|
||||
// `bd purge` (ephemeral tier) and `bd prune` (durable tier).
|
||||
//
|
||||
// It is ONE body across both routes now rather than two: the proxied twin held
|
||||
// a second copy of the selection, the recheck, the reference scan and every
|
||||
// line of output, and the two routes disagreed about which transaction the
|
||||
// deletion ran in.
|
||||
// `bd purge` (ephemeral tier) and `bd prune` (durable tier), on both routes.
|
||||
func runPurgeOrPrune(cmd *cobra.Command, scope purgeScope) error {
|
||||
CheckReadonly(scope.cmdName)
|
||||
|
||||
|
|
@ -119,13 +112,11 @@ func runPurgeOrPrune(cmd *cobra.Command, scope purgeScope) error {
|
|||
pattern, _ := cmd.Flags().GetString("pattern")
|
||||
|
||||
// The ROLE refuses an unfiltered durable sweep — that guard is
|
||||
// workapi.ValidateSweepRequest, below every front door, so an HTTP handler
|
||||
// or a library embedder inherits it instead of having to remember it. This
|
||||
// branch is here for the MESSAGE and nothing else: the role's refusal
|
||||
// names request fields, and a person who typed `bd prune --force` needs to
|
||||
// be told which two flags to reach for. The contract case
|
||||
// RunSweeperRefusesAnUnfilteredDurableSweep is what proves the guard
|
||||
// survives this branch being deleted.
|
||||
// workapi.ValidateSweepRequest, below every front door. This branch is here
|
||||
// for the MESSAGE: the role's refusal names request fields, not the two
|
||||
// flags a person who typed `bd prune --force` has to reach for. The contract
|
||||
// case RunSweeperRefusesAnUnfilteredDurableSweep proves the guard survives
|
||||
// this branch being deleted.
|
||||
if scope.tier == issueops.SweepDurable && olderThan == "" && pattern == "" {
|
||||
return HandleErrorWithHint(
|
||||
fmt.Sprintf("bd %s requires --older-than or --pattern", scope.cmdName),
|
||||
|
|
@ -141,9 +132,7 @@ func runPurgeOrPrune(cmd *cobra.Command, scope purgeScope) error {
|
|||
ProtectReferenced: scope.protectReferenced,
|
||||
// A --dry-run and an UNCONFIRMED run ask the role the same question —
|
||||
// "what would this do" — so both send DryRun. --force is this
|
||||
// command's confirmation, not a request field, and a sweep that
|
||||
// answered the confirmation prompt by deleting would be the worst
|
||||
// possible reading of it.
|
||||
// command's confirmation, not a request field.
|
||||
DryRun: dryRun || !force,
|
||||
}
|
||||
if olderThan != "" {
|
||||
|
|
@ -182,8 +171,7 @@ func runPurgeOrPrune(cmd *cobra.Command, scope purgeScope) error {
|
|||
|
||||
// warnSweepDefenseSkips reports the candidates the role's own recheck threw
|
||||
// out. A non-zero count means the tier query and the recheck disagreed about
|
||||
// which rows are closed, which is worth a line on stderr whatever the output
|
||||
// mode — see issueops.SweepSkips.
|
||||
// which rows are closed, which earns a line on stderr in any output mode.
|
||||
func warnSweepDefenseSkips(skips issueops.SweepSkips) {
|
||||
total := skips.Unreadable + skips.NotClosed + skips.UnknownClosedAt + skips.ClosedAtOrAfterCutoff
|
||||
if total == 0 {
|
||||
|
|
|
|||
|
|
@ -111,12 +111,8 @@ Examples:
|
|||
}
|
||||
|
||||
// openQuerier hands back the boolean-query role for whichever route this
|
||||
// invocation is on, each through its OWN capability accessor — the store's for
|
||||
// the direct route and the provider's for the proxied one. Neither branch
|
||||
// parses the expression, builds a filter or opens a unit of work: that is the
|
||||
// whole of what moved behind the role, and it used to be written out twice,
|
||||
// once per route, including the over-fetch heuristic that made both of them
|
||||
// wrong.
|
||||
// invocation is on. Neither branch parses the expression, builds a filter or
|
||||
// opens a unit of work: that is what moved behind the role.
|
||||
func openQuerier() (issueops.Querier, error) {
|
||||
if usesProxiedServer() {
|
||||
return proxiedQuerier()
|
||||
|
|
@ -138,14 +134,12 @@ type queryInput struct {
|
|||
}
|
||||
|
||||
// gatherQueryInput turns the flags into the role's request. It is flag parsing
|
||||
// and nothing else: the expression is handed over verbatim, because parsing it
|
||||
// — and deciding what an OR costs — is what the role exists to own.
|
||||
// and nothing else: the expression is handed over verbatim.
|
||||
//
|
||||
// ONE REFUSAL IS LEFT HERE, and it is flag hygiene rather than semantics: a
|
||||
// negative --offset is not a page request at all. The two that WERE here are
|
||||
// gone — the role refuses an offset under a display order for every caller,
|
||||
// and answers an offset over a predicate query correctly rather than refusing
|
||||
// it.
|
||||
// gone — the role refuses an offset under a display order for every caller, and
|
||||
// answers an offset over a predicate query correctly rather than refusing it.
|
||||
func gatherQueryInput(cmd *cobra.Command, args []string) (queryInput, error) {
|
||||
if len(args) == 0 {
|
||||
fmt.Fprintf(os.Stderr, "Error: query expression is required\n\n")
|
||||
|
|
@ -182,10 +176,8 @@ func gatherQueryInput(cmd *cobra.Command, args []string) (queryInput, error) {
|
|||
|
||||
// printParsedQuery serves --parse-only, which opens no store: it is a debugging
|
||||
// view of the AST, not a query, and asking for the role to print it would make
|
||||
// a syntax check need a database.
|
||||
//
|
||||
// Its refusal is worded as the ROLE words the same fault, so a syntax error
|
||||
// reads the same whether or not the caller asked for the AST.
|
||||
// a syntax check need a database. Its refusal is worded as the ROLE words the
|
||||
// same fault, so a syntax error reads the same either way.
|
||||
func printParsedQuery(expression string) error {
|
||||
node, err := query.Parse(expression)
|
||||
if err != nil {
|
||||
|
|
@ -209,9 +201,9 @@ func runQuery(ctx context.Context, querier issueops.Querier, in queryInput) erro
|
|||
} else {
|
||||
outputQueryResults(queryPageIssues(page.Items), in.expression, in.longFormat)
|
||||
}
|
||||
// The hint is on stderr and on BOTH routes now. The direct one printed
|
||||
// nothing before, not by choice: it had no has-more verdict to print,
|
||||
// because the query it ran was the truncating one.
|
||||
// The hint is on stderr and on BOTH routes now: the direct one had no
|
||||
// has-more verdict to print before, because the query it ran was the
|
||||
// truncating one.
|
||||
printTruncationHint(page.HasMore, in.limit)
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -348,8 +348,8 @@ func TestProxiedServerQuery(t *testing.T) {
|
|||
})
|
||||
|
||||
// The wording is the ROLE's now, on both routes: the expression is parsed
|
||||
// inside issueops.Querier, so the refusal a caller reads is the one the
|
||||
// library wrote rather than one of two the front doors each wrote.
|
||||
// inside issueops.Querier, so the refusal a caller reads is the library's
|
||||
// rather than one of two the front doors each wrote.
|
||||
t.Run("invalid_expression_fails", func(t *testing.T) {
|
||||
out := bdProxiedQueryFail(t, bd, p, "===invalid===")
|
||||
if !strings.Contains(out, "invalid query expression") {
|
||||
|
|
|
|||
|
|
@ -12,17 +12,14 @@ import (
|
|||
)
|
||||
|
||||
// proxiedQuerier hands back the guarded boolean-query surface for the
|
||||
// proxied-server provider, through the provider's OWN capability accessor —
|
||||
// the same two-step proxiedCounter performs, and for the same reason: the
|
||||
// accessor is where each layer is added.
|
||||
// proxied-server provider, through the provider's own accessor.
|
||||
//
|
||||
// TWO --offset REFUSALS LEFT WITH IT, in opposite directions. "--offset is not
|
||||
// supported with OR/predicate queries" is GONE: it existed because an offset
|
||||
// into a window that had already dropped matches meant nothing, and the window
|
||||
// is gone, so the role answers that combination correctly. "--offset with a
|
||||
// display order" is still refused, but by the ROLE and for every caller — the
|
||||
// order is applied to the rows the query bounded, so paging under a sort would
|
||||
// sort each page for itself.
|
||||
// is gone. "--offset with a display order" is still refused, but by the ROLE
|
||||
// and for every caller, because paging under a sort would sort each page for
|
||||
// itself.
|
||||
func proxiedQuerier() (issueops.Querier, error) {
|
||||
if uowProvider == nil {
|
||||
return nil, errors.New("proxied-server UOW provider not initialized")
|
||||
|
|
@ -35,9 +32,7 @@ func proxiedQuerier() (issueops.Querier, error) {
|
|||
}
|
||||
|
||||
// runQueryProxiedServer is the proxied route's entry point. It reads the same
|
||||
// flags the direct route reads and asks the same role, and the only line the
|
||||
// direct route has that this one does not is the refusal of an --offset it
|
||||
// cannot serve.
|
||||
// flags the direct route reads and asks the same role.
|
||||
func runQueryProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error {
|
||||
in, err := gatherQueryInput(cmd, args)
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -179,17 +179,10 @@ This is useful for agents executing molecules to see which steps can run next.`,
|
|||
totalReady := len(results)
|
||||
truncated := false
|
||||
if filter.Limit > 0 && len(results) == filter.Limit {
|
||||
// The page is full, so there may be more ready work. The size of
|
||||
// the whole ready set is the ReadyCounter role's question, asked
|
||||
// through the store's own accessor: the role promises its answer
|
||||
// equals len(Reader.Ready(Limit=0).Items), which is what makes
|
||||
// this total describe the page above it.
|
||||
//
|
||||
// It used to be asked here, of the store: unwrap past the
|
||||
// decorators, type-assert to storage.ReadyWorkCounter, and fall
|
||||
// back to the unbounded mega-query when the assertion missed.
|
||||
// That is now the role's business and the assertion is a
|
||||
// compile-time one (internal/workapi/storereadycounter).
|
||||
// The page is full, so there may be more ready work. The
|
||||
// ReadyCounter role promises its answer equals
|
||||
// len(Reader.Ready(Limit=0).Items), which is what makes this
|
||||
// total describe the page above it.
|
||||
if n, countErr := readyTotal(ctx, activeStore, in); countErr == nil && n > len(results) {
|
||||
totalReady = n
|
||||
truncated = true
|
||||
|
|
@ -228,8 +221,7 @@ This is useful for agents executing molecules to see which steps can run next.`,
|
|||
if filter.Limit > 0 && len(issues) == filter.Limit {
|
||||
// The same question the --json branch asks, through the same role,
|
||||
// so the "Showing X of N" a human reads and the total a script
|
||||
// parses are one number. This branch used to re-run the whole
|
||||
// unbounded ready query to size N.
|
||||
// parses are one number.
|
||||
if n, countErr := readyTotal(ctx, activeStore, in); countErr == nil && n > len(issues) {
|
||||
totalReady = n
|
||||
truncated = true
|
||||
|
|
@ -341,13 +333,11 @@ var blockedCmd = &cobra.Command{
|
|||
//
|
||||
// BOTH OUTPUT MODES CALL IT and only when the page came back full, which is
|
||||
// the one situation where the answer can differ from what is already on
|
||||
// screen. The role has no --max-rows field to honor and needs none: the cap is
|
||||
// a bound on a page this machine will materialize, and a count materializes no
|
||||
// rows — which is also why handleMaxRowsError has nothing to classify here.
|
||||
// screen. The role has no --max-rows field to honor and needs none: the cap
|
||||
// bounds a page this machine materializes, and a count materializes no rows.
|
||||
//
|
||||
// A failed count is not a failed command. The page is already correct; all
|
||||
// that is lost is the "of N" beside it, exactly as it was before this question
|
||||
// became a role.
|
||||
// A failed count is not a failed command — the page is already correct; all
|
||||
// that is lost is the "of N" beside it.
|
||||
func readyTotal(ctx context.Context, activeStore storage.DoltStorage, in readyInput) (int, error) {
|
||||
counter, err := activeStore.ReadyCounter()
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -23,11 +23,8 @@ type readyInput struct {
|
|||
|
||||
// dirLabels is the directory-label default (GH#541) this listing applied,
|
||||
// or nil when it did not apply one. It is the gatherer's DECISION rather
|
||||
// than the configured value: whether the default applies depends on
|
||||
// whether the caller named a label, and that question is answerable only
|
||||
// before the default has been written onto the filter. See
|
||||
// readyRoleRequest, which read it back off the filter and got the wrong
|
||||
// answer for exactly that reason.
|
||||
// than the configured value: the question is answerable only BEFORE the
|
||||
// default has been written onto the filter. See readyRoleRequest.
|
||||
dirLabels []string
|
||||
|
||||
claim bool
|
||||
|
|
@ -203,12 +200,9 @@ func gatherReadyInput(cmd *cobra.Command, resolveCap func(*cobra.Command) (int,
|
|||
if len(filter.Labels) == 0 && len(filter.LabelsAny) == 0 {
|
||||
if dirLabels := config.GetDirectoryLabels(); len(dirLabels) > 0 {
|
||||
filter.LabelsAny = dirLabels
|
||||
// Recorded rather than recomputed downstream. readyRoleRequest
|
||||
// needs the same answer, and it cannot ask this question again:
|
||||
// the line above has just made the filter's label sets non-empty,
|
||||
// so a second evaluation of the same emptiness test reads its own
|
||||
// output and concludes the default does not apply. It did exactly
|
||||
// that until this field existed — see readyRoleRequest.
|
||||
// Recorded rather than recomputed downstream: the line above has
|
||||
// just made the filter's label sets non-empty, so re-running the
|
||||
// emptiness test would read its own output.
|
||||
in.dirLabels = dirLabels
|
||||
}
|
||||
}
|
||||
|
|
@ -221,8 +215,7 @@ func gatherReadyInput(cmd *cobra.Command, resolveCap func(*cobra.Command) (int,
|
|||
// whole ready question rather than a filter: ReadyClaimer, which claims one
|
||||
// row out of it, and ReadyCounter, which sizes it. Both routes of both
|
||||
// operations build it here, so a claim, a count and the listing beside them
|
||||
// ask ONE question no matter which door they came through — it is the same
|
||||
// issueops.ReadyRequest the listing builds its filter from.
|
||||
// ask ONE question no matter which door they came through.
|
||||
//
|
||||
// The two things the filter carries that the request does not:
|
||||
//
|
||||
|
|
@ -230,31 +223,24 @@ func gatherReadyInput(cmd *cobra.Command, resolveCap func(*cobra.Command) (int,
|
|||
// one row however large the pool it scanned (ClaimReadyIssueInTx clears
|
||||
// MaxRows, MaxRowsSource and Limit before it scans, because a cap sized
|
||||
// for bulk reads must not make a single-row claim report an empty front),
|
||||
// and a count materializes no rows at all. Dropping it here is visible
|
||||
// only in that neither role has a field to ignore.
|
||||
// and a count materializes no rows at all.
|
||||
//
|
||||
// - The directory-label default (GH#541). The listing puts it on the built
|
||||
// filter verbatim; here it goes on the request, where it is normalized
|
||||
// along with every other label. That differs only for a directory.labels
|
||||
// value carrying stray whitespace.
|
||||
//
|
||||
// IT IS READ OFF readyInput.dirLabels, WHICH IS THE FIX. This used to
|
||||
// re-run the gatherer's own emptiness test against in.filter — and by
|
||||
// then the gatherer had already written the default INTO that filter, so
|
||||
// the test saw a non-empty label set and skipped. The branch could
|
||||
// therefore never fire: with no directory label configured there was
|
||||
// nothing to apply, and with one configured the filter it checked was the
|
||||
// one carrying it. `bd ready --claim` in a scoped directory consequently
|
||||
// claimed from the WHOLE ready front while `bd ready` beside it listed
|
||||
// only the configured scope, which is the one thing ReadyClaimer's
|
||||
// contract says a claim must never do (issueops/readyclaimer.go:9-14).
|
||||
// Recording the decision where it is made leaves one answer instead of
|
||||
// two derivations of it.
|
||||
// IT IS READ OFF readyInput.dirLabels, NEVER RECOMPUTED FROM in.filter.
|
||||
// The gatherer has already written the default INTO that filter, so
|
||||
// re-running its emptiness test here sees a non-empty label set and skips.
|
||||
// That is what made `bd ready --claim` in a scoped directory claim from
|
||||
// the WHOLE ready front while `bd ready` beside it listed only the
|
||||
// configured scope — the one thing ReadyClaimer's contract says a claim
|
||||
// must never do (issueops/readyclaimer.go:9-14).
|
||||
//
|
||||
// Limit and Offset are ErrValidation on BOTH roles, so they are cleared here
|
||||
// once. Neither was ever live for the claim (--offset with --claim is already
|
||||
// a usage error above and the claim scan zeroes the limit itself); for the
|
||||
// count they are exactly what has to go — the page is the thing being sized.
|
||||
// once. Neither was ever live for the claim; for the count they are exactly
|
||||
// what has to go — the page is the thing being sized.
|
||||
func readyRoleRequest(in readyInput) issueops.ReadyRequest {
|
||||
req := in.ReadyRequest
|
||||
req.Limit, req.Offset = nil, 0
|
||||
|
|
|
|||
|
|
@ -125,16 +125,13 @@ func runReadyProxiedList(ctx context.Context, uw uow.UnitOfWork, in readyInput)
|
|||
// Parity with the direct route: the pagination key is emitted only
|
||||
// when truncated, and it now carries the same Total, from the same
|
||||
// role. This route published no total at all until ReadyCounter
|
||||
// existed — the domain page reports has-more and nothing else, and
|
||||
// there is no cheap COUNT(*) on this seam — so a script that read
|
||||
// `pagination.total` got one number under a direct-mode workspace and
|
||||
// no key at all under a proxied one.
|
||||
// existed, so a script that read `pagination.total` got one number
|
||||
// under a direct-mode workspace and no key at all under a proxied one.
|
||||
//
|
||||
// The guard is the direct route's guard: a total that does not exceed
|
||||
// the page says nothing this envelope does not already say, and the
|
||||
// two queries are not one snapshot (issueops.ReadyCounter.CountReady),
|
||||
// so a close landing between them must not publish a total smaller
|
||||
// than the page beside it.
|
||||
// The guard is the direct route's guard: the two queries are not one
|
||||
// snapshot (issueops.ReadyCounter.CountReady), so a close landing
|
||||
// between them must not publish a total smaller than the page beside
|
||||
// it.
|
||||
var pag *PaginationMeta
|
||||
if truncated {
|
||||
pag = &PaginationMeta{
|
||||
|
|
@ -243,10 +240,9 @@ func runReadyProxiedClaim(ctx context.Context, in readyInput) error {
|
|||
// ReadyCounter accessor — the same role the direct route reaches through the
|
||||
// store's accessor, over the request both build in readyRoleRequest.
|
||||
//
|
||||
// It opens NO unit of work of its own, and the caller's is not handed to it:
|
||||
// the role's request is the transaction, exactly as it is for the claim beside
|
||||
// it. So the count runs in its own read-only unit of work rather than the one
|
||||
// the page came from, which is why the two are not one snapshot.
|
||||
// It opens NO unit of work of its own: the role's request IS the transaction,
|
||||
// so the count runs in its own read-only unit of work rather than the one the
|
||||
// page came from, which is why the two are not one snapshot.
|
||||
func proxiedReadyTotal(ctx context.Context, in readyInput) (int, error) {
|
||||
if uowProvider == nil {
|
||||
return 0, errors.New("proxied-server UOW provider not initialized")
|
||||
|
|
|
|||
|
|
@ -12,10 +12,9 @@ import (
|
|||
// `bd ready` share: the claim and the count are asked over the LISTING's
|
||||
// request with the page removed.
|
||||
//
|
||||
// Both roles refuse a Limit and an Offset (ErrValidation), so a request that
|
||||
// carried either would fail at the seam rather than silently ignore it — and
|
||||
// for the count, which is published as "showing 2 of N", a limit that survived
|
||||
// would make N the size of the page instead of the size of the set.
|
||||
// Both roles refuse a Limit and an Offset (ErrValidation). For the count,
|
||||
// published as "showing 2 of N", a limit that survived would make N the size of
|
||||
// the page instead of the size of the set.
|
||||
func TestReadyRoleRequestDropsThePage(t *testing.T) {
|
||||
got := runGatherReadyInput(t, newReadyFlagsCommand(t, "--limit", "5", "--label", "api"), nil)
|
||||
if got.err != nil {
|
||||
|
|
@ -44,9 +43,9 @@ func TestReadyRoleRequestDropsThePage(t *testing.T) {
|
|||
t.Errorf("the claim's filter and the shared role request differ:\nclaim: %+v\nrole: %+v", claim.Filter, req)
|
||||
}
|
||||
|
||||
// And the predicate the count actually runs is the listing's predicate,
|
||||
// unbounded — the identity issueops.ReadyCounter promises, checked here at
|
||||
// the front door rather than only at the three backends.
|
||||
// And the predicate the count actually runs is the listing's, unbounded —
|
||||
// the identity issueops.ReadyCounter promises, checked at the front door
|
||||
// rather than only at the three backends.
|
||||
counted, err := workapi.BuildReadyCountFilter(req)
|
||||
if err != nil {
|
||||
t.Fatalf("BuildReadyCountFilter: %v", err)
|
||||
|
|
@ -65,12 +64,9 @@ func TestReadyRoleRequestDropsThePage(t *testing.T) {
|
|||
|
||||
// TestReadyRoleRequestCarriesTheDirectoryLabelDefault pins the one thing the
|
||||
// role request adds that the raw flags do not: GH#541's configured label,
|
||||
// applied under the same gate the listing applies it under.
|
||||
//
|
||||
// It goes on the REQUEST here rather than on the built filter, so it is
|
||||
// normalized with every other label — which is exactly why it is asserted:
|
||||
// a count or a claim that missed the default would answer for a wider set than
|
||||
// the listing beside it shows.
|
||||
// applied under the same gate the listing applies it under. A count or a claim
|
||||
// that missed the default would answer for a wider set than the listing beside
|
||||
// it shows.
|
||||
func TestReadyRoleRequestCarriesTheDirectoryLabelDefault(t *testing.T) {
|
||||
const configured = "scope:web"
|
||||
configureDirectoryLabel(t, configured)
|
||||
|
|
|
|||
|
|
@ -236,9 +236,7 @@ func TestProxiedServerReopen(t *testing.T) {
|
|||
|
||||
// Q2, adopted: a multi-id reopen writes ONE HISTORY ENTRY PER ID, naming
|
||||
// that id, where this route used to write one combined "bd: reopen a, b".
|
||||
// The role owns the transaction and hands out no handle to hold open, so
|
||||
// per-id is what falls out of calling it once per id — and it is what the
|
||||
// direct route has always written, which is the point of the move.
|
||||
// It is what the direct route has always written.
|
||||
t.Run("batch_commits_once_per_id", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
p := newSharedProxiedProject(t, bd, "rosd")
|
||||
|
|
|
|||
|
|
@ -20,36 +20,27 @@ import (
|
|||
// before the reopens ran.
|
||||
type reopenProxiedTarget struct {
|
||||
id string
|
||||
// status is the prior status, and it feeds the audit sidecar's old_value
|
||||
// and nothing else. The role's result is a post-state snapshot and carries
|
||||
// no prior status, and a constant "closed" is exactly the value this commit
|
||||
// would make wrong, now that a configured done status reopens here.
|
||||
// status is the prior status, and it feeds the audit sidecar's old_value and
|
||||
// nothing else. The role's result is a post-state snapshot with no prior
|
||||
// status, and a constant "closed" is now wrong: a configured done status
|
||||
// reopens here too.
|
||||
status types.Status
|
||||
}
|
||||
|
||||
// runReopenProxiedServer reopens each id through issueops.Lifecycle — the same
|
||||
// role, reached through the same kind of accessor, that the direct route calls.
|
||||
// Nothing here decides what a reopen means: the plane resolve, the done-category
|
||||
// rule, the reopened event, the version-control entry and the whole-attempt
|
||||
// retry all live behind the call, so the two routes can no longer answer the
|
||||
// same command differently.
|
||||
//
|
||||
// TWO BEHAVIORS CHANGE, both of them toward the direct route.
|
||||
// Nothing here decides what a reopen means.
|
||||
//
|
||||
// A CONFIGURED DONE STATUS NOW REOPENS. This route used to compare the current
|
||||
// status against literal StatusClosed and report "already <status>" for
|
||||
// anything else, so an issue parked on a custom done status could not be
|
||||
// reopened on a team server while the same command worked locally. The role
|
||||
// speaks in terms of the configured done CATEGORY
|
||||
// (issueops/issueops.go:417-420), and the contract pins that at all three
|
||||
// backends.
|
||||
// (issueops/issueops.go:417-420).
|
||||
//
|
||||
// ONE CALL PER ID, so one transaction and one history entry per id, where this
|
||||
// route used to run every id in one unit of work under a hand-composed
|
||||
// "bd: reopen a, b" message. The role hands out no transaction handle to hold
|
||||
// open, and a batch role for a two-flag command is not warranted (Q2,
|
||||
// recommended and non-blocking), so the per-id entry the direct route has
|
||||
// always written is what both routes now write.
|
||||
// "bd: reopen a, b" message.
|
||||
func runReopenProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error {
|
||||
if len(args) == 0 {
|
||||
return HandleErrorRespectJSON("no issue ID provided")
|
||||
|
|
@ -91,8 +82,7 @@ func runReopenProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri
|
|||
if !result.Changed {
|
||||
// Read off the result rather than off the pre-read: the status the
|
||||
// reopen left in place is the one the operation saw inside its own
|
||||
// transaction, and it is what lets this route reach the
|
||||
// already-open line without a short-circuit of its own.
|
||||
// transaction.
|
||||
fmt.Fprintln(os.Stderr, reopenNoOpMessage(target.id, reopenStatusOf(result.Issue, nil)))
|
||||
continue
|
||||
}
|
||||
|
|
@ -104,8 +94,7 @@ func runReopenProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri
|
|||
if jsonOut {
|
||||
if issue := result.Issue; issue != nil {
|
||||
// `bd reopen` has never printed dependency records, on either
|
||||
// route: the direct route drops them from the operation's own
|
||||
// snapshot for exactly this reason.
|
||||
// route.
|
||||
issue.Dependencies = nil
|
||||
reopenedIssues = append(reopenedIssues, issue)
|
||||
}
|
||||
|
|
@ -132,16 +121,13 @@ func runReopenProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri
|
|||
// reports the ones that did not resolve, returning the survivors with the
|
||||
// status each sat at.
|
||||
//
|
||||
// It is the shape `bd close`'s preflight landed with, and it exists for the two
|
||||
// things the role's result cannot supply: the audit sidecar's old_value, and
|
||||
// the difference between an absent id and a backend that failed to answer —
|
||||
// which this route has always drawn, and which reportIssueLookupFailure spells
|
||||
// the same way here as it does for `bd show`.
|
||||
// It exists for the two things the role's result cannot supply: the audit
|
||||
// sidecar's old_value, and the difference between an absent id and a backend
|
||||
// that failed to answer.
|
||||
//
|
||||
// It decides NOTHING about the reopen. A resolved id goes to the role whatever
|
||||
// status it is at, including a status this route used to refuse; the read is a
|
||||
// transaction earlier than the mutation, and every guard that matters is inside
|
||||
// the role's own.
|
||||
// status it is at, including a status this route used to refuse; every guard
|
||||
// that matters is inside the role's own transaction.
|
||||
func reopenProxiedResolve(ctx context.Context, ids []string) ([]reopenProxiedTarget, bool, error) {
|
||||
var targets []reopenProxiedTarget
|
||||
failed := false
|
||||
|
|
|
|||
|
|
@ -408,12 +408,10 @@ func errServeEmbedded() error {
|
|||
//
|
||||
// The assertion is conditional because a BD_NO_HOOKS=1 workspace has no hook
|
||||
// layer to peel.
|
||||
// It returns the WHOLE set httpapi.Config requires, not the two the first
|
||||
// version of this arm needed. httpapi.Listen refuses a partial set (see
|
||||
// checkDatabaseSource), so a role added to Config without being added here is
|
||||
// a startup failure on this arm rather than a nil dereference on the first
|
||||
// request that reaches it — which is why this returns a struct that must be
|
||||
// spread field-by-field instead of a growing list of unnamed results.
|
||||
//
|
||||
// It returns the WHOLE set httpapi.Config requires; Listen refuses a partial
|
||||
// set (see checkDatabaseSource), so a role missing here is a startup failure
|
||||
// rather than a nil dereference on the first request that reaches it.
|
||||
func serveIssueRoles(src storage.DoltStorage) (serveRoles, error) {
|
||||
var roles serveRoles
|
||||
if src == nil {
|
||||
|
|
@ -425,9 +423,8 @@ func serveIssueRoles(src storage.DoltStorage) (serveRoles, error) {
|
|||
src = hooked.Unwrap()
|
||||
}
|
||||
|
||||
// Each entry binds one Config field to the accessor that fills it. A role
|
||||
// whose accessor errors names itself in the failure, so an unsupported
|
||||
// role on some future backend says which one at startup.
|
||||
// Each entry binds one Config field to the accessor that fills it, and
|
||||
// names itself in the failure.
|
||||
type binding struct {
|
||||
name string
|
||||
get func() error
|
||||
|
|
@ -457,7 +454,7 @@ func serveIssueRoles(src storage.DoltStorage) (serveRoles, error) {
|
|||
// serveRoles is the store-shaped database source, assembled once before Listen.
|
||||
// It is deliberately NOT an httpapi.Config: the gate test in serve_test.go
|
||||
// requires every httpapi.Config literal in this package to sit in a function
|
||||
// that consulted serveDatabaseSource, and this one has not.
|
||||
// that consulted serveDatabaseSource.
|
||||
type serveRoles struct {
|
||||
reader issueops.Reader
|
||||
claimer issueops.Claimer
|
||||
|
|
|
|||
|
|
@ -184,9 +184,7 @@ func writeBrokenBeadsConfig(t *testing.T, beadsDir string) {
|
|||
// pin the peel DEPTH, which is the whole property under test: serveIssueRoles
|
||||
// peels once and then calls every accessor on that one store value, so no role
|
||||
// can come from a different layer than these two did. The rest return nil
|
||||
// because the extraction does not inspect them — httpapi.Listen is what
|
||||
// refuses a nil role, and TestServeAnswersFromARegisteredBackendStore is what
|
||||
// exercises that end of it against a real store.
|
||||
// because the extraction does not inspect them.
|
||||
type serveRolesStore struct {
|
||||
storage.DoltStorage
|
||||
reader *serveStubReader
|
||||
|
|
|
|||
|
|
@ -180,8 +180,7 @@ func (s *serveIdentityStore) Close() error { return nil }
|
|||
//
|
||||
// They hand back serveIdentityRole, which satisfies each interface by
|
||||
// EMBEDDING it rather than implementing it: non-nil, so the set is complete,
|
||||
// while an actual call panics naming the method it reached — the same choice
|
||||
// the nil DoltStorage above makes, for the same reason.
|
||||
// while an actual call panics naming the method it reached.
|
||||
func (*serveIdentityStore) WorkspaceConfig() (issueops.WorkspaceConfig, error) {
|
||||
return serveIdentityRole{}, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -91,12 +91,10 @@ Examples:
|
|||
} else {
|
||||
result, err = reporter.Stats(rootCtx, issueops.StatsRequest{SkipBlocked: noBlocked})
|
||||
if err == nil && noBlocked && result.Summary.BlockedIssues != nil {
|
||||
// The hint is a hint, and this is where a caller who asked for
|
||||
// the fast path finds out it was not available. It is derived
|
||||
// from the ANSWER rather than from the route: the two routes
|
||||
// differ on it today (the unit-of-work seam publishes no
|
||||
// no-blocked query), and a backend that gains one stops
|
||||
// printing this without an edit here.
|
||||
// Derived from the ANSWER rather than from the route: the two
|
||||
// routes differ on it today (the unit-of-work seam publishes no
|
||||
// no-blocked query), and a backend that gains one stops printing
|
||||
// this without an edit here.
|
||||
fmt.Fprintln(os.Stderr, "warning: this backend has no --no-blocked fast path; the full blocked-count query ran")
|
||||
}
|
||||
}
|
||||
|
|
@ -114,8 +112,7 @@ Examples:
|
|||
}
|
||||
|
||||
// openStatsReporter hands back the summary role for whichever route this
|
||||
// invocation is on, each through its OWN capability accessor — the store's for
|
||||
// the direct route and the provider's for the proxied one.
|
||||
// invocation is on, each through its own capability accessor.
|
||||
func openStatsReporter() (issueops.StatsReporter, error) {
|
||||
if usesProxiedServer() {
|
||||
return proxiedStatsReporter()
|
||||
|
|
|
|||
|
|
@ -30,8 +30,7 @@ func countAttemptRefusals(out string) int {
|
|||
// other's stale shape. #5206 added the policy and its two proxied refusal arms
|
||||
// while this path still ran a bespoke read-merge-write of its own, and the only
|
||||
// proxied coverage it shipped was a unit test on the spec that path built —
|
||||
// which passes whether or not the refusal ever reaches a user. The
|
||||
// read-merge-write is gone now, but the assertions still earn their keep: they
|
||||
// which passes whether or not the refusal ever reaches a user. These assertions
|
||||
// are the only proxied close-policy coverage that watches a user-visible
|
||||
// boundary rather than an internal request.
|
||||
//
|
||||
|
|
|
|||
|
|
@ -538,13 +538,10 @@ func TestProxiedServerUpdate2(t *testing.T) {
|
|||
bdProxiedUpdateOne(t, bd, p.dir, issue.ID, "--no-history")
|
||||
|
||||
// --no-history selects a WISP RETENTION MODE, so the aggregate moves to
|
||||
// the ephemeral plane rather than flipping a column on the durable row:
|
||||
// issueops.IssuePatch.Persistence says "Ephemeral and NoHistory select
|
||||
// wisp retention modes, never durable unversioned storage" and "every
|
||||
// aggregate move is atomic". The direct route has always done this; the
|
||||
// proxied route flipped the column in place until it joined the
|
||||
// contract, which left a durable row that the wisp-plane reads could
|
||||
// not see (bd-xt6de).
|
||||
// the ephemeral plane rather than flipping a column on the durable row
|
||||
// (issueops.IssuePatch.Persistence). The proxied route flipped the
|
||||
// column in place until it joined the contract, which left a durable
|
||||
// row that the wisp-plane reads could not see (bd-xt6de).
|
||||
if got := readPersistenceFlag(t, db, "wisps", "no_history", issue.ID); got != 1 {
|
||||
t.Errorf("wisps.no_history: got %d, want 1 after --no-history", got)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -71,8 +71,7 @@ func runUpdateProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri
|
|||
}
|
||||
|
||||
// proxiedIssueLifecycle asks the unit-of-work provider for the write role, the
|
||||
// same way proxiedIssueReader asks it for the read one. The accessor is the
|
||||
// door: a provider that cannot answer says so rather than being wired around.
|
||||
// same way proxiedIssueReader asks it for the read one.
|
||||
func proxiedIssueLifecycle() (issueops.Lifecycle, error) {
|
||||
if uowProvider == nil {
|
||||
return nil, errors.New("proxied-server UOW provider not initialized")
|
||||
|
|
@ -85,12 +84,10 @@ func proxiedIssueLifecycle() (issueops.Lifecycle, error) {
|
|||
}
|
||||
|
||||
// applyUpdateProxiedOne applies one issue's update — plain or --claim —
|
||||
// through issueops.Lifecycle rather than through a hand-rolled attempt.
|
||||
//
|
||||
// What stays here is this surface's own protocol: the template guard, the
|
||||
// advisory reassign pre-read, the per-id failure taxonomy the multi-id batch
|
||||
// needs, the notes-overwrite warning and the completion hooks — none of which
|
||||
// the HTTP surface has, and none of which is an update.
|
||||
// through issueops.Lifecycle. What stays here is this surface's own protocol:
|
||||
// the template guard, the advisory reassign pre-read, the per-id failure
|
||||
// taxonomy the multi-id batch needs, the notes-overwrite warning and the
|
||||
// completion hooks.
|
||||
//
|
||||
// Provenance carries the commit message this path has always written, so `bd
|
||||
// dolt log` reads the same after the move as before it. The plane is
|
||||
|
|
@ -98,11 +95,9 @@ func proxiedIssueLifecycle() (issueops.Lifecycle, error) {
|
|||
// unlike the HTTP claim endpoint, which serves durable issues only.
|
||||
//
|
||||
// The pre-read is a read of its own, one transaction earlier than the
|
||||
// mutation, so the guards it applies are advisory in a way they were not when
|
||||
// this file did the read itself. They guard command-shaped policy, not
|
||||
// invariants — the mutation's own guards are all inside the contract's
|
||||
// transaction, including the fence and the close policy — and paying for it is
|
||||
// what lets the update itself have exactly one implementation.
|
||||
// mutation, so the guards it applies are ADVISORY. The mutation's own guards
|
||||
// are all inside the contract's transaction, including the fence and the close
|
||||
// policy.
|
||||
func applyUpdateProxiedOne(ctx context.Context, id string, in *updateInput) (*types.Issue, *updateIDFailure, error) {
|
||||
ops, err := proxiedIssueLifecycle()
|
||||
if err != nil {
|
||||
|
|
@ -140,8 +135,7 @@ func applyUpdateProxiedOne(ctx context.Context, id string, in *updateInput) (*ty
|
|||
if err != nil {
|
||||
// Cancellation is not a verdict on this issue — SIGINT cancels bd's
|
||||
// root context, and every remaining id in the batch would fail the same
|
||||
// way. Abort the batch, as the loop this replaced did. The contract owns
|
||||
// the unit of work now, so a commit that itself failed with a context
|
||||
// way, so abort the batch. A commit that itself failed with a context
|
||||
// error is indistinguishable from a cancellation between attempts;
|
||||
// aborting is the right call for both.
|
||||
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
||||
|
|
@ -159,16 +153,12 @@ func applyUpdateProxiedOne(ctx context.Context, id string, in *updateInput) (*ty
|
|||
updated.Dependencies = nil
|
||||
if in.claim {
|
||||
// A CLAIM answers an already-published surface, and that surface is the
|
||||
// bare row. issueops.ClaimResult says so outright — labels, dependency
|
||||
// records and comments omitted, and "enriching it is a decision for the
|
||||
// next revision window, not a side effect of moving the operation onto a
|
||||
// role." Routing this path through Lifecycle hydrates labels, which is
|
||||
// exactly that side effect, so they come back off here.
|
||||
//
|
||||
// This is what keeps `bd update --claim --json` byte-identical to the v0
|
||||
// claim response, which TestProxiedServerServeClaim asserts with an EMPTY
|
||||
// allowlist: any difference at all between the two surfaces is a real
|
||||
// divergence. A plain update carries labels, as the direct route's does.
|
||||
// bare row: issueops.ClaimResult omits labels, dependency records and
|
||||
// comments, but routing this path through Lifecycle hydrates labels.
|
||||
// Stripping them keeps `bd update --claim --json` byte-identical to the
|
||||
// v0 claim response, which TestProxiedServerServeClaim asserts with an
|
||||
// EMPTY allowlist. A plain update carries labels, as the direct route
|
||||
// does.
|
||||
updated.Labels = nil
|
||||
updated.Comments = nil
|
||||
}
|
||||
|
|
@ -211,16 +201,12 @@ func proxiedUpdateTarget(ctx context.Context, id string, in *updateInput) (*type
|
|||
return nil, &updateIDFailure{ID: id, Error: err.Error()}
|
||||
}
|
||||
// bd-98s5c: an unguarded assignee update must not silently overwrite
|
||||
// another actor's live claim. Skipped under --if-assignee: that CAS names
|
||||
// the holder explicitly (park stays possible without --force). Also skipped
|
||||
// under --claim: the claim CAS is itself the anti-steal gate (a foreign live
|
||||
// claim fails it with the canonical "already claimed" copy), and an assignee
|
||||
// edit that rides a WON claim only ever touches the actor's own fresh claim.
|
||||
// The contract fences the same transfer inside the mutation with
|
||||
// ErrAlreadyClaimed; this pre-read is what keeps the advice a user reads
|
||||
// identical on both routes, exactly as update.go's own pre-read does.
|
||||
// A policy refusal: terminal per-issue failure, exit 1, never
|
||||
// GuardMismatch/13.
|
||||
// another actor's live claim. Skipped under --if-assignee, whose CAS names
|
||||
// the holder explicitly (park stays possible without --force), and under
|
||||
// --claim, whose CAS is itself the anti-steal gate. The contract fences the
|
||||
// same transfer inside the mutation with ErrAlreadyClaimed; this pre-read is
|
||||
// what keeps the advice a user reads identical on both routes. A policy
|
||||
// refusal: terminal per-issue failure, exit 1, never GuardMismatch/13.
|
||||
if newAssignee, ok := in.fields["assignee"].(string); ok && in.ifAssignee == nil && !in.claim {
|
||||
if err := validateIssueReassignable(id, current, actor, newAssignee,
|
||||
proxiedClaimPoolAliases(ctx), in.force); err != nil {
|
||||
|
|
@ -232,11 +218,10 @@ func proxiedUpdateTarget(ctx context.Context, id string, in *updateInput) (*type
|
|||
}
|
||||
|
||||
// proxiedClaimPoolAliases is uowClaimPoolAliases for a caller that owns no unit
|
||||
// of work. The mutation's transaction belongs to the contract now, so the
|
||||
// pre-read fence's claim.pools lookup opens a short-lived unit of work of its
|
||||
// own — and only when the fence is otherwise about to refuse, which is what the
|
||||
// thunk is for. A read that fails yields no aliases, the same fail-closed
|
||||
// answer its siblings give.
|
||||
// of work: the pre-read fence's claim.pools lookup opens a short-lived unit of
|
||||
// work of its own, and only when the fence is otherwise about to refuse, which
|
||||
// is what the thunk is for. A read that fails yields no aliases, the same
|
||||
// fail-closed answer its siblings give.
|
||||
func proxiedClaimPoolAliases(ctx context.Context) func() []string {
|
||||
return func() []string {
|
||||
if uowProvider == nil {
|
||||
|
|
@ -251,15 +236,13 @@ func proxiedClaimPoolAliases(ctx context.Context) func() []string {
|
|||
}
|
||||
}
|
||||
|
||||
// proxiedUpdateFailure sorts a refused update into the per-id verdicts, with
|
||||
// the same copy, the hand-rolled attempt this file used to run produced. A
|
||||
// guard refusal sets GuardMismatch so the batch exits 13 rather than 1.
|
||||
// proxiedUpdateFailure sorts a refused update into the per-id verdicts. A guard
|
||||
// refusal sets GuardMismatch so the batch exits 13 rather than 1.
|
||||
//
|
||||
// The one verdict it cannot reproduce is stage attribution: "opening unit of
|
||||
// work" and "committing" were told apart by watching the provider this path no
|
||||
// longer owns, so both now read as the generic update failure. That is the
|
||||
// price of the contract owning the transaction, and it costs a word in the
|
||||
// message, not a verdict — the id still fails, loudly and non-zero.
|
||||
// longer owns, so both now read as the generic update failure. The id still
|
||||
// fails, loudly and non-zero.
|
||||
func proxiedUpdateFailure(id string, err error) *updateIDFailure {
|
||||
switch {
|
||||
case errors.Is(err, storage.ErrNotFound):
|
||||
|
|
|
|||
|
|
@ -20,8 +20,7 @@ import (
|
|||
// The plain proxied update joined the claim on issueops.Lifecycle, so these pin
|
||||
// the same three things its sibling in update_claim_proxied_test.go pins: the
|
||||
// request this surface makes, the roles it reaches them through, and the fact
|
||||
// that it opens no unit of work of its own. The update's behaviour against real
|
||||
// Dolt is the integration suite's job.
|
||||
// that it opens no unit of work of its own.
|
||||
|
||||
func captureStderrDuring(t *testing.T, fn func()) string {
|
||||
t.Helper()
|
||||
|
|
@ -176,8 +175,8 @@ func mustProxiedUpdatePatch(t *testing.T, in *updateInput, before *types.Issue)
|
|||
// `--force`. An earlier attempt was reverted for exactly this missing mapping:
|
||||
// the proxied caller built a request that never carried the override, so a
|
||||
// shared policy check refused the close with no way for the user to say
|
||||
// otherwise. One flag, two overrides — and the assignee half only applies to an
|
||||
// assignee edit, so `--force -s closed` asks for the close-policy half alone.
|
||||
// otherwise. The assignee half only applies to an assignee edit, so
|
||||
// `--force -s closed` asks for the close-policy half alone.
|
||||
func TestProxiedUpdateCarriesForce(t *testing.T) {
|
||||
closing := map[string]any{"status": string(types.StatusClosed)}
|
||||
|
||||
|
|
@ -203,9 +202,8 @@ func TestProxiedUpdateCarriesForce(t *testing.T) {
|
|||
}
|
||||
|
||||
// TestProxiedUpdateCarriesConditionalGuards pins the bd-wsqvw guards onto the
|
||||
// request. They used to be applied by this file's own read-merge-write; the
|
||||
// contract now runs the compare-and-set inside the mutation transaction, which
|
||||
// is the only place it can be atomic with the write it gates.
|
||||
// request. The contract runs the compare-and-set inside the mutation
|
||||
// transaction, the only place it can be atomic with the write it gates.
|
||||
func TestProxiedUpdateCarriesConditionalGuards(t *testing.T) {
|
||||
holder, status := "alice", string(types.StatusInProgress)
|
||||
req := recordProxiedUpdateRequest(t, &updateInput{
|
||||
|
|
|
|||
|
|
@ -12,8 +12,7 @@ import (
|
|||
|
||||
// proxiedVersionReconciler hands back the clone-local version markers for the
|
||||
// proxied-server provider, through the provider's OWN capability accessor —
|
||||
// the same two-step proxiedCounter performs, and for the same reason: the
|
||||
// accessor is where each layer is added.
|
||||
// the same two-step proxiedCounter performs.
|
||||
func proxiedVersionReconciler() (issueops.VersionReconciler, error) {
|
||||
if uowProvider == nil {
|
||||
return nil, errors.New("proxied-server UOW provider not initialized")
|
||||
|
|
@ -28,11 +27,10 @@ func proxiedVersionReconciler() (issueops.VersionReconciler, error) {
|
|||
// reconcileVersionProxiedServer records this binary's version on the proxied
|
||||
// route, and is the twin of autoMigrateOnVersionBump's tail.
|
||||
//
|
||||
// EVERY FAILURE HERE IS SWALLOWED TO A DEBUG LINE, deliberately, and
|
||||
// issueops.VersionReconciler says that this is what its callers do. This runs
|
||||
// from PersistentPreRun before every proxied command: a workspace whose markers
|
||||
// cannot be read is a workspace whose commands must still run, and turning that
|
||||
// into an error would refuse `bd list` over a number nobody asked for.
|
||||
// EVERY FAILURE HERE IS SWALLOWED TO A DEBUG LINE, as
|
||||
// issueops.VersionReconciler says its callers do. This runs from
|
||||
// PersistentPreRun before every proxied command: a workspace whose markers
|
||||
// cannot be read is a workspace whose commands must still run.
|
||||
func reconcileVersionProxiedServer(ctx context.Context) {
|
||||
if !versionUpgradeDetected || uowProvider == nil {
|
||||
return
|
||||
|
|
|
|||
|
|
@ -233,9 +233,7 @@ func autoMigrateOnVersionBump(beadsDir string) {
|
|||
// needed. (be-1he)
|
||||
//
|
||||
// The probe asks the ROLE for the marker rather than reading the metadata
|
||||
// key itself, which is why the read shares issueops.VersionReconciler with
|
||||
// the write: this front door needs the read alone, and a store opened
|
||||
// read-only can answer it.
|
||||
// key itself: a store opened read-only can answer it.
|
||||
if roStore, roErr := dolt.NewFromConfigWithOptions(ctx, beadsDir, &dolt.Config{ReadOnly: true}); roErr == nil {
|
||||
recorded, probeErr := recordedWorkspaceVersion(ctx, roStore)
|
||||
_ = roStore.Close()
|
||||
|
|
@ -258,9 +256,8 @@ func autoMigrateOnVersionBump(beadsDir string) {
|
|||
}()
|
||||
|
||||
// Everything the version markers mean — is this an upgrade, is it a
|
||||
// downgrade to refuse, does the high-water mark move — is the role's, and
|
||||
// the same decision answers on the proxied route. This front door reads the
|
||||
// outcome and logs it.
|
||||
// downgrade to refuse, does the high-water mark move — is the role's. This
|
||||
// front door reads the outcome and logs it.
|
||||
//
|
||||
// No Dolt commit is needed after it: local_metadata is dolt-ignored and
|
||||
// persists in the working set for the lifetime of the server session.
|
||||
|
|
@ -286,12 +283,9 @@ func autoMigrateOnVersionBump(beadsDir string) {
|
|||
}
|
||||
|
||||
// recordedWorkspaceVersion reads the marker through the role's accessor on a
|
||||
// store the caller owns and closes.
|
||||
//
|
||||
// It takes the storage interface rather than the concrete store so the probe
|
||||
// above cannot drift into using a seam the role hides; it is a helper only
|
||||
// because the probe's store is opened, read and closed in one statement's
|
||||
// worth of scope.
|
||||
// store the caller owns and closes. It takes the storage interface rather than
|
||||
// the concrete store so the probe above cannot drift into using a seam the role
|
||||
// hides.
|
||||
func recordedWorkspaceVersion(ctx context.Context, store storage.Storage) (string, error) {
|
||||
reconciler, err := store.VersionReconciler()
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -20,17 +20,15 @@ const (
|
|||
// have no size in them.
|
||||
maxBatchCreateItems = 100
|
||||
// maxBatchCreateBodyBytes bounds the request body. A hundred items each
|
||||
// carrying a description, a design and acceptance criteria is the shape
|
||||
// this has to admit, so it is generous where the claim's is not; it exists
|
||||
// to refuse the absurd before any of it is parsed.
|
||||
// carrying a description, a design and acceptance criteria is the shape this
|
||||
// has to admit, so it refuses the absurd before any of it is parsed.
|
||||
maxBatchCreateBodyBytes = 4 << 20
|
||||
)
|
||||
|
||||
// batchCreateMembers is the document's member list at each level. The schemas
|
||||
// are additionalProperties: false, so anything else is refused BY NAME — which
|
||||
// is the whole reason these are decoded as raw members first: encoding/json's
|
||||
// DisallowUnknownFields reports the offender only inside an error string, and
|
||||
// this surface exists to let clients stop parsing prose.
|
||||
// are additionalProperties: false, so anything else is refused BY NAME, which is
|
||||
// why these are decoded as raw members first: encoding/json's
|
||||
// DisallowUnknownFields reports the offender only inside an error string.
|
||||
var (
|
||||
batchCreateRequestMembers = []string{"actor", "items"}
|
||||
batchCreateItemMembers = []string{"title", "description", "design", "acceptance_criteria", "priority", "issue_type", "assignee", "labels", "dependencies"}
|
||||
|
|
@ -39,12 +37,10 @@ var (
|
|||
|
||||
// handleBatchCreate creates every issue in the request body, or none of them.
|
||||
//
|
||||
// WHAT IS NOT HERE is the point. Which rows land together, what an edge onto an
|
||||
// absent target does, the create-only guard, the workspace's type and status
|
||||
// vocabulary, the id assignment, the wisp routing, the transaction retry and the
|
||||
// history entry all belong to issueops.BatchCreator, reached through the
|
||||
// provider's own accessor. This function decodes a body, refuses the shapes the
|
||||
// document refuses, and marshals what came back.
|
||||
// The create-only guard, the vocabulary, the id assignment, the wisp routing,
|
||||
// the retry and the history entry all belong to issueops.BatchCreator. This
|
||||
// function decodes a body, refuses the shapes the document refuses, and
|
||||
// marshals what came back.
|
||||
//
|
||||
// It shares the claim's posture exactly: the actor is caller-ASSERTED
|
||||
// provenance and not authenticated identity, hooks do not fire, and the
|
||||
|
|
@ -83,9 +79,9 @@ func (s *Server) handleBatchCreate(w http.ResponseWriter, r *http.Request) {
|
|||
// request may proceed.
|
||||
//
|
||||
// Every refusal here happens BEFORE any database work, which is what lets the
|
||||
// 400s be specific: they reflect the caller's own input back. The role's own
|
||||
// refusals cannot be that specific without quoting a storage error into a
|
||||
// response, so failBatchCreate answers those in the server's own words.
|
||||
// 400s reflect the caller's own input back. The role's own refusals cannot be
|
||||
// that specific without quoting a storage error into a response, so
|
||||
// failBatchCreate answers those in the server's own words.
|
||||
func (s *Server) batchCreateRequest(w http.ResponseWriter, r *http.Request) (issueops.CreateBatchRequest, bool) {
|
||||
members, res := decodeJSONObject(w, r, maxBatchCreateBodyBytes)
|
||||
if res != nil {
|
||||
|
|
@ -108,10 +104,9 @@ func (s *Server) batchCreateRequest(w http.ResponseWriter, r *http.Request) (iss
|
|||
return issueops.CreateBatchRequest{Actor: actor, Items: items}, true
|
||||
}
|
||||
|
||||
// batchCreateActor validates `actor` under the claim's rules, which the
|
||||
// document says are the same rules and which are shared here rather than
|
||||
// restated: the value lands in the same columns and the same storage commit
|
||||
// message, so a newline forges the same audit-trail lines.
|
||||
// batchCreateActor validates `actor` under the claim's rules, shared rather
|
||||
// than restated: the value lands in the same columns and the same storage
|
||||
// commit message, so a newline forges the same audit-trail lines.
|
||||
func (s *Server) batchCreateActor(w http.ResponseWriter, r *http.Request, members map[string]json.RawMessage) (string, bool) {
|
||||
raw, ok := members[claimActorMember]
|
||||
if !ok {
|
||||
|
|
@ -176,12 +171,10 @@ func (s *Server) batchCreateItems(w http.ResponseWriter, r *http.Request, member
|
|||
return items, true
|
||||
}
|
||||
|
||||
// batchCreateItem projects one decoded item onto the role's item, or reports
|
||||
// the refusal it earned.
|
||||
//
|
||||
// It decodes into the GENERATED struct, which is what makes a member's type the
|
||||
// document's type: `priority: "high"` is refused here rather than reaching a
|
||||
// role that would have to guess what the caller meant.
|
||||
// batchCreateItem projects one decoded item onto the role's item, or reports the
|
||||
// refusal it earned. It decodes into the GENERATED struct, which is what makes a
|
||||
// member's type the document's type: `priority: "high"` is refused here rather
|
||||
// than reaching a role that would have to guess what the caller meant.
|
||||
func batchCreateItem(index int, raw map[string]json.RawMessage) (issueops.BatchCreateItem, *Result) {
|
||||
refuse := func(member, detail string) *Result {
|
||||
res := InvalidArgument(batchCreateItemParam(index, member), ReasonInvalidValue, detail)
|
||||
|
|
@ -202,14 +195,11 @@ func batchCreateItem(index int, raw map[string]json.RawMessage) (issueops.BatchC
|
|||
return issueops.BatchCreateItem{}, refuse("title",
|
||||
fmt.Sprintf("`title` is longer than the %d characters storage holds", types.MaxFieldLen))
|
||||
}
|
||||
// The role validates the type against the workspace's configured
|
||||
// vocabulary, which this server cannot read without a transaction. What is
|
||||
// checked here is only what the schema declares: a value at all, and one
|
||||
// short enough for the column.
|
||||
//
|
||||
// A SLICE and not a map, so that an item breaking both rules always names
|
||||
// the same offender: `param` is what a client dispatches on, and it must
|
||||
// not depend on map order.
|
||||
// The role validates the type against the workspace's configured vocabulary,
|
||||
// which this server cannot read without a transaction; what is checked here
|
||||
// is only what the schema declares. A SLICE and not a map, so that an item
|
||||
// breaking both rules always names the same offender: `param` is what a
|
||||
// client dispatches on, and it must not depend on map order.
|
||||
for _, bounded := range []struct {
|
||||
member string
|
||||
value *string
|
||||
|
|
@ -260,9 +250,9 @@ func batchCreateItem(index int, raw map[string]json.RawMessage) (issueops.BatchC
|
|||
"`target_id` is required and must be at most "+fmt.Sprint(types.MaxFieldLen)+" characters")
|
||||
}
|
||||
// A value at all, and one the column holds — never membership of a
|
||||
// known-types list. The edge vocabulary is OPEN, exactly as
|
||||
// EdgeReadRequest.Types says it is, so a workspace's own type passes
|
||||
// here and only an unstorable one is refused.
|
||||
// known-types list. The edge vocabulary is OPEN, as EdgeReadRequest.Types
|
||||
// says, so a workspace's own type passes and only an unstorable one is
|
||||
// refused.
|
||||
if !types.DependencyType(dependency.Type).IsValid() {
|
||||
return issueops.BatchCreateItem{}, refuse("dependencies.type",
|
||||
fmt.Sprintf("`type` must be 1 to %d characters", types.MaxDependencyTypeLen))
|
||||
|
|
@ -277,9 +267,9 @@ func batchCreateItem(index int, raw map[string]json.RawMessage) (issueops.BatchC
|
|||
|
||||
// rawDependencyMembers decodes an item's edges as raw members, so an unknown
|
||||
// member INSIDE an edge is refused by name like every other one. It answers nil
|
||||
// — which carries no unknown member — when the shape is not the one the
|
||||
// generated decode already accepted, because a disagreement between the two
|
||||
// decodes is not a client-attributable refusal.
|
||||
// — carrying no unknown member — when the shape is not the one the generated
|
||||
// decode accepted, because a disagreement between the two decodes is not a
|
||||
// client-attributable refusal.
|
||||
func rawDependencyMembers(item map[string]json.RawMessage) []map[string]json.RawMessage {
|
||||
raw, ok := item["dependencies"]
|
||||
if !ok {
|
||||
|
|
@ -301,8 +291,7 @@ func rawEdgeAt(edges []map[string]json.RawMessage, j int) map[string]json.RawMes
|
|||
}
|
||||
|
||||
// batchCreateItemParam spells the `param` member for a refusal inside `items`,
|
||||
// so a client dispatching on it learns WHICH item and WHICH member without
|
||||
// reading the detail.
|
||||
// so a client dispatching on it learns WHICH item and WHICH member.
|
||||
func batchCreateItemParam(index int, member string) string {
|
||||
param := fmt.Sprintf("items[%d]", index)
|
||||
if member == "" {
|
||||
|
|
@ -322,25 +311,22 @@ func (s *Server) failUnknownMember(w http.ResponseWriter, r *http.Request, offen
|
|||
|
||||
// failBatchCreate answers a failed batch.
|
||||
//
|
||||
// The role's ErrValidation is answered HERE rather than in ClassifyError, and
|
||||
// the reason is the same one that makes this operation's 400 worth having: the
|
||||
// The role's ErrValidation is answered HERE rather than in ClassifyError: the
|
||||
// role wraps its dangling-edge refusal in BOTH ErrValidation and ErrNotFound,
|
||||
// so the shared classifier — which reaches ErrNotFound first — would answer 404
|
||||
// for a request that addressed no resource at all.
|
||||
//
|
||||
// NEITHER BRANCH QUOTES THE ROLE'S MESSAGE. A refused edge arrives as a driver
|
||||
// error naming tables and constraints, and 4xx details on this surface reflect
|
||||
// the caller's own input back rather than server internals. The two sentences
|
||||
// below say exactly what the client can act on, and the real error goes to the
|
||||
// log with the request id, which is where the rest of it belongs.
|
||||
// the caller's own input back rather than server internals. The real error goes
|
||||
// to the log with the request id.
|
||||
func (s *Server) failBatchCreate(w http.ResponseWriter, r *http.Request, err error) {
|
||||
if !errors.Is(err, storage.ErrValidation) {
|
||||
s.failErr(w, r, err)
|
||||
return
|
||||
}
|
||||
// The 4xx path does not log by default, so this is the one place the real
|
||||
// refusal is recorded: without it the operator has a request id and a
|
||||
// sentence that deliberately says less than the error did.
|
||||
// refusal is recorded for the operator.
|
||||
s.event("request_refused", "request_id", requestInfo(r.Context()).id, "error", err.Error())
|
||||
if errors.Is(err, storage.ErrNotFound) {
|
||||
s.fail(w, r, InvalidArgument("items", ReasonInvalidValue,
|
||||
|
|
|
|||
|
|
@ -14,9 +14,8 @@ import (
|
|||
|
||||
// These cover the transport half of POST /v0/beads/issues:batchCreate — the
|
||||
// body shape, the refusals this operation owns, and how a role refusal is named
|
||||
// on the wire. Everything below the wire — what lands together, what an edge
|
||||
// onto an absent target does, the id assignment — is the role's, and is pinned
|
||||
// by backend/conformance/batch_creator_contract.go at all three backends.
|
||||
// on the wire. Everything below the wire is the role's, pinned by
|
||||
// backend/conformance/batch_creator_contract.go at all three backends.
|
||||
|
||||
const batchCreatePath = "/v0/beads/issues:batchCreate"
|
||||
|
||||
|
|
@ -87,8 +86,7 @@ func TestBatchCreatePassesTheRequestToTheRoleAndAnswersWithWhatItCreated(t *test
|
|||
t.Errorf("item 1 = %+v, want the wire's description and no priority", *got.Items[1].Issue)
|
||||
}
|
||||
// No provenance: the file name a CLI batch spells has no analogue here, so
|
||||
// the entry reads as the implementation's default rather than as a lie
|
||||
// about where the request came from.
|
||||
// the entry reads as the implementation's default rather than as a lie.
|
||||
if got.Provenance != "" {
|
||||
t.Errorf("provenance = %q, want empty: this surface names no source file", got.Provenance)
|
||||
}
|
||||
|
|
@ -170,14 +168,12 @@ func TestBatchCreateRefusesAnOversizeBatch(t *testing.T) {
|
|||
}
|
||||
|
||||
// TestBatchCreateNamesARoleRefusalInTheServersOwnWords is the case
|
||||
// failBatchCreate exists for.
|
||||
//
|
||||
// The absent-target refusal arrives as ErrValidation WRAPPING ErrNotFound, and
|
||||
// the shared classifier reaches ErrNotFound first — so without the operation's
|
||||
// own failure path this 400 would be a 404 for a request that addressed no
|
||||
// resource at all. The detail is the server's own sentence: the role's carries
|
||||
// a driver error naming tables and constraints, and 4xx details here reflect
|
||||
// the caller's input rather than server internals.
|
||||
// failBatchCreate exists for. The absent-target refusal arrives as
|
||||
// ErrValidation WRAPPING ErrNotFound, and the shared classifier reaches
|
||||
// ErrNotFound first — so without the operation's own failure path this 400
|
||||
// would be a 404 for a request that addressed no resource at all. The detail
|
||||
// is the server's own sentence: the role's carries a driver error naming
|
||||
// tables and constraints.
|
||||
func TestBatchCreateNamesARoleRefusalInTheServersOwnWords(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
|
|
@ -234,12 +230,9 @@ func TestBatchCreateReportsANonValidationRoleFailureAsTheGenericFailure(t *testi
|
|||
}
|
||||
}
|
||||
|
||||
// TestBatchCreateRefusesACreatorThatAnswersWithNothing pins checkedBatchCreator.
|
||||
//
|
||||
// The response body carries issue VALUES where the role answers with pointers,
|
||||
// so a nil entry is a nil dereference in the handler. It is the generic 500
|
||||
// with the fault in the log — not a 404, because nothing here knows an issue is
|
||||
// missing — and above all not a panic.
|
||||
// TestBatchCreateRefusesACreatorThatAnswersWithNothing pins
|
||||
// checkedBatchCreator: a nil entry would be a nil dereference in the handler,
|
||||
// so it is the generic 500 and above all not a panic.
|
||||
func TestBatchCreateRefusesACreatorThatAnswersWithNothing(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
|
|
@ -263,9 +256,7 @@ func TestBatchCreateRefusesACreatorThatAnswersWithNothing(t *testing.T) {
|
|||
// TestBatchCreateRefusesANonJSONContentType pins the CSRF control this
|
||||
// operation inherits from the claim: a JSON content type is not CORS-"simple",
|
||||
// so a cross-origin write always triggers a preflight this server never
|
||||
// approves. It is the second write on this surface and the first one that
|
||||
// creates rows, so accepting text/plain here would be strictly worse than
|
||||
// accepting it there.
|
||||
// approves.
|
||||
func TestBatchCreateRefusesANonJSONContentType(t *testing.T) {
|
||||
creator := &roleBatchCreator{}
|
||||
ts := newBatchCreateServer(t, creator)
|
||||
|
|
|
|||
|
|
@ -31,10 +31,9 @@ func (s *Server) handleBlockingAnnotations(w http.ResponseWriter, r *http.Reques
|
|||
return
|
||||
}
|
||||
// Both bounds are checked here rather than left to the role, for the reason
|
||||
// handleListDependencies gives: they are this operation's own limits on one
|
||||
// shared process, not statements about what a blocking annotation means,
|
||||
// and the role answers an empty request with an empty result rather than a
|
||||
// refusal.
|
||||
// handleListDependencies gives: they are this operation's own limits, not
|
||||
// statements about what a blocking annotation means, and the role answers an
|
||||
// empty request with an empty result rather than a refusal.
|
||||
if len(ids) == 0 {
|
||||
requestInfo(r.Context()).refuse("issue_id")
|
||||
s.fail(w, r, InvalidArgument("issue_id", ReasonInvalidValue, "name at least one issue_id"))
|
||||
|
|
@ -63,11 +62,8 @@ func (s *Server) handleBlockingAnnotations(w http.ResponseWriter, r *http.Reques
|
|||
// failBlockingErr answers a failed blocking annotation. The role's one
|
||||
// request-validation refusal — an empty id — is the caller's own input and
|
||||
// reaches the client as the 400 it is; everything else keeps going through the
|
||||
// one mapping in problem.go.
|
||||
//
|
||||
// It classifies on the SENTINEL rather than on prose, as failEdgeReadErr does,
|
||||
// and it needs no parameter guess: `issue_id` is the only parameter this
|
||||
// operation has.
|
||||
// one mapping in problem.go. It classifies on the SENTINEL rather than on
|
||||
// prose, as failEdgeReadErr does.
|
||||
func (s *Server) failBlockingErr(w http.ResponseWriter, r *http.Request, err error) {
|
||||
if !errors.Is(err, issueops.ErrValidation) {
|
||||
s.failErr(w, r, err)
|
||||
|
|
@ -83,9 +79,8 @@ func (s *Server) failBlockingErr(w http.ResponseWriter, r *http.Request, err err
|
|||
// one.
|
||||
//
|
||||
// It exists for the one thing that is not free: the document says `items` is an
|
||||
// empty array and never null, and the role's slice is already empty rather than
|
||||
// nil for a request that named nothing. Making the guarantee here as well means
|
||||
// the wire promise does not depend on the role keeping its own.
|
||||
// empty array and never null, so the wire promise does not depend on the role
|
||||
// keeping its own.
|
||||
func wireBlocking(result issueops.BlockingResult) apigen.BlockingAnnotations {
|
||||
if result.Items == nil {
|
||||
return apigen.BlockingAnnotations{Items: []apigen.IssueBlocking{}}
|
||||
|
|
|
|||
|
|
@ -23,9 +23,9 @@ func newBlockingServer(t *testing.T, annotator *roleBlockingAnnotator) *testServ
|
|||
}
|
||||
|
||||
// TestBlockingAnnotationsPassTheIDsThroughUnaltered pins the half of this
|
||||
// handler that is easiest to get wrong by helping: the ids go to the role in the
|
||||
// order they arrived, repeats and all, because collapsing them is the ROLE's
|
||||
// promise and a handler that did it first would make the two front doors
|
||||
// handler that is easiest to get wrong by helping: the ids go to the role in
|
||||
// the order they arrived, repeats and all. Collapsing them is the ROLE's
|
||||
// promise, and a handler that did it first would make the two front doors
|
||||
// collapse in different places.
|
||||
func TestBlockingAnnotationsPassTheIDsThroughUnaltered(t *testing.T) {
|
||||
annotator := &roleBlockingAnnotator{}
|
||||
|
|
@ -137,11 +137,10 @@ func TestBlockingAnnotationsBoundTheQuestion(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestBlockingAnnotationsRefuseAnUnknownParameter keeps this operation under the
|
||||
// document's uniform rule. It matters more here than on most routes: this
|
||||
// operation publishes exactly ONE parameter, so a client that guessed at a
|
||||
// `type` or `direction` filter would otherwise receive the unfiltered
|
||||
// decoration and believe it narrowed.
|
||||
// TestBlockingAnnotationsRefuseAnUnknownParameter keeps this operation under
|
||||
// the document's uniform rule. It publishes exactly ONE parameter, so a client
|
||||
// that guessed at a `type` or `direction` filter would otherwise receive the
|
||||
// unfiltered decoration and believe it narrowed.
|
||||
func TestBlockingAnnotationsRefuseAnUnknownParameter(t *testing.T) {
|
||||
ts := newBlockingServer(t, &roleBlockingAnnotator{})
|
||||
|
||||
|
|
|
|||
|
|
@ -413,79 +413,62 @@ func (p timedProvider) WorkspaceConfig() (issueops.WorkspaceConfig, error) {
|
|||
}
|
||||
|
||||
// StatsReporter builds the summary role OVER THIS WRAPPER, for the same reason
|
||||
// as every accessor above it: a reporter bound to the wrapped provider would open
|
||||
// its units of work outside this request's measurement and the summary route
|
||||
// would log uow_ms=0.000 forever.
|
||||
// and with the same hazard as IssueReader.
|
||||
func (p timedProvider) StatsReporter() (issueops.StatsReporter, error) {
|
||||
return uow.NewStatsReporter(p)
|
||||
}
|
||||
|
||||
// CycleDetector builds the detector OVER THIS WRAPPER, for the same reason and
|
||||
// with the same hazard as the two above: the sweep opens its own read-only unit
|
||||
// of work, and a detector bound to the untimed provider would report
|
||||
// uow_ms=0.000 for the one round trip the request makes.
|
||||
// with the same hazard as IssueReader.
|
||||
func (p timedProvider) CycleDetector() (issueops.CycleDetector, error) {
|
||||
return uow.NewCycleDetector(p)
|
||||
}
|
||||
|
||||
// EdgeReader builds the stored-edge reader OVER THIS WRAPPER, for the same
|
||||
// reason and with the same hazard as the two above: the role opens one unit of
|
||||
// work per call, and it must go through NewUOW below or the dependencies route
|
||||
// reports uow_ms=0.000.
|
||||
// reason and with the same hazard as IssueReader.
|
||||
func (p timedProvider) EdgeReader() (issueops.EdgeReader, error) {
|
||||
return uow.NewEdgeReader(p)
|
||||
}
|
||||
|
||||
// BlockingAnnotator builds the blocking-decoration role OVER THIS WRAPPER, for
|
||||
// the same reason as the ones above: the annotation opens a unit of work of its
|
||||
// own, and it must land in this request's uow_ms rather than in nobody's.
|
||||
// the same reason and with the same hazard as IssueReader.
|
||||
func (p timedProvider) BlockingAnnotator() (issueops.BlockingAnnotator, error) {
|
||||
return uow.NewBlockingAnnotator(p)
|
||||
}
|
||||
|
||||
// TreeWalker builds the dependency-tree walker OVER THIS WRAPPER, for the same
|
||||
// reason and with the same hazard as the accessors above: the walk opens one
|
||||
// read-only unit of work per call, and it must go through NewUOW below or the
|
||||
// tree route reports uow_ms=0.000.
|
||||
// reason and with the same hazard as IssueReader.
|
||||
func (p timedProvider) TreeWalker() (issueops.TreeWalker, error) {
|
||||
return uow.NewTreeWalker(p)
|
||||
}
|
||||
|
||||
// ReadyCounter builds the ready counter OVER THIS WRAPPER, for the same reason
|
||||
// as the two above: the count opens a unit of work of its own, and it must land
|
||||
// in this request's uow_ms rather than in nobody's.
|
||||
// and with the same hazard as IssueReader.
|
||||
func (p timedProvider) ReadyCounter() (issueops.ReadyCounter, error) {
|
||||
return uow.NewReadyCounter(p)
|
||||
}
|
||||
|
||||
// Querier builds the boolean-query role OVER THIS WRAPPER, for the same reason
|
||||
// as every accessor above: the query opens a read-only unit of work of its own,
|
||||
// and it must land in this request's uow_ms rather than in nobody's.
|
||||
// and with the same hazard as IssueReader.
|
||||
func (p timedProvider) Querier() (issueops.Querier, error) {
|
||||
return uow.NewQuerier(p)
|
||||
}
|
||||
|
||||
// Sweeper builds the sweeper OVER THIS WRAPPER, for the same reason as the two
|
||||
// above and with the sharpest version of the hazard: the sweep is the longest
|
||||
// unit of work on this surface, so a sweeper bound to the untimed provider
|
||||
// would report uow_ms=0.000 for exactly the request whose duration an operator
|
||||
// most wants in the log.
|
||||
// Sweeper builds the sweeper OVER THIS WRAPPER, for the same reason and with
|
||||
// the same hazard as IssueReader.
|
||||
func (p timedProvider) Sweeper() (issueops.Sweeper, error) {
|
||||
return uow.NewSweeper(p)
|
||||
}
|
||||
|
||||
// Deleter builds the deleter OVER THIS WRAPPER, for the same reason: it opens
|
||||
// the request's unit of work, so a deleter bound to the untimed provider would
|
||||
// leave the longest transaction on this surface out of uow_ms.
|
||||
// Deleter builds the deleter OVER THIS WRAPPER, for the same reason and with
|
||||
// the same hazard as IssueReader.
|
||||
func (p timedProvider) Deleter() (issueops.Deleter, error) {
|
||||
return uow.NewDeleter(p)
|
||||
}
|
||||
|
||||
// BatchCreator builds the batch creator OVER THIS WRAPPER, for the same reason
|
||||
// as the roles above and with more at stake than any of them: this is the one
|
||||
// role here that opens a WRITE unit of work per call, so a creator bound to the
|
||||
// untimed provider would report uow_ms=0.000 for the slowest request this
|
||||
// server serves.
|
||||
// as the roles above. It is the one role here that opens a WRITE unit of work
|
||||
// per call.
|
||||
func (p timedProvider) BatchCreator() (issueops.BatchCreator, error) {
|
||||
return uow.NewBatchCreator(p)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,13 +9,12 @@ import (
|
|||
|
||||
// handleDependencyCycles answers GET /v0/beads/dependencies/cycles.
|
||||
//
|
||||
// WHAT IS NOT HERE IS THE POINT, as it is for the read operations next door. No
|
||||
// graph is built, no table is chosen, no path is rotated and no report is
|
||||
// sorted: the canonicalization the document promises is inside
|
||||
// issueops.CycleDetector's implementation, which `bd dep cycles` reaches
|
||||
// through the same accessor. A handler that ordered the answer for itself would
|
||||
// be a second definition of "canonical" and the two surfaces would drift the
|
||||
// first time either was edited.
|
||||
// WHAT IS NOT HERE, as for the read operations next door: no graph is built, no
|
||||
// table is chosen, no path is rotated and no report is sorted. The
|
||||
// canonicalization the document promises is inside issueops.CycleDetector's
|
||||
// implementation, which `bd dep cycles` reaches through the same accessor; a
|
||||
// handler that ordered the answer for itself would be a second definition of
|
||||
// "canonical".
|
||||
//
|
||||
// The element type is an ALIAS of issueops.Cycle — the same struct the CLI's
|
||||
// --json marshals — so there is no second wire struct here and there must never
|
||||
|
|
@ -47,13 +46,11 @@ func (s *Server) handleDependencyCycles(w http.ResponseWriter, r *http.Request)
|
|||
}
|
||||
|
||||
// wireCycles projects the role's report onto the generated envelope's element
|
||||
// type, which is an alias of the role's own struct — so this is a slice copy
|
||||
// and nothing else.
|
||||
// type, which is an alias of the role's own struct.
|
||||
//
|
||||
// It exists for the one thing that is not free: the document says `items` is an
|
||||
// empty array and never null, and the role's slice is already empty rather than
|
||||
// nil for an acyclic workspace. Making the guarantee here as well means the
|
||||
// wire promise does not depend on the role keeping its own.
|
||||
// empty array and never null. Making the guarantee here as well means the wire
|
||||
// promise does not depend on the role keeping its own.
|
||||
func wireCycles(cycles []issueops.Cycle) []apigen.Cycle {
|
||||
if cycles == nil {
|
||||
return []apigen.Cycle{}
|
||||
|
|
|
|||
|
|
@ -103,8 +103,7 @@ func TestCyclesOmitsAnUndescribableMemberIssueAndMarksThePath(t *testing.T) {
|
|||
}
|
||||
|
||||
// TestCyclesAnswersAnEmptyArrayForACleanWorkspace pins the `never null` half of
|
||||
// the envelope. A client that had to tell null from empty to learn a workspace
|
||||
// is clean would have to branch on the difference.
|
||||
// the envelope.
|
||||
func TestCyclesAnswersAnEmptyArrayForACleanWorkspace(t *testing.T) {
|
||||
ts := cyclesServer(t, &roleCycleDetector{})
|
||||
|
||||
|
|
|
|||
|
|
@ -12,8 +12,7 @@ import (
|
|||
)
|
||||
|
||||
// The request body's member vocabulary. The schema is
|
||||
// additionalProperties: false, so anything else is refused BY NAME — the same
|
||||
// posture the sweep takes, and for the same reason sharpened: on this
|
||||
// additionalProperties: false, so anything else is refused BY NAME: on this
|
||||
// operation an ignored member is the difference between orphaning a dependent
|
||||
// and deleting it.
|
||||
const (
|
||||
|
|
@ -25,8 +24,8 @@ const (
|
|||
)
|
||||
|
||||
// deleteMembers is the whole vocabulary, in one place, so the unknown-member
|
||||
// refusal and the decoding below cannot come to disagree about what this
|
||||
// operation accepts.
|
||||
// refusal and the decoding below cannot disagree about what this operation
|
||||
// accepts.
|
||||
var deleteMembers = []string{
|
||||
deleteIDsMember,
|
||||
deleteActorMember,
|
||||
|
|
@ -35,10 +34,9 @@ var deleteMembers = []string{
|
|||
deleteDryRunMember,
|
||||
}
|
||||
|
||||
// maxDeleteIDs bounds the `ids` array, matching the document's maxItems. It is
|
||||
// a bound on the REQUEST rather than on what a cascade expands to: the whole
|
||||
// delete is one transaction, so the practical ceiling is the backend's write
|
||||
// timeout and no number here can promise it.
|
||||
// maxDeleteIDs bounds the `ids` array, matching the document's maxItems. It
|
||||
// bounds the REQUEST rather than what a cascade expands to: the whole delete is
|
||||
// one transaction, so the practical ceiling is the backend's write timeout.
|
||||
const maxDeleteIDs = 1000
|
||||
|
||||
// handleDelete answers POST /v0/beads/issues:delete — the second DESTRUCTIVE
|
||||
|
|
@ -48,12 +46,8 @@ const maxDeleteIDs = 1000
|
|||
// not resolve ids, does not expand a cascade, does not decide which rows are
|
||||
// dependents, and — the one that matters — does not implement the guard that
|
||||
// refuses an unforced delete over an outside dependent. All of that is
|
||||
// issueops.Deleter, the same library surface `bd delete` calls, so this
|
||||
// endpoint cannot orphan a workspace's graph by omission even if a future edit
|
||||
// here forgot the rule existed.
|
||||
//
|
||||
// Everything above the role here is argument validation: the media type, the
|
||||
// body shape, and the five members the document publishes.
|
||||
// issueops.Deleter, the same library surface `bd delete` calls. Everything
|
||||
// above the role here is argument validation.
|
||||
//
|
||||
// NO ACTOR IS INFERRED, for the reason the claim gives. It is OPTIONAL here as
|
||||
// it is on the sweep — a deleted bead leaves no row to attribute the deletion
|
||||
|
|
@ -111,9 +105,9 @@ func (s *Server) deleteRequest(w http.ResponseWriter, r *http.Request) (issueops
|
|||
}
|
||||
|
||||
// cascade, force and dry_run all default to their ZERO values here, unlike
|
||||
// the sweep's protect_referenced. That is not an inconsistency: false is
|
||||
// already the guarded answer for all three, so an omitted member cannot buy
|
||||
// weaker protection than the operator typing `bd delete` gets.
|
||||
// the sweep's protect_referenced: false is already the guarded answer for
|
||||
// all three, so an omitted member cannot buy weaker protection than the
|
||||
// operator typing `bd delete` gets.
|
||||
var request issueops.DeleteRequest
|
||||
|
||||
raw, ok := members[deleteIDsMember]
|
||||
|
|
@ -130,8 +124,7 @@ func (s *Server) deleteRequest(w http.ResponseWriter, r *http.Request) (issueops
|
|||
}
|
||||
if len(*ids) == 0 {
|
||||
// The ROLE refuses this too. It is refused here as well so the client
|
||||
// gets the member name, and because an empty array is the shape most
|
||||
// likely to arrive from a caller's own broken construction.
|
||||
// gets the member name.
|
||||
s.fail(w, r, InvalidArgument(deleteIDsMember, ReasonInvalidValue,
|
||||
"`"+deleteIDsMember+"` must name at least one bead"))
|
||||
return issueops.DeleteRequest{}, false
|
||||
|
|
@ -150,8 +143,7 @@ func (s *Server) deleteRequest(w http.ResponseWriter, r *http.Request) (issueops
|
|||
"`"+deleteActorMember+"` must be a string"))
|
||||
return issueops.DeleteRequest{}, false
|
||||
}
|
||||
// The claim's rules, unchanged, which is what makes the two operations
|
||||
// one vocabulary for a client.
|
||||
// The claim's rules, unchanged.
|
||||
trimmed, res := validateActor(*value)
|
||||
if res != nil {
|
||||
s.fail(w, r, *res)
|
||||
|
|
@ -196,23 +188,18 @@ func deleteMemberList() string {
|
|||
//
|
||||
// It draws the same ErrValidation-is-a-400 line the sweep draws, and adds ONE
|
||||
// more: the role's dependents refusal. That one is a 400 rather than a 409
|
||||
// because the fix is to change the REQUEST — send `cascade` or `force` — and
|
||||
// the detail carries the role's own sentence, which names the blocked id and
|
||||
// says exactly that.
|
||||
// because the fix is to change the REQUEST — send `cascade` or `force`.
|
||||
//
|
||||
// THE ABSENT-ID REFUSAL NEEDS NO BRANCH AT ALL, and does not get one: the
|
||||
// role's *NotFoundError wraps issueops.ErrNotFound, which ClassifyError already
|
||||
// maps to a 404 carrying NotFound()'s FIXED detail. The role's own message
|
||||
// names every id that did not resolve and the wire deliberately does not repeat
|
||||
// it — NotFound's doc says why, and it is a posture about this whole surface
|
||||
// rather than about this operation. `bd delete` still names them, because it is
|
||||
// it — NotFound's doc says why. `bd delete` still names them, because it is
|
||||
// talking to the person who typed them.
|
||||
func (s *Server) failDeleteErr(w http.ResponseWriter, r *http.Request, err error) {
|
||||
if errors.Is(err, issueops.ErrValidation) || errors.Is(err, issueops.ErrDependentsOutsideRequest) {
|
||||
// No `param`: neither refusal is about one member of the request. The
|
||||
// dependents one is about the absence of a CHOICE between two of them,
|
||||
// and the document's `param` is documented absent on exactly that kind
|
||||
// of case.
|
||||
// dependents one is about the absence of a CHOICE between two of them.
|
||||
s.fail(w, r, InvalidArgument("", ReasonInvalidValue, err.Error()))
|
||||
return
|
||||
}
|
||||
|
|
@ -221,9 +208,8 @@ func (s *Server) failDeleteErr(w http.ResponseWriter, r *http.Request, err error
|
|||
|
||||
// deleteResponse projects the role's result onto the wire type. It is a field
|
||||
// list rather than an alias for the reason sweepResponse is: DeleteResult is
|
||||
// deliberately not x-go-type-pinned, so the projection is where the two shapes
|
||||
// are held together and TestDeleteResponseCarriesEveryRoleField is what keeps a
|
||||
// new result field from being dropped here in silence.
|
||||
// deliberately not x-go-type-pinned, and TestDeleteResponseCarriesEveryRoleField
|
||||
// is what keeps a new result field from being dropped here in silence.
|
||||
func deleteResponse(result issueops.DeleteResult) apigen.DeleteIssuesResult {
|
||||
body := apigen.DeleteIssuesResult{
|
||||
DryRun: result.DryRun,
|
||||
|
|
|
|||
|
|
@ -83,12 +83,9 @@ func TestDeleteForwardsEveryDocumentedMember(t *testing.T) {
|
|||
// TestDeleteDefaultsTheOptionalMembers: a body carrying only `ids` reaches the
|
||||
// role as a GUARDED, non-cascading, real delete.
|
||||
//
|
||||
// All three flags default to their zero values, which is the one place this
|
||||
// operation's defaults differ in SPIRIT from the sweep's: there, false was the
|
||||
// unsafe answer for protect_referenced and the handler had to override it; here
|
||||
// false is the guarded answer for all three, so the zero value is the
|
||||
// protection and a handler that "helpfully" defaulted force on would be the
|
||||
// bug.
|
||||
// All three flags default to their zero values, and here — unlike the sweep's
|
||||
// protect_referenced — false is the GUARDED answer for all three. The zero value
|
||||
// is the protection, so a handler that "helpfully" defaulted force on is the bug.
|
||||
func TestDeleteDefaultsTheOptionalMembers(t *testing.T) {
|
||||
deleter := &roleDeleter{}
|
||||
ts := newTestServer(t, rolesConfig(Config{Deleter: deleter}))
|
||||
|
|
@ -106,10 +103,9 @@ func TestDeleteDefaultsTheOptionalMembers(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestDeletePublishesTheWholeResult drives every member of the response body,
|
||||
// which is the half deleteResponse owns: the schema is not x-go-type-pinned, so
|
||||
// a field added to the role's result and forgotten in the projection would be
|
||||
// silently absent from the wire.
|
||||
// TestDeletePublishesTheWholeResult drives every member of the response body:
|
||||
// the schema is not x-go-type-pinned, so a field added to the role's result and
|
||||
// forgotten in the projection would be silently absent from the wire.
|
||||
func TestDeletePublishesTheWholeResult(t *testing.T) {
|
||||
deleter := &roleDeleter{result: issueops.DeleteResult{
|
||||
DryRun: true,
|
||||
|
|
@ -202,8 +198,7 @@ func TestDeleteRefusesTheDocumentedBodies(t *testing.T) {
|
|||
// The dependents guard is refused BELOW the wire, by issueops.Deleter — that is
|
||||
// what makes this endpoint incapable of orphaning a graph by omission. The
|
||||
// refusal reaching the client as a 500 would tell it the server was broken when
|
||||
// the request was, and would hide the one sentence that says what to send
|
||||
// instead.
|
||||
// the request was.
|
||||
func TestDeletePublishesTheRolesGuardAsA400(t *testing.T) {
|
||||
// The typed error, not a lookalike: the handler keys on the sentinel it
|
||||
// wraps.
|
||||
|
|
@ -234,11 +229,9 @@ func TestDeletePublishesTheRolesGuardAsA400(t *testing.T) {
|
|||
// TestDeletePublishesAnAbsentIDAsA404 pins the other refusal, and pins that its
|
||||
// detail does NOT name the ids.
|
||||
//
|
||||
// That is deliberate and is this surface's posture rather than this operation's
|
||||
// preference: NotFound's fixed sentence is what keeps a handler that decided a
|
||||
// miss without reading storage indistinguishable from one that read and missed.
|
||||
// `bd delete` still names them, because it is answering the person who typed
|
||||
// them.
|
||||
// NotFound's fixed sentence is what keeps a handler that decided a miss without
|
||||
// reading storage indistinguishable from one that read and missed. `bd delete`
|
||||
// still names them, because it is answering the person who typed them.
|
||||
func TestDeletePublishesAnAbsentIDAsA404(t *testing.T) {
|
||||
deleter := &roleDeleter{err: &issueops.NotFoundError{IDs: []string{"bd-nosuch"}}}
|
||||
ts := newTestServer(t, rolesConfig(Config{Deleter: deleter}))
|
||||
|
|
|
|||
|
|
@ -16,8 +16,7 @@ import (
|
|||
// rather than on the answer. `bd dep list` takes no limit, so a `limit`
|
||||
// parameter here would make the two front doors answer differently by default;
|
||||
// a cap on the answer with no cursor behind it would truncate with no way to
|
||||
// fetch the rest. Bounding the anchors bounds the work without doing either,
|
||||
// and it is the same shape of bound the document states.
|
||||
// fetch the rest. Bounding the anchors bounds the work without doing either.
|
||||
const maxDependencyAnchors = 100
|
||||
|
||||
// handleListDependencies answers GET /v0/beads/dependencies.
|
||||
|
|
@ -25,9 +24,8 @@ const maxDependencyAnchors = 100
|
|||
// Everything below the wire is on issueops.EdgeReader: which plane each anchor
|
||||
// is probed on, whether an absent anchor is a miss or an error, the type
|
||||
// filter, the edge order, and the de-duplication of a repeated id. What stays
|
||||
// here is transport — decoding two repeatable parameters, the size bound, and
|
||||
// flattening the role's per-anchor answer onto the flat array `bd dep list
|
||||
// --json` emits.
|
||||
// here is transport — two repeatable parameters, the size bound, and flattening
|
||||
// the role's per-anchor answer onto the flat array `bd dep list --json` emits.
|
||||
func (s *Server) handleListDependencies(w http.ResponseWriter, r *http.Request) {
|
||||
q := newQuery(r.URL.Query())
|
||||
|
||||
|
|
@ -41,9 +39,8 @@ func (s *Server) handleListDependencies(w http.ResponseWriter, r *http.Request)
|
|||
return
|
||||
}
|
||||
// Both bounds are checked here rather than left to the role: they are this
|
||||
// operation's own limits on one shared process, not statements about what a
|
||||
// stored-edge read means, and the role answers an empty request with an
|
||||
// empty result rather than a refusal.
|
||||
// operation's own limits, not statements about what a stored-edge read
|
||||
// means, and the role answers an empty request with an empty result.
|
||||
if len(ids) == 0 {
|
||||
requestInfo(r.Context()).refuse("issue_id")
|
||||
s.fail(w, r, InvalidArgument("issue_id", ReasonInvalidValue, "name at least one issue_id"))
|
||||
|
|
@ -76,9 +73,8 @@ func (s *Server) handleListDependencies(w http.ResponseWriter, r *http.Request)
|
|||
//
|
||||
// It classifies on the SENTINEL rather than on prose, unlike the read handlers'
|
||||
// invalidFilterParam: this role publishes issueops.ErrValidation for exactly
|
||||
// those two cases, so there is no message to match. Which of the two parameters
|
||||
// is named comes from the request the handler still holds — an empty entry can
|
||||
// only have come from `issue_id`, so anything else is `type`.
|
||||
// those two cases. Which parameter is named comes from the request the handler
|
||||
// still holds — an empty entry can only have come from `issue_id`.
|
||||
func (s *Server) failEdgeReadErr(w http.ResponseWriter, r *http.Request, err error, ids []string) {
|
||||
if !errors.Is(err, issueops.ErrValidation) {
|
||||
s.failErr(w, r, err)
|
||||
|
|
@ -98,11 +94,10 @@ func (s *Server) failEdgeReadErr(w http.ResponseWriter, r *http.Request, err err
|
|||
// wireEdges flattens the role's per-anchor answer onto the wire envelope.
|
||||
//
|
||||
// The element type is an ALIAS of types.Dependency — the same struct the CLI's
|
||||
// --json marshals — so this copies a header and shares everything under it.
|
||||
// There is no second wire struct here and there must never be one.
|
||||
// --json marshals. There is no second wire struct here and there must never be
|
||||
// one.
|
||||
//
|
||||
// Both members are non-nil so the body carries `[]` rather than `null`, which
|
||||
// the document states for each of them.
|
||||
// Both members are non-nil so the body carries `[]` rather than `null`.
|
||||
func wireEdges(result issueops.EdgeReadResult) apigen.DependencyEdges {
|
||||
body := apigen.DependencyEdges{
|
||||
Items: []apigen.Dependency{},
|
||||
|
|
|
|||
|
|
@ -12,10 +12,9 @@ import (
|
|||
)
|
||||
|
||||
// These cover the transport half of GET /v0/beads/dependencies: the two size
|
||||
// refusals this operation owns, how a role refusal is named on the wire, and
|
||||
// the two never-null members. Everything below the wire — which plane an anchor
|
||||
// is probed on, what Missing means, the edge order — is the role's, and is
|
||||
// pinned by backend/conformance/edge_reader_contract.go at all three backends.
|
||||
// refusals this operation owns, how a role refusal is named on the wire, and the
|
||||
// two never-null members. Everything below the wire is the role's, and is pinned
|
||||
// by backend/conformance/edge_reader_contract.go at all three backends.
|
||||
|
||||
func newEdgesServer(t *testing.T, edges *roleEdgeReader) *testServer {
|
||||
t.Helper()
|
||||
|
|
@ -130,9 +129,8 @@ func TestDependenciesRefuseAnUnknownParameter(t *testing.T) {
|
|||
// role's ErrValidation onto the two parameters that can cause it.
|
||||
//
|
||||
// The role owns both refusals — an empty id, an unusable dependency type — so
|
||||
// the handler cannot re-derive which one happened from the error; it names the
|
||||
// parameter from the request it still holds. An empty entry can only have come
|
||||
// from issue_id, so anything else is type.
|
||||
// the handler names the parameter from the request it still holds: an empty
|
||||
// entry can only have come from issue_id, so anything else is type.
|
||||
func TestADependencyRoleRefusalIsTheDocumentedBadRequest(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
|
|
|
|||
|
|
@ -56,10 +56,9 @@ var (
|
|||
// The envelopes that are NOT pages resolve their items the same way and are
|
||||
// pinned for the same reason: one whose items generated as a mirror struct
|
||||
// would put a second wire shape for one fact on this surface, silently.
|
||||
// DependencyEdges is here because wave 2 shipped without it and two reviews
|
||||
// did not catch that (bd-5o3gt); with it, every envelope on this surface
|
||||
// whose items are a canonical struct is now pinned, and the list has no
|
||||
// remaining hole to grow.
|
||||
// DependencyEdges is here because wave 2 shipped without it (bd-5o3gt);
|
||||
// every envelope on this surface whose items are a canonical struct is now
|
||||
// pinned.
|
||||
_ []types.Dependency = apigen.DependencyEdges{}.Items
|
||||
_ []issueops.IssueBlocking = apigen.BlockingAnnotations{}.Items
|
||||
_ []types.Issue = apigen.BatchCreateResponse{}.Items
|
||||
|
|
|
|||
|
|
@ -160,14 +160,14 @@ const (
|
|||
OpListDependencies = "listDependencies"
|
||||
// OpListBlockingAnnotations reads the DERIVED blocking decoration for
|
||||
// several issues at once — open blockers, issues blocked, and the parent.
|
||||
// It is a separate operation from listDependencies because it answers a
|
||||
// summary over two edge types with a status rule applied, where that one
|
||||
// returns the stored rows and applies nothing.
|
||||
// It is separate from listDependencies because it answers a summary over
|
||||
// two edge types with a status rule applied, where that one returns the
|
||||
// stored rows and applies nothing.
|
||||
OpListBlockingAnnotations = "listBlockingAnnotations"
|
||||
// OpGetDependencyTree walks the dependency graph from ONE root. It is a
|
||||
// separate operation from listDependencies because that one answers raw
|
||||
// edge rows for many anchors at one hop, and this one recurses from a
|
||||
// single anchor with a depth, a cycle policy and a node shape of its own.
|
||||
// OpGetDependencyTree walks the dependency graph from ONE root. It is
|
||||
// separate from listDependencies because that one answers raw edge rows for
|
||||
// many anchors at one hop, and this one recurses from a single anchor with a
|
||||
// depth, a cycle policy and a node shape of its own.
|
||||
OpGetDependencyTree = "getDependencyTree"
|
||||
OpCountReadyWork = "countReadyWork"
|
||||
OpQueryIssues = "queryIssues"
|
||||
|
|
@ -175,9 +175,9 @@ const (
|
|||
// bulk clearance of closed beads from one tier, behind issueops.Sweeper.
|
||||
OpSweepIssues = "sweepIssues"
|
||||
// OpDeleteIssues is the other DESTRUCTIVE operation: erasure of beads the
|
||||
// request NAMES, behind issueops.Deleter. It is the one operation on this
|
||||
// surface whose refusals include a question about the GRAPH — a named bead
|
||||
// with a dependent the request did not name — as well as about the request.
|
||||
// request NAMES, behind issueops.Deleter. It is the one operation here whose
|
||||
// refusals include a question about the GRAPH — a named bead with a
|
||||
// dependent the request did not name.
|
||||
OpDeleteIssues = "deleteIssues"
|
||||
// OpBatchCreateIssues creates many issues as one transaction, or none.
|
||||
OpBatchCreateIssues = "batchCreateIssues"
|
||||
|
|
@ -211,9 +211,9 @@ var operationCodes = map[string][]Code{
|
|||
// invalid_argument it can raise is the document-level unknown-query-key
|
||||
// rule this table deliberately omits.
|
||||
OpListSettings: {CodeBusy, CodeDBUnavailable, CodeInternal},
|
||||
// No 404, and that is the operation's whole shape: a key nothing stored and
|
||||
// a key stored as the empty string are one answer on this surface, so the
|
||||
// only refusal a key can earn is the 400 that says it was not a key.
|
||||
// No 404: a key nothing stored and a key stored as the empty string are one
|
||||
// answer on this surface, so the only refusal a key can earn is the 400
|
||||
// that says it was not a key.
|
||||
OpGetSetting: {CodeInvalidArgument, CodeBusy, CodeDBUnavailable, CodeInternal},
|
||||
// The 400 here is this operation's own, not the document-level
|
||||
// unknown-parameter rule: a malformed `skip_blocked`, and the EMPTY
|
||||
|
|
@ -231,29 +231,26 @@ var operationCodes = map[string][]Code{
|
|||
// for a stronger version of the same reason: this operation probes no id's
|
||||
// existence at all, so there is nothing it could 404 on.
|
||||
OpListBlockingAnnotations: {CodeInvalidArgument, CodeBusy, CodeDBUnavailable, CodeInternal},
|
||||
// The 404 is the difference from the row above, and it is the same
|
||||
// difference: this operation has ONE anchor, so there is no other answer to
|
||||
// preserve by reporting the miss in the body. Its 400 is its own — an empty
|
||||
// root, a direction outside the closed set, a non-positive max_depth — and
|
||||
// all three are the ROLE's ErrValidation reaching the wire.
|
||||
// The 404 is the difference from the row above: this operation has ONE
|
||||
// anchor, so there is no other answer to preserve by reporting the miss in
|
||||
// the body. Its 400 is its own — an empty root, a direction outside the
|
||||
// closed set, a non-positive max_depth — all three the ROLE's ErrValidation
|
||||
// reaching the wire.
|
||||
OpGetDependencyTree: {CodeInvalidArgument, CodeNotFound, CodeBusy, CodeDBUnavailable, CodeInternal},
|
||||
// The same vocabulary as the listing it sizes: it takes the same filters
|
||||
// and can refuse them the same way. limit=0's mode-dependent refusal has no
|
||||
// analog here because there is no limit to pass — but that was a
|
||||
// CodeInvalidArgument too, so this row would not change if there were.
|
||||
// analog here because there is no limit to pass.
|
||||
OpCountReadyWork: {CodeInvalidArgument, CodeBusy, CodeDBUnavailable, CodeInternal},
|
||||
// The listing's vocabulary minus the cursor: this operation has none, so
|
||||
// invalid_cursor cannot arise. An unparseable EXPRESSION is an
|
||||
// invalid_argument on `q` rather than a code of its own — a client's
|
||||
// recovery is the same as for any other malformed parameter value, and a
|
||||
// code it cannot act on differently is a code it should not have to know.
|
||||
// recovery is the same as for any other malformed parameter value.
|
||||
OpQueryIssues: {CodeInvalidArgument, CodeBusy, CodeDBUnavailable, CodeInternal},
|
||||
// The 400 here is the widest on this surface, and most of it is not this
|
||||
// handler's: an unknown or malformed body member is, but the unfiltered
|
||||
// durable sweep, the unrecognized tier and the malformed glob are all the
|
||||
// ROLE's ErrValidation reaching the wire through failSweepErr. No 404 —
|
||||
// this operation names no id — and no 409: a sweep has nothing to conflict
|
||||
// with, since a bead another sweep already took is simply not in the set.
|
||||
// handler's: the unfiltered durable sweep, the unrecognized tier and the
|
||||
// malformed glob are all the ROLE's ErrValidation reaching the wire through
|
||||
// failSweepErr. No 404 — this operation names no id — and no 409: a bead
|
||||
// another sweep already took is simply not in the set.
|
||||
OpSweepIssues: {CodeInvalidArgument, CodeBusy, CodeDBUnavailable, CodeInternal},
|
||||
// CodeNotFound is the one this operation has and the sweep does not: a
|
||||
// sweep describes a set that can legitimately be empty, while a delete
|
||||
|
|
@ -263,11 +260,11 @@ var operationCodes = map[string][]Code{
|
|||
CodeInvalidArgument, CodeNotFound, CodeAlreadyClaimed, CodeNotClaimable,
|
||||
CodeBusy, CodeDBUnavailable, CodeInternal,
|
||||
},
|
||||
// No not_found, and that is a decision rather than an omission. The role
|
||||
// refuses an edge whose target names nothing, and that refusal is about the
|
||||
// REQUEST BODY the client sent, not about a resource this operation was
|
||||
// asked to address — there is no id in the path to have missed. A 404 here
|
||||
// would tell a client its request went to the wrong place.
|
||||
// No not_found. The role refuses an edge whose target names nothing, and
|
||||
// that refusal is about the REQUEST BODY the client sent, not about a
|
||||
// resource this operation was asked to address — there is no id in the path
|
||||
// to have missed. A 404 here would tell a client its request went to the
|
||||
// wrong place.
|
||||
//
|
||||
// No conflict code either: this operation publishes no `id` member, so no
|
||||
// item can collide with a stored row and the role's ErrAlreadyExists is
|
||||
|
|
|
|||
|
|
@ -92,10 +92,7 @@ func (s *Server) handleReady(w http.ResponseWriter, r *http.Request) {
|
|||
// It is one function because the two operations must admit exactly the same
|
||||
// filters: countReadyWork answers with the size of the set listReadyWork
|
||||
// returns, and a parameter one of them decoded and the other did not would
|
||||
// make that identity false for any client that sent it. Each parameter this
|
||||
// reads is also, by construction, one the operation accepts — the unknown-
|
||||
// parameter allowlist IS the set of names the handler asked for — so the two
|
||||
// parameter tables cannot drift apart either.
|
||||
// make that identity false for any client that sent it.
|
||||
func readyFilters(q *query) issueops.ReadyRequest {
|
||||
return issueops.ReadyRequest{
|
||||
Assignee: q.str("assignee"),
|
||||
|
|
@ -129,11 +126,9 @@ func readyFilters(q *query) issueops.ReadyRequest {
|
|||
// bounded count past it even if a parameter for one existed.
|
||||
//
|
||||
// THE SORT IS SENT ANYWAY, and the operation publishes no parameter for it. A
|
||||
// count has no order, so there is nothing for a client to choose; but the
|
||||
// request still has to be a request the builder accepts, and sending the
|
||||
// listing's own default is how this stays the listing's question rather than a
|
||||
// second one that merely resembles it. Sending "" would adopt the storage
|
||||
// layer's hybrid fallback, which the document says no front door relies on.
|
||||
// count has no order, but the request still has to be one the builder accepts,
|
||||
// and sending "" would adopt the storage layer's hybrid fallback that no front
|
||||
// door relies on.
|
||||
func (s *Server) handleCountReady(w http.ResponseWriter, r *http.Request) {
|
||||
q := newQuery(r.URL.Query())
|
||||
|
||||
|
|
@ -251,12 +246,10 @@ func (s *Server) handleListIssues(w http.ResponseWriter, r *http.Request) {
|
|||
|
||||
// handleQueryIssues answers GET /v0/beads/issues:query.
|
||||
//
|
||||
// The EXPRESSION IS NOT PARSED HERE, and that is the whole shape of this
|
||||
// handler. `bd query` used to parse it, evaluate it, decide from the result
|
||||
// whether a predicate was needed, and — because it knew — bound the scan at
|
||||
// max(3*limit, 100) rows, twice, once per route. Every one of those decisions
|
||||
// is inside the role, so this handler cannot make the truncating one: it reads
|
||||
// five parameters and hands the sentence over.
|
||||
// The EXPRESSION IS NOT PARSED HERE. Parsing, evaluation, the predicate
|
||||
// decision and the scan bound all live inside the role, so this handler cannot
|
||||
// make the truncating one: it reads five parameters and hands the sentence
|
||||
// over.
|
||||
func (s *Server) handleQueryIssues(w http.ResponseWriter, r *http.Request) {
|
||||
q := newQuery(r.URL.Query())
|
||||
|
||||
|
|
|
|||
|
|
@ -12,17 +12,16 @@ import (
|
|||
// lives in roles_test.go, beside the other store-shaped-source cases.
|
||||
|
||||
// TestCountReadyRunsTheListingsQueryUnbounded asserts the property the
|
||||
// operation exists to deliver rather than the number it happened to return: the
|
||||
// count runs the SAME ready query the listing runs, with the page taken off.
|
||||
// operation exists to deliver: the count runs the SAME ready query the listing
|
||||
// runs, with the page taken off.
|
||||
//
|
||||
// The recorded filter is the only place that is visible. A body carrying the
|
||||
// right total says nothing about which set was counted — every wrong predicate
|
||||
// also produces a number — so the assertions are on the filter: the label the
|
||||
// wire named, the listing's own sort policy, and Limit 0. Limit is the one that
|
||||
// would silently break the operation's promise, because the shared builder
|
||||
// defaults an UNSET limit to workapi.DefaultReadyLimit: a count assembled
|
||||
// without the role would answer "how many of the first 100" and be published as
|
||||
// a total.
|
||||
// A body carrying the right total says nothing about which set was counted —
|
||||
// every wrong predicate also produces a number — so the assertions are on the
|
||||
// filter: the label the wire named, the listing's own sort policy, and Limit 0.
|
||||
// Limit is the one that would silently break the operation's promise, because
|
||||
// the shared builder defaults an UNSET limit to workapi.DefaultReadyLimit: a
|
||||
// count assembled without the role would answer "how many of the first 100" and
|
||||
// be published as a total.
|
||||
func TestCountReadyRunsTheListingsQueryUnbounded(t *testing.T) {
|
||||
rec := &recordingIssues{items: countedPage()}
|
||||
ts := newTestServer(t, Config{Provider: &fakeProvider{
|
||||
|
|
@ -59,11 +58,10 @@ func TestCountReadyRunsTheListingsQueryUnbounded(t *testing.T) {
|
|||
|
||||
// TestCountReadyPublishesNoPageParameters: `limit`, `offset` and `sort` are the
|
||||
// listing's parameters and are absent from this operation's table, so sending
|
||||
// one is version skew rather than a bad value — the client is asking for
|
||||
// something this operation does not have, and `unknown_parameter` is the answer
|
||||
// that tells it so. Silently accepting `limit` would be the failure the role
|
||||
// itself refuses; silently accepting `sort` would advertise a knob that changes
|
||||
// nothing about a set with no order.
|
||||
// one is version skew rather than a bad value and `unknown_parameter` is the
|
||||
// answer. Silently accepting `limit` would be the failure the role itself
|
||||
// refuses; silently accepting `sort` would advertise a knob that changes nothing
|
||||
// about a set with no order.
|
||||
func TestCountReadyPublishesNoPageParameters(t *testing.T) {
|
||||
for _, param := range []string{"limit=5", "limit=0", "offset=1", "sort=oldest"} {
|
||||
ts, _ := newReadServer(t, Config{})
|
||||
|
|
@ -83,8 +81,7 @@ func TestCountReadyPublishesNoPageParameters(t *testing.T) {
|
|||
// rests on: every filter the listing accepts, the count accepts too, and both
|
||||
// build the same predicate from it. A parameter one of them knew and the other
|
||||
// did not would make "the size of the page you would get" false for exactly the
|
||||
// clients that sent it — and would fail as a 400 on one path only, which is the
|
||||
// kind of asymmetry nobody notices until a script breaks.
|
||||
// clients that sent it, and would fail as a 400 on one path only.
|
||||
func TestCountReadyAndListReadyAdmitTheSameFilters(t *testing.T) {
|
||||
shared := "assignee=alice&unassigned=false&type=bug&exclude_type=epic&label=api&label_any=x" +
|
||||
"&exclude_label=wip&label_pattern=tech-*&label_regex=^tech-&priority=1&parent=bd-1" +
|
||||
|
|
|
|||
|
|
@ -39,10 +39,8 @@ import (
|
|||
// already drops a nil element out of a page. Get is the whole reason the type
|
||||
// exists.
|
||||
//
|
||||
// issueops.EdgeReader has no wrapper here for the same reason Ready and List
|
||||
// need nothing: it answers with a value, and wireEdges drops a nil edge. A role
|
||||
// that hands back no pointer cannot be dereferenced into a panic, so a checked
|
||||
// wrapper over it would be a layer with nothing to check.
|
||||
// issueops.EdgeReader has no wrapper here for the same reason: it answers with
|
||||
// a value, and wireEdges drops a nil edge.
|
||||
type checkedReader struct{ inner issueops.Reader }
|
||||
|
||||
// Ready passes the request through unchanged.
|
||||
|
|
@ -70,10 +68,8 @@ func (c checkedReader) Get(ctx context.Context, req issueops.GetRequest) (*issue
|
|||
//
|
||||
// The response body carries issue VALUES where the role answers with pointers,
|
||||
// so the handler dereferences every entry — checkedClaimer's hazard, once per
|
||||
// item. The role promises no nil entry for a successful call precisely because
|
||||
// a batch that could not create every item creates none; an entry that is nil
|
||||
// anyway is a broken implementation, so it is the generic 500 with the fault in
|
||||
// the log, not a 404 (nothing here knows an issue is missing) and not a panic.
|
||||
// item. An entry that is nil anyway is a broken implementation, so it is the
|
||||
// generic 500 with the fault in the log and not a panic.
|
||||
type checkedBatchCreator struct{ inner issueops.BatchCreator }
|
||||
|
||||
// CreateBatch refuses a result that reports success without every issue the
|
||||
|
|
|
|||
|
|
@ -105,9 +105,9 @@ func (e *roleEdgeReader) edgeRequests() []issueops.EdgeReadRequest {
|
|||
}
|
||||
|
||||
// roleBlockingAnnotator is the derived-decoration role of the store-shaped
|
||||
// source. It is its own fake beside roleEdgeReader rather than a second method
|
||||
// on it, because the two are separate interfaces for separate questions and a
|
||||
// double answering both would be the shape that seam exists to rule out.
|
||||
// source. It is its own fake beside roleEdgeReader because the two are separate
|
||||
// interfaces for separate questions, and a double answering both would be the
|
||||
// shape that seam exists to rule out.
|
||||
type roleBlockingAnnotator struct {
|
||||
result issueops.BlockingResult
|
||||
err error
|
||||
|
|
@ -132,10 +132,10 @@ func (a *roleBlockingAnnotator) blockingRequests() []issueops.BlockingRequest {
|
|||
return append([]issueops.BlockingRequest(nil), a.reads...)
|
||||
}
|
||||
|
||||
// roleTreeWalker is the dependency-tree role of the store-shaped source. Like
|
||||
// its siblings it records the request it was handed, because the assertion the
|
||||
// tree route is worth making is that the WIRE's parameters reach the role
|
||||
// unrewritten — the walk itself belongs to the conformance contract.
|
||||
// roleTreeWalker is the dependency-tree role of the store-shaped source. It
|
||||
// records the request it was handed: the assertion worth making on the tree
|
||||
// route is that the WIRE's parameters reach the role unrewritten, since the
|
||||
// walk itself belongs to the conformance contract.
|
||||
type roleTreeWalker struct {
|
||||
result issueops.TreeResult
|
||||
err error
|
||||
|
|
@ -160,11 +160,8 @@ func (w *roleTreeWalker) walkRequests() []issueops.WalkTreeRequest {
|
|||
return append([]issueops.WalkTreeRequest(nil), w.walks...)
|
||||
}
|
||||
|
||||
// roleReadyCounter is the third role a store-shaped source must supply. It is
|
||||
// its own fake rather than a method on roleReader for the reason the roles are
|
||||
// separate interfaces: a backend hands out one surface per question, and a test
|
||||
// double that answered two of them would be the shape this seam exists to rule
|
||||
// out.
|
||||
// roleReadyCounter is the ready-sizing role of the store-shaped source, its own
|
||||
// fake rather than a method on roleReader.
|
||||
type roleReadyCounter struct {
|
||||
total int64
|
||||
err error
|
||||
|
|
@ -191,8 +188,8 @@ func (c *roleReadyCounter) countRequests() []issueops.ReadyRequest {
|
|||
|
||||
// roleQuerier is the boolean-query role's double. It records the whole request
|
||||
// because the property this surface owes is that the EXPRESSION reaches the
|
||||
// role untouched: a handler that parsed it here would be the drift the role
|
||||
// exists to remove, and only the recorded sentence can show it did not.
|
||||
// role untouched: a handler that parsed it here would be a second
|
||||
// implementation of the query language.
|
||||
type roleQuerier struct {
|
||||
page issueops.IssuePage
|
||||
err error
|
||||
|
|
@ -220,7 +217,7 @@ func (q *roleQuerier) queryRequests() []issueops.QueryRequest {
|
|||
// roleBatchCreator is the store-shaped source's batch-create role. It answers
|
||||
// with one issue per requested item by default, which is what the role promises
|
||||
// and what the handler's checked wrapper insists on; a case that wants the
|
||||
// broken shape sets issues explicitly.
|
||||
// broken shape sets issues.
|
||||
type roleBatchCreator struct {
|
||||
issues []*types.Issue
|
||||
err error
|
||||
|
|
@ -359,12 +356,9 @@ func (s *roleStats) assigneeRequests() []issueops.AssigneeStatsRequest {
|
|||
return append([]issueops.AssigneeStatsRequest(nil), s.assignees...)
|
||||
}
|
||||
|
||||
// rolesConfig completes a store-shaped database source.
|
||||
//
|
||||
// Listen requires the WHOLE role set together (checkDatabaseSource), so a test
|
||||
// that exercises one operation still has to hand over the roles the other
|
||||
// operations reach. This fills the ones the caller left nil with inert fakes
|
||||
// and keeps the ones it set, so a test names only the role it is about.
|
||||
// rolesConfig completes a store-shaped database source. Listen requires the
|
||||
// WHOLE role set together (checkDatabaseSource), so this fills the roles the
|
||||
// caller left nil with inert fakes and a test names only the role it is about.
|
||||
//
|
||||
// Not for TestListenRequiresExactlyOneDatabaseSource: that test's whole subject
|
||||
// is the PARTIAL set, so it builds its Configs by hand.
|
||||
|
|
@ -411,19 +405,18 @@ func rolesConfig(cfg Config) Config {
|
|||
return cfg
|
||||
}
|
||||
|
||||
// rolesConfigWithout is a complete source with exactly one role removed, which
|
||||
// is the shape every half-set case in TestListenRequiresExactlyOneDatabaseSource
|
||||
// wants. Naming the role to DROP rather than the roles to keep is what stops
|
||||
// those cases from having to be edited every time the set grows.
|
||||
// rolesConfigWithout is a complete source with exactly one role removed. Naming
|
||||
// the role to DROP rather than the roles to keep is what stops the partial-set
|
||||
// cases from having to be edited every time the set grows.
|
||||
func rolesConfigWithout(drop func(*Config)) Config {
|
||||
cfg := rolesConfig(Config{})
|
||||
drop(&cfg)
|
||||
return cfg
|
||||
}
|
||||
|
||||
// roleCycleDetector is the third role of the store-shaped source. It is the
|
||||
// same shape as the two above so that every configured-roles case can hand
|
||||
// Listen a complete source without deciding what its cycle answer should be.
|
||||
// roleCycleDetector is the cycle-report role of the store-shaped source, the
|
||||
// same shape as its siblings so a case can hand Listen a complete source
|
||||
// without deciding what its cycle answer should be.
|
||||
type roleCycleDetector struct {
|
||||
report issueops.CycleReport
|
||||
err error
|
||||
|
|
@ -442,12 +435,10 @@ func (d *roleCycleDetector) DetectCycles(_ context.Context, req issueops.DetectC
|
|||
return d.report, nil
|
||||
}
|
||||
|
||||
// roleSweeper is the store-shaped source's bulk-clearance role. Like the
|
||||
// others it answers with whatever a case configured, so every configured-roles
|
||||
// case can hand Listen a COMPLETE source without deciding what a sweep of its
|
||||
// fixture should do — which matters more here than for the reads, because the
|
||||
// alternative to a complete source is a server that binds and then
|
||||
// nil-dereferences on the one request that deletes beads.
|
||||
// roleSweeper is the store-shaped source's bulk-clearance role. Every case
|
||||
// hands Listen a COMPLETE source for a reason that bites hardest here: the
|
||||
// alternative is a server that binds and then nil-dereferences on the one
|
||||
// request that deletes beads.
|
||||
type roleSweeper struct {
|
||||
result issueops.SweepResult
|
||||
err error
|
||||
|
|
@ -473,9 +464,7 @@ func (s *roleSweeper) requests() []issueops.SweepRequest {
|
|||
}
|
||||
|
||||
// roleDeleter is the store-shaped source's named-row erasure role, the same
|
||||
// shape as roleSweeper and for the same reason: the alternative to a complete
|
||||
// source is a server that binds and then nil-dereferences on a request that
|
||||
// deletes beads.
|
||||
// shape as roleSweeper and for the same reason.
|
||||
type roleDeleter struct {
|
||||
result issueops.DeleteResult
|
||||
err error
|
||||
|
|
@ -516,9 +505,7 @@ func countedPage() []*types.IssueWithCounts {
|
|||
// PARTIAL set is the dangerous one: a Config carrying a reader and no claimer
|
||||
// would bind, answer every read, and fail the one write on this surface with a
|
||||
// nil dereference — at claim time, in a handler, on a live server. Each role an
|
||||
// operation reaches has a row below for that reason, and the case that matters
|
||||
// most is the NEWEST role missing: that is what a caller written against the
|
||||
// previous release passes.
|
||||
// operation reaches has a row below for that reason.
|
||||
func TestListenRequiresExactlyOneDatabaseSource(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
|
|
@ -539,10 +526,8 @@ func TestListenRequiresExactlyOneDatabaseSource(t *testing.T) {
|
|||
cfg: rolesConfig(Config{}),
|
||||
},
|
||||
// One case per role, each dropping exactly that role from an otherwise
|
||||
// complete source. The set is all-or-nothing rather than a required
|
||||
// pair plus optional extras: a Config missing any one role binds,
|
||||
// advertises that operation's capability, and then faults inside a
|
||||
// handler on a live server. A new role adds one line here and one to
|
||||
// complete source: the set is all-or-nothing rather than a required
|
||||
// pair plus optional extras. A new role adds one line here and one to
|
||||
// rolesConfig, and nothing else in this test.
|
||||
{
|
||||
name: "no reader",
|
||||
|
|
@ -585,7 +570,7 @@ func TestListenRequiresExactlyOneDatabaseSource(t *testing.T) {
|
|||
wantErr: "no database source",
|
||||
},
|
||||
{
|
||||
// The other destructive role: a Config missing this one binds,
|
||||
// The other destructive role: missing it, the server binds,
|
||||
// advertises issues.delete, and nil-dereferences on the first
|
||||
// request that erases a named bead.
|
||||
name: "no deleter",
|
||||
|
|
@ -603,9 +588,9 @@ func TestListenRequiresExactlyOneDatabaseSource(t *testing.T) {
|
|||
wantErr: "no database source",
|
||||
},
|
||||
{
|
||||
// The absence that would cost most: a Config missing this one binds,
|
||||
// advertises issues.sweep in its own capability list, and
|
||||
// nil-dereferences on the first request that deletes beads in bulk.
|
||||
// The absence that would cost most: the server binds, advertises
|
||||
// issues.sweep, and nil-dereferences on the first request that
|
||||
// deletes beads in bulk.
|
||||
name: "no sweeper",
|
||||
cfg: rolesConfigWithout(func(c *Config) { c.Sweeper = nil }),
|
||||
wantErr: "no database source",
|
||||
|
|
@ -636,9 +621,8 @@ func TestListenRequiresExactlyOneDatabaseSource(t *testing.T) {
|
|||
wantErr: "exactly one database source",
|
||||
},
|
||||
{
|
||||
// The pair ALONE used to be a complete source, so this is the exact
|
||||
// Config the first release of this arm accepted. It is here as a
|
||||
// regression case rather than as another one-role-missing row.
|
||||
// The exact Config the first release of this arm accepted: the pair
|
||||
// ALONE used to be a complete source. A regression case.
|
||||
name: "a reader and a claimer without a ready counter",
|
||||
cfg: Config{Reader: &roleReader{}, Claimer: &roleClaimer{}},
|
||||
wantErr: "no database source",
|
||||
|
|
@ -750,22 +734,17 @@ func TestConfiguredRolesServeTheSameReadyBytesAsAProvider(t *testing.T) {
|
|||
}
|
||||
|
||||
// TestConfiguredRolesAnswerEveryDatabaseRoute drives the database-touching
|
||||
// operations against a store-shaped source, which is the whole point: none of
|
||||
// them can reach a unit of work here, because there is no provider to open one.
|
||||
// operations against a store-shaped source: none of them can reach a unit of
|
||||
// work here, because there is no provider to open one.
|
||||
//
|
||||
// NOT ALL OF THEM, despite the name, and the shortfall is worth knowing before
|
||||
// reading a green run as coverage. The subtests below drive ten of the sixteen
|
||||
// capability-bearing operations in routes.go. The other six —
|
||||
// NOT ALL OF THEM, despite the name: the subtests below drive ten of the
|
||||
// sixteen capability-bearing operations in routes.go. The other six —
|
||||
// dependencies/cycles, dependencies/blocking, dependencies/tree,
|
||||
// issues:batchCreate, issues:sweep and issues:delete — are exercised against a
|
||||
// roles source in their own files (cycles_test.go, blocking_test.go,
|
||||
// tree_test.go, batch_create_test.go, sweep_test.go, delete_test.go) rather
|
||||
// than here.
|
||||
//
|
||||
// The name predates most of those and an earlier pass "fixed" a stale count in
|
||||
// it by widening the claim to "every", which made it less true rather than
|
||||
// more. Either add the six here or leave this paragraph accurate; do not
|
||||
// generalize the sentence again.
|
||||
// tree_test.go, batch_create_test.go, sweep_test.go, delete_test.go). Either
|
||||
// add the six here or keep this paragraph accurate; do not generalize the
|
||||
// sentence again.
|
||||
func TestConfiguredRolesAnswerEveryDatabaseRoute(t *testing.T) {
|
||||
details := &issueops.IssueDetails{Issue: *seededIssue("bd-1", "alice", types.StatusOpen)}
|
||||
reader := &roleReader{page: issueops.IssuePage{Items: countedPage(), HasMore: true}, details: details}
|
||||
|
|
@ -817,9 +796,8 @@ func TestConfiguredRolesAnswerEveryDatabaseRoute(t *testing.T) {
|
|||
if body := decodeBody(t, resp); body["total"] != float64(41) {
|
||||
t.Errorf("total = %v, want the 41 the role reported", body["total"])
|
||||
}
|
||||
// The role is handed the listing's request with the page taken off:
|
||||
// the filter the wire named, no Limit, no Offset, and the sort this
|
||||
// server sends on both ready operations.
|
||||
// The listing's request with the page taken off: the filter the wire
|
||||
// named, no Limit, no Offset, and the sort both ready operations send.
|
||||
reqs := counter.countRequests()
|
||||
if len(reqs) != 1 {
|
||||
t.Fatalf("count requests = %+v, want exactly one", reqs)
|
||||
|
|
@ -845,8 +823,8 @@ func TestConfiguredRolesAnswerEveryDatabaseRoute(t *testing.T) {
|
|||
t.Errorf("query page carries a next_cursor: %v", body)
|
||||
}
|
||||
// The EXPRESSION reaches the role verbatim. A handler that parsed,
|
||||
// normalised or re-quoted it would be the second implementation of the
|
||||
// query language this role exists to prevent.
|
||||
// normalised or re-quoted it would be a second implementation of the
|
||||
// query language.
|
||||
reqs := querier.queryRequests()
|
||||
if len(reqs) != 1 {
|
||||
t.Fatalf("query requests = %+v, want exactly one", reqs)
|
||||
|
|
|
|||
|
|
@ -118,9 +118,7 @@ var routeTable = []route{
|
|||
{
|
||||
op: OpQueryIssues,
|
||||
method: http.MethodGet,
|
||||
// A collection-level custom method, spelled as ready:count is: the
|
||||
// segment is a LITERAL, so the router registers the documented path
|
||||
// itself and no specPath declaration is needed.
|
||||
// A collection-level custom method, spelled as ready:count is.
|
||||
pattern: "/v0/beads/issues:query",
|
||||
capability: "issues.query",
|
||||
implemented: true,
|
||||
|
|
@ -161,11 +159,9 @@ var routeTable = []route{
|
|||
{
|
||||
op: OpListBlockingAnnotations,
|
||||
method: http.MethodGet,
|
||||
// A literal path under the same collection as the stored-edge read, so
|
||||
// no specPath declaration is needed and no wildcard is involved: the
|
||||
// router registers the documented path itself, and it cannot collide
|
||||
// with /v0/beads/dependencies or /v0/beads/dependencies/cycles, both of
|
||||
// which are literals too.
|
||||
// A literal path under the same collection as the stored-edge read. No
|
||||
// wildcard is involved, so it cannot collide with /v0/beads/dependencies
|
||||
// or /v0/beads/dependencies/cycles, both of which are literals too.
|
||||
pattern: "/v0/beads/dependencies/blocking",
|
||||
capability: "dependencies.blocking",
|
||||
implemented: true,
|
||||
|
|
@ -185,9 +181,7 @@ var routeTable = []route{
|
|||
{
|
||||
op: OpBatchCreateIssues,
|
||||
method: http.MethodPost,
|
||||
// A collection-level custom method, spelled the way ready:count's is
|
||||
// and registered as the literal path for the same reason: the segment
|
||||
// carries no wildcard, so ServeMux can match it exactly.
|
||||
// A collection-level custom method, spelled the way ready:count's is.
|
||||
//
|
||||
// It does not collide with the claim row's wide POST wildcard below.
|
||||
// That pattern is /v0/beads/issues/{idop} and requires the separating
|
||||
|
|
@ -227,11 +221,7 @@ var routeTable = []route{
|
|||
{
|
||||
op: OpSweepIssues,
|
||||
method: http.MethodPost,
|
||||
// A collection-level custom method, spelled the way countReadyWork's
|
||||
// is and needing no specPath declaration for the same reason: the
|
||||
// segment is a LITERAL. Only a WILDCARD segment is inexpressible as a
|
||||
// ServeMux pattern, which is what makes the claim route the one
|
||||
// exception.
|
||||
// A collection-level custom method, spelled the way countReadyWork's is.
|
||||
//
|
||||
// It is registered AFTER the claim's `/v0/beads/issues/{idop}`, and
|
||||
// ServeMux precedence is by specificity rather than by order, so the
|
||||
|
|
|
|||
|
|
@ -131,11 +131,6 @@ type Config struct {
|
|||
// dereference inside a handler on a live server, which is worse than not
|
||||
// starting.
|
||||
//
|
||||
// The set grows as operations do: each role a new operation reaches becomes
|
||||
// another field here and another one this source must carry, in the same
|
||||
// change as the operation, because a database source that answers some
|
||||
// operations and faults on others is not a source.
|
||||
//
|
||||
// A caller with a store takes them off the store's own accessors, and WHICH
|
||||
// store value it takes them off is the whole question. Every decorator a
|
||||
// store wears is on the value its accessor returns — that is what the
|
||||
|
|
@ -174,11 +169,6 @@ type Config struct {
|
|||
// one reason — so the units of work they open land in that request's uow_ms
|
||||
// (see Server.reader) — and a role reached this way opens none through this
|
||||
// server, so a rebuild would buy nothing.
|
||||
//
|
||||
// Every one of these is required for one reason: a server that binds while
|
||||
// unable to answer an operation its own capability list advertises is the
|
||||
// failure this check exists to prevent, and a nil role would produce it on
|
||||
// the first request to that route instead of at startup.
|
||||
Reader issueops.Reader
|
||||
Claimer issueops.Claimer
|
||||
Settings issueops.WorkspaceConfig
|
||||
|
|
@ -189,16 +179,12 @@ type Config struct {
|
|||
TreeWalker issueops.TreeWalker
|
||||
ReadyCounter issueops.ReadyCounter
|
||||
Querier issueops.Querier
|
||||
// Sweeper is the DESTRUCTIVE one, and it is required on the same terms as
|
||||
// every other role rather than opt-in. A Config that could omit it would
|
||||
// be a Config that quietly decides whether this build erases beads, which
|
||||
// is a decision that belongs to the operator who chose to run bd serve at
|
||||
// all — not to whether a caller remembered a field.
|
||||
// Sweeper is the DESTRUCTIVE one, required on the same terms as every other
|
||||
// role rather than opt-in: whether this build erases beads is a decision
|
||||
// for the operator who chose to run bd serve, not a consequence of whether
|
||||
// a caller remembered a field.
|
||||
Sweeper issueops.Sweeper
|
||||
// Deleter is the OTHER destructive one, required on the same terms and for
|
||||
// the same reason: whether this build can erase named beads is the
|
||||
// operator's decision, not a consequence of whether a caller remembered a
|
||||
// field.
|
||||
// Deleter is the OTHER destructive one, required for the same reason.
|
||||
Deleter issueops.Deleter
|
||||
BatchCreator issueops.BatchCreator
|
||||
// Workspace is the startup snapshot GET /v0/beads/context answers from.
|
||||
|
|
@ -407,15 +393,12 @@ func Listen(cfg Config) (*Server, error) {
|
|||
// set is refused with the same message as none at all, because it is the same
|
||||
// mistake and the failure it would otherwise produce is the worst shape
|
||||
// available — a Config missing one role binds, answers every other route, and
|
||||
// fails that one with a nil dereference in a handler on a live server. That is
|
||||
// why the set is all-or-nothing rather than a required pair plus optional
|
||||
// extras.
|
||||
// fails that one with a nil dereference in a handler on a live server.
|
||||
//
|
||||
// The set GROWS as this surface grows, and that is deliberate rather than
|
||||
// unfortunate: every operation added here is an operation a roles-backed
|
||||
// deployment must be able to answer, so a role added to the set turns "this
|
||||
// build serves an operation your Config cannot answer" into a startup error
|
||||
// instead of a 500 on the first client that finds it.
|
||||
// The set GROWS as this surface grows: every operation added here is an
|
||||
// operation a roles-backed deployment must be able to answer, so a role added
|
||||
// to the set turns "this build serves an operation your Config cannot answer"
|
||||
// into a startup error instead of a 500 on the first client that finds it.
|
||||
//
|
||||
// Both together is refused rather than resolved by precedence: a caller that
|
||||
// set both holds two different opinions about where this server reads from, and
|
||||
|
|
@ -431,16 +414,16 @@ func Listen(cfg Config) (*Server, error) {
|
|||
// at Listen is the difference between a startup error naming the store to take
|
||||
// roles from and a server that has been quietly running a user's subprocess per
|
||||
// claim since it booted.
|
||||
|
||||
// sourceRoles is the store-shaped source's roles in ONE place, so the three
|
||||
// questions checkDatabaseSource asks — is any set, is any missing, does any
|
||||
// fire hooks — cannot drift apart from each other as the set grows. An
|
||||
// operation that reaches a role this source does not yet carry adds a line
|
||||
// here and a line to roleSourceNames, and nothing else in this file.
|
||||
// fire hooks — cannot drift apart as the set grows. An operation that reaches a
|
||||
// role this source does not yet carry adds a line here and a line to
|
||||
// roleSourceNames, and nothing else in this file.
|
||||
//
|
||||
// A role is compared against nil as an INTERFACE, which is what the caller
|
||||
// actually sets; a typed nil stored in one of these fields is a value as far
|
||||
// as this check is concerned, exactly as it was when the check was a hand-
|
||||
// written boolean per role.
|
||||
// actually sets; a typed nil stored in one of these fields is a value as far as
|
||||
// this check is concerned.
|
||||
func sourceRoles(cfg Config) []any {
|
||||
return []any{cfg.Reader, cfg.Claimer, cfg.Settings, cfg.Stats, cfg.CycleDetector, cfg.EdgeReader, cfg.BlockingAnnotator, cfg.TreeWalker, cfg.ReadyCounter, cfg.Querier, cfg.Sweeper, cfg.Deleter, cfg.BatchCreator}
|
||||
}
|
||||
|
|
@ -576,14 +559,9 @@ func (s *Server) reader(r *http.Request) (issueops.Reader, error) {
|
|||
|
||||
// statsReporter returns the guarded summary-statistics surface for one request.
|
||||
//
|
||||
// It is the third of the same shape reader() and claimer() have, for the same
|
||||
// reasons: the configured role on the roles source, one built per request on the
|
||||
// provider source so its units of work land in THIS request's uow_ms, and the
|
||||
// source held by INTERFACE so uow.StatsReporterSource is load-bearing rather
|
||||
// than decorative.
|
||||
//
|
||||
// There is no checked wrapper around it, and that is a property of the role
|
||||
// rather than an omission: issueops.StatsResult carries a VALUE, so there is no
|
||||
// Same two sources as reader() and claimer(), for the same reasons, and held by
|
||||
// INTERFACE so uow.StatsReporterSource is load-bearing rather than decorative.
|
||||
// No checked wrapper: issueops.StatsResult carries a VALUE, so there is no
|
||||
// nil-with-nil-error answer for a handler to dereference. checkedReader exists
|
||||
// because Reader.Get hands back a pointer.
|
||||
func (s *Server) statsReporter(r *http.Request) (issueops.StatsReporter, error) {
|
||||
|
|
@ -596,16 +574,11 @@ func (s *Server) statsReporter(r *http.Request) (issueops.StatsReporter, error)
|
|||
|
||||
// cycleDetector returns the guarded cycle-report surface for one request.
|
||||
//
|
||||
// It is the third of the same trio, built the same two ways for the same
|
||||
// reasons: the configured role on the roles source, and on the provider source
|
||||
// one built per request so its unit of work lands in THIS request's log line,
|
||||
// held by INTERFACE so uow.CycleDetectorSource is load-bearing rather than
|
||||
// decorative.
|
||||
//
|
||||
// There is no checked wrapper around it, and that is the difference from its
|
||||
// two siblings. Those exist because a handler DEREFERENCES a pointer the role
|
||||
// returned; this report is a value whose slice a nil-safe range walks, so there
|
||||
// is no dereference for a misbehaving implementation to turn into a panic.
|
||||
// Same two sources as reader() and claimer(), for the same reasons, and held by
|
||||
// INTERFACE so uow.CycleDetectorSource is load-bearing rather than decorative.
|
||||
// No checked wrapper: this report is a value whose slice a nil-safe range
|
||||
// walks, so there is no dereference for a misbehaving implementation to turn
|
||||
// into a panic.
|
||||
func (s *Server) cycleDetector(r *http.Request) (issueops.CycleDetector, error) {
|
||||
if s.provider == nil {
|
||||
return s.issueCycles, nil
|
||||
|
|
@ -638,10 +611,9 @@ func (s *Server) claimer(r *http.Request) (issueops.Claimer, error) {
|
|||
//
|
||||
// Same two sources as reader and claimer above, for the same reasons, and held
|
||||
// by INTERFACE so uow.WorkspaceConfigSource is load-bearing rather than
|
||||
// decorative. It needs no checked wrapper: both settings handlers read VALUES
|
||||
// out of the result, so there is no pointer for a caller-supplied role to hand
|
||||
// back nil in — which is exactly what checkedReader and checkedClaimer exist
|
||||
// to make safe.
|
||||
// decorative. No checked wrapper: both settings handlers read VALUES out of the
|
||||
// result, so there is no pointer for a caller-supplied role to hand back nil
|
||||
// in.
|
||||
func (s *Server) workspaceConfig(r *http.Request) (issueops.WorkspaceConfig, error) {
|
||||
if s.provider == nil {
|
||||
return s.settings, nil
|
||||
|
|
@ -652,14 +624,10 @@ func (s *Server) workspaceConfig(r *http.Request) (issueops.WorkspaceConfig, err
|
|||
|
||||
// edgeReader returns the guarded stored-edge surface for one request.
|
||||
//
|
||||
// It is the third of the same shape, for the same reasons: the configured role
|
||||
// on the roles source, and on the provider source one built per request so its
|
||||
// units of work are timed into THIS request's log line, held by INTERFACE so
|
||||
// uow.EdgeReaderSource is load-bearing rather than decorative.
|
||||
//
|
||||
// There is no checked wrapper here, and roles.go says why: this role answers
|
||||
// with a VALUE, so no handler dereferences a pointer it returned. checkedReader
|
||||
// exists for Get alone.
|
||||
// Same two sources as reader() and claimer(), for the same reasons, and held by
|
||||
// INTERFACE so uow.EdgeReaderSource is load-bearing rather than decorative. No
|
||||
// checked wrapper: this role answers with a VALUE, so no handler dereferences a
|
||||
// pointer it returned — checkedReader exists for Get alone.
|
||||
func (s *Server) edgeReader(r *http.Request) (issueops.EdgeReader, error) {
|
||||
if s.provider == nil {
|
||||
return s.issueEdges, nil
|
||||
|
|
@ -669,15 +637,10 @@ func (s *Server) edgeReader(r *http.Request) (issueops.EdgeReader, error) {
|
|||
}
|
||||
|
||||
// blockingAnnotator returns the derived blocking-decoration surface for one
|
||||
// request, on the same terms as every role above: the configured role on the
|
||||
// roles source, one built per request on the provider source so the unit of
|
||||
// work the annotation opens lands in THIS request's uow_ms, and held by
|
||||
// INTERFACE so uow.BlockingAnnotatorSource is load-bearing rather than
|
||||
// decorative.
|
||||
//
|
||||
// It goes out UNWRAPPED, for the reason edgeReader's answer does: this role
|
||||
// answers with a VALUE, so no handler dereferences a pointer it returned, and
|
||||
// checkedReader exists for Get alone.
|
||||
// request, on the same terms as every role above and held by INTERFACE so
|
||||
// uow.BlockingAnnotatorSource is load-bearing rather than decorative. It goes
|
||||
// out UNWRAPPED for the reason edgeReader's answer does: this role answers with
|
||||
// a VALUE, and checkedReader exists for Get alone.
|
||||
func (s *Server) blockingAnnotator(r *http.Request) (issueops.BlockingAnnotator, error) {
|
||||
if s.provider == nil {
|
||||
return s.issueBlocking, nil
|
||||
|
|
@ -688,14 +651,10 @@ func (s *Server) blockingAnnotator(r *http.Request) (issueops.BlockingAnnotator,
|
|||
|
||||
// treeWalker returns the guarded dependency-tree surface for one request.
|
||||
//
|
||||
// Built the same two ways as its siblings and for the same reasons: the
|
||||
// configured role on the roles source, and on the provider source one built per
|
||||
// request so its unit of work lands in THIS request's log line, held by
|
||||
// INTERFACE so uow.TreeWalkerSource is load-bearing rather than decorative.
|
||||
//
|
||||
// No checked wrapper, for the reason cycleDetector gives: this role answers with
|
||||
// a VALUE whose slice a nil-safe range walks, so there is no pointer for a
|
||||
// misbehaving implementation to turn into a panic.
|
||||
// Built the same two ways as its siblings and for the same reasons, held by
|
||||
// INTERFACE so uow.TreeWalkerSource is load-bearing rather than decorative. No
|
||||
// checked wrapper, for the reason cycleDetector gives: this role answers with a
|
||||
// VALUE whose slice a nil-safe range walks.
|
||||
func (s *Server) treeWalker(r *http.Request) (issueops.TreeWalker, error) {
|
||||
if s.provider == nil {
|
||||
return s.issueTree, nil
|
||||
|
|
@ -704,18 +663,13 @@ func (s *Server) treeWalker(r *http.Request) (issueops.TreeWalker, error) {
|
|||
return src.TreeWalker()
|
||||
}
|
||||
|
||||
// readyCounter returns the ready-count surface for one request.
|
||||
// readyCounter returns the ready-count surface for one request, on the same
|
||||
// terms as every role above and held by INTERFACE so uow.ReadyCounterSource is
|
||||
// load-bearing rather than decorative.
|
||||
//
|
||||
// It is the third role this server hands a handler, and the read-side twin of
|
||||
// the two above in every respect: the configured role on the roles source, one
|
||||
// built per request on the provider source so the unit of work the count opens
|
||||
// lands in THIS request's uow_ms, and held by INTERFACE so
|
||||
// uow.ReadyCounterSource is load-bearing rather than decorative.
|
||||
//
|
||||
// It goes out UNWRAPPED, and that is the difference worth stating. checkedReader
|
||||
// and checkedClaimer exist because their handlers dereference a POINTER a role
|
||||
// returned; CountReady answers with a value, so there is no dereference to make
|
||||
// safe and a wrapper would be ceremony that reads like a guarantee.
|
||||
// It goes out UNWRAPPED. checkedReader and checkedClaimer exist because their
|
||||
// handlers dereference a POINTER a role returned; CountReady answers with a
|
||||
// value, so a wrapper would be ceremony that reads like a guarantee.
|
||||
func (s *Server) readyCounter(r *http.Request) (issueops.ReadyCounter, error) {
|
||||
if s.provider == nil {
|
||||
return s.issueReadyCounter, nil
|
||||
|
|
@ -725,14 +679,10 @@ func (s *Server) readyCounter(r *http.Request) (issueops.ReadyCounter, error) {
|
|||
}
|
||||
|
||||
// querier returns the boolean-query surface for one request, on the same terms
|
||||
// as every role above: the configured role on the roles source, one built per
|
||||
// request on the provider source so the unit of work the query opens lands in
|
||||
// THIS request's uow_ms, and held by INTERFACE so uow.QuerierSource is
|
||||
// load-bearing rather than decorative.
|
||||
//
|
||||
// It goes out UNWRAPPED, like the counter and unlike checkedReader: the handler
|
||||
// dereferences no pointer this role returned — a page is a value carrying a
|
||||
// slice — so there is nothing for a wrapper to make safe.
|
||||
// as every role above and held by INTERFACE so uow.QuerierSource is
|
||||
// load-bearing rather than decorative. It goes out UNWRAPPED, like the counter
|
||||
// and unlike checkedReader: a page is a value carrying a slice, so there is
|
||||
// nothing for a wrapper to make safe.
|
||||
func (s *Server) querier(r *http.Request) (issueops.Querier, error) {
|
||||
if s.provider == nil {
|
||||
return s.issueQuerier, nil
|
||||
|
|
@ -741,12 +691,10 @@ func (s *Server) querier(r *http.Request) (issueops.Querier, error) {
|
|||
return src.Querier()
|
||||
}
|
||||
|
||||
// sweeper returns the guarded bulk-clearance surface for one request.
|
||||
//
|
||||
// The same two sources as every role above, for the same reasons, and held by
|
||||
// INTERFACE so uow.SweeperSource is load-bearing rather than decorative. It
|
||||
// goes out unwrapped for the reason readyCounter does: SweepResult is a VALUE,
|
||||
// so there is no pointer for a caller-supplied role to hand back nil in.
|
||||
// sweeper returns the guarded bulk-clearance surface for one request, on the
|
||||
// same terms as every role above and held by INTERFACE so uow.SweeperSource is
|
||||
// load-bearing rather than decorative. It goes out unwrapped: SweepResult is a
|
||||
// VALUE, so there is no pointer for a caller-supplied role to hand back nil in.
|
||||
//
|
||||
// The role this returns is the ONLY thing standing between a POST body and a
|
||||
// mass delete — the require-a-filter gate, the pinned protection and the
|
||||
|
|
@ -760,12 +708,10 @@ func (s *Server) sweeper(r *http.Request) (issueops.Sweeper, error) {
|
|||
return src.Sweeper()
|
||||
}
|
||||
|
||||
// deleter returns the named-row erasure surface for one request.
|
||||
//
|
||||
// The same two sources as every role above, for the same reasons, and held by
|
||||
// INTERFACE so uow.DeleterSource is load-bearing rather than decorative. It
|
||||
// goes out unwrapped for the reason the sweeper does: DeleteResult is a VALUE,
|
||||
// so there is no pointer for a caller-supplied role to hand back nil in.
|
||||
// deleter returns the named-row erasure surface for one request, on the same
|
||||
// terms as every role above and held by INTERFACE so uow.DeleterSource is
|
||||
// load-bearing rather than decorative. It goes out unwrapped for the reason the
|
||||
// sweeper does: DeleteResult is a VALUE.
|
||||
//
|
||||
// The role this returns is the only thing standing between a POST body and an
|
||||
// orphaned dependency graph — the guard, the id resolution and the reference
|
||||
|
|
@ -779,16 +725,14 @@ func (s *Server) deleter(r *http.Request) (issueops.Deleter, error) {
|
|||
return src.Deleter()
|
||||
}
|
||||
|
||||
// batchCreator returns the batch-create surface for one request, the same two
|
||||
// ways every other role is reached: the configured role on the roles source,
|
||||
// one built per request on the provider source so the unit of work the batch
|
||||
// opens lands in THIS request's uow_ms, and held by INTERFACE so
|
||||
// uow.BatchCreatorSource is load-bearing rather than decorative.
|
||||
// batchCreator returns the batch-create surface for one request, on the same
|
||||
// terms as every role above and held by INTERFACE so uow.BatchCreatorSource is
|
||||
// load-bearing rather than decorative.
|
||||
//
|
||||
// It goes out CHECKED, unlike the ready counter. CreateBatchResult carries a
|
||||
// slice of POINTERS and the response body carries values, so the handler
|
||||
// dereferences every one of them — the same hazard checkedClaimer exists for,
|
||||
// N times over. See checkedBatchCreator.
|
||||
// dereferences every one of them — the checkedClaimer hazard, N times over.
|
||||
// See checkedBatchCreator.
|
||||
func (s *Server) batchCreator(r *http.Request) (issueops.BatchCreator, error) {
|
||||
if s.provider == nil {
|
||||
return checkedBatchCreator{inner: s.issueBatchCreator}, nil
|
||||
|
|
|
|||
|
|
@ -79,18 +79,15 @@ func (emptyDeps) GetIssueDependencyRecords(context.Context, []string) (map[strin
|
|||
return nil, nil
|
||||
}
|
||||
|
||||
// DetectCycleReport answers for a workspace with no cycles, which is what an
|
||||
// empty fake should say. Without it the promoted method on the embedded nil
|
||||
// interface panics, and the provider-backed cycle route would 500 through the
|
||||
// panic recovery rather than answering.
|
||||
// DetectCycleReport answers for a workspace with no cycles. Without it the
|
||||
// promoted method on the embedded nil interface panics, and the provider-backed
|
||||
// cycle route would 500 through the panic recovery rather than answering.
|
||||
func (emptyDeps) DetectCycleReport(context.Context) (issueops.CycleReport, error) {
|
||||
return issueops.CycleReport{Cycles: []issueops.Cycle{}}, nil
|
||||
}
|
||||
|
||||
// WalkDependencyTree answers a one-node tree, for the same reason
|
||||
// DetectCycleReport answers an empty report: without it the promoted method on
|
||||
// the embedded nil interface panics and the provider-backed tree route 500s
|
||||
// through the panic recovery instead of answering.
|
||||
// WalkDependencyTree answers a one-node tree, present for the same reason
|
||||
// DetectCycleReport is.
|
||||
//
|
||||
// A ONE-NODE tree rather than an empty one, because that is what the role
|
||||
// promises for a root with no edges, and a fake that answered nothing would let
|
||||
|
|
|
|||
|
|
@ -13,14 +13,13 @@ import (
|
|||
// The two settings operations. Each one decodes its parameters, hands the whole
|
||||
// request to the workspace-settings role, and shapes the answer onto the wire.
|
||||
//
|
||||
// WHAT IS NOT HERE IS THE POINT, as it is in reads.go. No key is routed to a
|
||||
// source, no value is parsed, no projection is performed, no unit of work is
|
||||
// opened: all of that is inside issueops.WorkspaceConfig's implementation,
|
||||
// which `bd config` reaches through the same accessor. In particular this
|
||||
// surface cannot answer the multi-source questions `bd config show`, `drift`,
|
||||
// `apply` and `validate` ask — three of their five sources are files on the
|
||||
// CLIENT's filesystem — and it therefore publishes no operation that pretends
|
||||
// to.
|
||||
// WHAT IS NOT HERE, as in reads.go: no key is routed to a source, no value is
|
||||
// parsed, no projection is performed, no unit of work is opened. All of that is
|
||||
// inside issueops.WorkspaceConfig's implementation, which `bd config` reaches
|
||||
// through the same accessor. This surface cannot answer the multi-source
|
||||
// questions `bd config show`, `drift`, `apply` and `validate` ask — three of
|
||||
// their five sources are files on the CLIENT's filesystem — so it publishes no
|
||||
// operation that pretends to.
|
||||
//
|
||||
// THE ONE THING THIS FILE DECIDES THAT THE ROLE DOES NOT is redaction, and that
|
||||
// is a wire decision rather than a storage one. The CLI prints stored values in
|
||||
|
|
@ -90,10 +89,8 @@ func (s *Server) handleGetSetting(w http.ResponseWriter, r *http.Request) {
|
|||
// proceed.
|
||||
//
|
||||
// The refusal is a 400 rather than the 404 the issue routes give a malformed
|
||||
// id, and the difference is not cosmetic: this operation HAS no 404, because a
|
||||
// key nothing stored and a key stored empty are one answer here. A 404 would
|
||||
// therefore be a status a client could never map back to anything, where a 400
|
||||
// naming `key` says exactly what was wrong with the request.
|
||||
// id: this operation HAS no 404, because a key nothing stored and a key stored
|
||||
// empty are one answer here.
|
||||
//
|
||||
// A control character is refused rather than looked up because a percent-escape
|
||||
// in the path decodes to one, and a key carrying a newline could only have come
|
||||
|
|
@ -115,10 +112,10 @@ func (s *Server) settingKey(w http.ResponseWriter, r *http.Request) (string, boo
|
|||
// wireSetting projects one stored setting onto the wire, withholding the value
|
||||
// when the KEY marks the setting as credential-bearing.
|
||||
//
|
||||
// The predicate is internal/config's, unchanged and not re-implemented: it is
|
||||
// the same rule `bd config set` uses to refuse writing a secret into a
|
||||
// git-tracked file, so the set of keys this surface protects and the set the
|
||||
// CLI warns about cannot drift apart. It is a decision about the key ALONE — no
|
||||
// The predicate is internal/config's, not re-implemented: it is the same rule
|
||||
// `bd config set` uses to refuse writing a secret into a git-tracked file, so
|
||||
// the set of keys this surface protects and the set the CLI warns about cannot
|
||||
// drift apart. It is a decision about the key ALONE — no
|
||||
// value is inspected — which is stated on the wire in `Setting.redacted` so
|
||||
// that no operator concludes a credential stored under an innocuous name is
|
||||
// covered by it.
|
||||
|
|
|
|||
|
|
@ -10,21 +10,17 @@ import (
|
|||
// The summary operation. It decodes two parameters, hands the whole request to
|
||||
// the summary role, and shapes the answer onto the wire.
|
||||
//
|
||||
// WHAT IS NOT HERE IS THE POINT, exactly as in reads.go. No filter is built,
|
||||
// no assignee predicate is assembled, no ready-work query is issued and no
|
||||
// status fold is performed: all of that is inside issueops.StatsReporter's
|
||||
// implementation, which `bd status` reaches through the same accessor on both
|
||||
// of its routes. The fold in particular is the thing worth keeping out of a
|
||||
// handler — it is where "your work" is DEFINED, and a second copy of it here
|
||||
// would be a second definition that nothing compares against the first.
|
||||
// No filter is built, no assignee predicate is assembled, no ready-work query
|
||||
// is issued and no status fold is performed: all of that is inside
|
||||
// issueops.StatsReporter. The fold in particular is where "your work" is
|
||||
// DEFINED, and a second copy here would be a second definition that nothing
|
||||
// compares against the first.
|
||||
//
|
||||
// WHICH METHOD IS TRANSPORT'S CALL, and it is the only decision this file
|
||||
// makes about meaning: an absent `assignee` is the workspace-wide question, a
|
||||
// present one is the actor question, and an EMPTY one is neither, so it is
|
||||
// refused here rather than passed down. The role would refuse it too
|
||||
// (ErrValidation), but a 400 that names the parameter is what a client can act
|
||||
// on, and the document says the workspace-wide question is asked by omitting
|
||||
// the parameter rather than by emptying it.
|
||||
// WHICH METHOD IS TRANSPORT'S CALL, and it is the only decision this file makes
|
||||
// about meaning: an absent `assignee` is the workspace-wide question, a present
|
||||
// one is the actor question, and an EMPTY one is neither, so it is refused here
|
||||
// rather than passed down. The role would refuse it too (ErrValidation), but a
|
||||
// 400 that names the parameter is what a client can act on.
|
||||
|
||||
// handleStats answers GET /v0/beads/stats.
|
||||
func (s *Server) handleStats(w http.ResponseWriter, r *http.Request) {
|
||||
|
|
@ -35,8 +31,8 @@ func (s *Server) handleStats(w http.ResponseWriter, r *http.Request) {
|
|||
|
||||
// Supplied-but-empty is distinguishable from absent only at the raw values:
|
||||
// q.str answers "" for both. The refusal goes through the query's own
|
||||
// first-refusal slot so a request that is also malformed elsewhere reports
|
||||
// one parameter rather than depending on read order.
|
||||
// first-refusal slot so a request malformed elsewhere too reports one
|
||||
// parameter rather than depending on read order.
|
||||
if assignee == "" && r.URL.Query().Has("assignee") {
|
||||
q.invalid("assignee", "an assignee must not be empty; omit the parameter for the workspace-wide summary")
|
||||
}
|
||||
|
|
@ -56,7 +52,7 @@ func (s *Server) handleStats(w http.ResponseWriter, r *http.Request) {
|
|||
// skip_blocked is not forwarded, and there is nothing to forward it
|
||||
// to: AssigneeStatsRequest has no such field, because that answer
|
||||
// computes both numbers by a route with no fast path. The document
|
||||
// says the parameter is ignored here; this is where it is ignored.
|
||||
// says the parameter is ignored here.
|
||||
result, err = reporter.AssigneeStats(r.Context(), issueops.AssigneeStatsRequest{Assignee: assignee})
|
||||
} else {
|
||||
result, err = reporter.Stats(r.Context(), issueops.StatsRequest{SkipBlocked: skipBlocked})
|
||||
|
|
@ -70,7 +66,7 @@ func (s *Server) handleStats(w http.ResponseWriter, r *http.Request) {
|
|||
Summary: result.Summary,
|
||||
// DERIVED from the answer, never echoed from the request. skip_blocked
|
||||
// is a hint: a backend with no cheaper path returns the full numbers,
|
||||
// and a flag echoing the request would then tell a client the scan was
|
||||
// and a flag echoing the request would tell a client the scan was
|
||||
// skipped while the numbers beside it prove it was not.
|
||||
BlockedCountSkipped: result.Summary.BlockedIssues == nil,
|
||||
})
|
||||
|
|
|
|||
|
|
@ -12,8 +12,7 @@ import (
|
|||
// pointers, never from the request that asked for the fast path.
|
||||
//
|
||||
// The role here TAKES the hint, which is the half the roles-path route test
|
||||
// cannot show — its reporter answers with a populated count. Both halves matter
|
||||
// because the two shipped backends differ on it.
|
||||
// cannot show. Both halves matter because the two shipped backends differ.
|
||||
func TestStatsReportsTheSkippedScanFromTheAnswer(t *testing.T) {
|
||||
reporter := &roleStats{summary: types.Statistics{TotalIssues: 3, OpenIssues: 2}}
|
||||
ts := newTestServer(t, rolesConfig(Config{Stats: reporter}))
|
||||
|
|
@ -64,8 +63,7 @@ func TestStatsRefusesAnEmptyAssignee(t *testing.T) {
|
|||
}
|
||||
|
||||
// TestStatsRefusesAMalformedSkipBlocked pins the other 400 this operation can
|
||||
// produce on its own, which is why invalid_argument is in its row of the
|
||||
// handler table.
|
||||
// produce on its own.
|
||||
func TestStatsRefusesAMalformedSkipBlocked(t *testing.T) {
|
||||
ts := newTestServer(t, rolesConfig(Config{Stats: &roleStats{}}))
|
||||
|
||||
|
|
|
|||
|
|
@ -41,16 +41,14 @@ var sweepMembers = []string{
|
|||
// handleSweep answers POST /v0/beads/issues:sweep — one of the two DESTRUCTIVE
|
||||
// operations on this surface, the other being issues:delete.
|
||||
//
|
||||
// WHAT THIS HANDLER DOES NOT DO is the whole point of it. It does not decide
|
||||
// which beads are closed, does not match the glob, does not recheck closed_at,
|
||||
// does not protect pinned beads, and — the one that matters most — does not
|
||||
// implement the require-a-filter safety gate. All of that is
|
||||
// issueops.Sweeper, the same library surface `bd prune` calls, so this
|
||||
// endpoint could not erase every closed bead in a workspace by omission even
|
||||
// if a future edit here forgot the rule existed. That is the reason the gate
|
||||
// was moved INTO the role rather than left in the CLI handler that historically
|
||||
// owned it: without it, a second front door is one handler away from an
|
||||
// unguarded mass delete.
|
||||
// WHAT THIS HANDLER DOES NOT DO. It does not decide which beads are closed,
|
||||
// does not match the glob, does not recheck closed_at, does not protect pinned
|
||||
// beads, and — the one that matters most — does not implement the
|
||||
// require-a-filter safety gate. All of that is issueops.Sweeper, the same
|
||||
// library surface `bd prune` calls, so this endpoint could not erase every
|
||||
// closed bead in a workspace by omission even if a future edit here forgot the
|
||||
// rule existed. With the gate in the CLI handler instead, a second front door
|
||||
// would be one handler away from an unguarded mass delete.
|
||||
//
|
||||
// Everything above the role here is argument validation: the media type, the
|
||||
// body shape, and the six members the document publishes.
|
||||
|
|
@ -125,10 +123,9 @@ func (s *Server) sweepRequest(w http.ResponseWriter, r *http.Request) (issueops.
|
|||
// inverted exactly that: locally you opt OUT of protection, remotely you
|
||||
// had to opt IN.
|
||||
//
|
||||
// The cost the default now accepts is a full scan of the not-done set and
|
||||
// its comments. A caller that wants the cheaper sweep asks for it by
|
||||
// sending `protect_referenced: false`, which is the request that should be
|
||||
// the deliberate one.
|
||||
// The cost is a full scan of the not-done set and its comments. A caller
|
||||
// that wants the cheaper sweep asks for it by sending
|
||||
// `protect_referenced: false`.
|
||||
request.ProtectReferenced = true
|
||||
|
||||
raw, ok := members[sweepTierMember]
|
||||
|
|
@ -145,8 +142,8 @@ func (s *Server) sweepRequest(w http.ResponseWriter, r *http.Request) (issueops.
|
|||
}
|
||||
// The enum check uses the GENERATED validator, which is derived from the
|
||||
// document rather than a second hand-written copy of the vocabulary. The
|
||||
// role refuses an unrecognized tier too — this is here so the refusal can
|
||||
// name the member, not because the role's is in doubt.
|
||||
// role refuses an unrecognized tier too; this is here so the refusal can
|
||||
// name the member.
|
||||
if !apigen.SweepRequestTier(*tier).Valid() {
|
||||
s.fail(w, r, InvalidArgument(sweepTierMember, ReasonInvalidValue,
|
||||
"`"+sweepTierMember+"` must be \"ephemeral\" or \"durable\""))
|
||||
|
|
@ -162,8 +159,8 @@ func (s *Server) sweepRequest(w http.ResponseWriter, r *http.Request) (issueops.
|
|||
return issueops.SweepRequest{}, false
|
||||
}
|
||||
// The claim's rules, unchanged: trim, then refuse empty, over-long and
|
||||
// any control character. `param` reads "actor" there too, which is what
|
||||
// makes the two operations one vocabulary for a client.
|
||||
// any control character. `param` reads "actor" there too, so the two
|
||||
// operations are one vocabulary for a client.
|
||||
trimmed, res := validateActor(*value)
|
||||
if res != nil {
|
||||
s.fail(w, r, *res)
|
||||
|
|
@ -229,15 +226,12 @@ func sweepMemberList() string {
|
|||
// failSweepErr answers a failed sweep.
|
||||
//
|
||||
// issueops.ErrValidation is mapped to a 400 HERE rather than in ClassifyError,
|
||||
// and this was the FIRST operation to need that: the first whose ROLE performs
|
||||
// request validation the handler does not duplicate — the require-a-filter
|
||||
// gate, the tier vocabulary and the glob are all refused below the wire — so it
|
||||
// was the first place a role's refusal had to reach the client as its own fault
|
||||
// instead of as a 500. Delete, tree, edges, blocking and batch-create each draw
|
||||
// the same line in their own handler now, for the same reason and deliberately
|
||||
// in the same shape. Widening ClassifyError instead would change what every
|
||||
// other operation returns for an error it has never produced, which is a bigger
|
||||
// claim than any one of these operations is making.
|
||||
// because this operation's ROLE performs request validation the handler does
|
||||
// not duplicate — the require-a-filter gate, the tier vocabulary and the glob
|
||||
// are all refused below the wire. Delete, tree, edges, blocking and batch-create
|
||||
// each draw the same line in their own handler, deliberately in the same shape.
|
||||
// Widening ClassifyError instead would change what every other operation
|
||||
// returns for an error it has never produced.
|
||||
func (s *Server) failSweepErr(w http.ResponseWriter, r *http.Request, err error) {
|
||||
if errors.Is(err, issueops.ErrValidation) {
|
||||
// No `param`: the refusal is about the REQUEST rather than one member
|
||||
|
|
|
|||
|
|
@ -10,11 +10,10 @@ import (
|
|||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// The pins for POST /v0/beads/issues:sweep. The role is the surface under
|
||||
// scrutiny everywhere else in this package's storage tests; what is asserted
|
||||
// here is the WIRE EDGE — that the handler decodes the document's six members
|
||||
// into the role's request faithfully, refuses what the document refuses, and
|
||||
// does not re-implement anything the role owns.
|
||||
// The pins for POST /v0/beads/issues:sweep. What is asserted here is the WIRE
|
||||
// EDGE — that the handler decodes the document's six members into the role's
|
||||
// request faithfully, refuses what the document refuses, and does not
|
||||
// re-implement anything the role owns.
|
||||
|
||||
const sweepPath = "/v0/beads/issues:sweep"
|
||||
|
||||
|
|
@ -23,11 +22,11 @@ func (ts *testServer) sweep(t *testing.T, body string) *http.Response {
|
|||
return ts.claimRequest(t, sweepPath, "application/json", body)
|
||||
}
|
||||
|
||||
// TestSweepPathReachesItsHandler is the routing assertion the claim row's twin
|
||||
// makes: the sweep path is a LITERAL segment registered beside the claim's
|
||||
// wildcard `/v0/beads/issues/{idop}`, and ServeMux precedence is by specificity
|
||||
// rather than by registration order. A 404 or a claim-shaped refusal here would
|
||||
// mean the sweep is being parsed as a claim of an issue named ":sweep".
|
||||
// TestSweepPathReachesItsHandler: the sweep path is a LITERAL segment
|
||||
// registered beside the claim's wildcard `/v0/beads/issues/{idop}`, and ServeMux
|
||||
// precedence is by specificity rather than by registration order. A 404 or a
|
||||
// claim-shaped refusal here would mean the sweep is being parsed as a claim of
|
||||
// an issue named ":sweep".
|
||||
func TestSweepPathReachesItsHandler(t *testing.T) {
|
||||
sweeper := &roleSweeper{result: issueops.SweepResult{Swept: 3}}
|
||||
ts := newTestServer(t, rolesConfig(Config{Sweeper: sweeper}))
|
||||
|
|
@ -45,10 +44,9 @@ func TestSweepPathReachesItsHandler(t *testing.T) {
|
|||
// TestSweepForwardsEveryDocumentedMember is the operation's central pin: each
|
||||
// of the six body members reaches the role's request unchanged.
|
||||
//
|
||||
// It is asserted on the REQUEST the role received rather than on the response,
|
||||
// because a body carrying the right numbers says nothing about which set was
|
||||
// swept — this is the operation where the handler dropping a narrowing member
|
||||
// widens what is erased.
|
||||
// It is asserted on the REQUEST the role received rather than on the response:
|
||||
// a body carrying the right numbers says nothing about which set was swept, and
|
||||
// a handler dropping a narrowing member widens what is erased.
|
||||
func TestSweepForwardsEveryDocumentedMember(t *testing.T) {
|
||||
sweeper := &roleSweeper{}
|
||||
ts := newTestServer(t, rolesConfig(Config{Sweeper: sweeper}))
|
||||
|
|
@ -96,7 +94,7 @@ func TestSweepForwardsEveryDocumentedMember(t *testing.T) {
|
|||
// The dry-run default is the one worth pinning. `dry_run` absent must mean
|
||||
// false — that is what the document says — and a handler that defaulted it the
|
||||
// safe-looking way would make the endpoint silently incapable of deleting
|
||||
// anything, which is a worse failure than it sounds: a caller would retry.
|
||||
// anything.
|
||||
func TestSweepDefaultsTheOptionalMembers(t *testing.T) {
|
||||
sweeper := &roleSweeper{}
|
||||
ts := newTestServer(t, rolesConfig(Config{Sweeper: sweeper}))
|
||||
|
|
@ -119,9 +117,8 @@ func TestSweepDefaultsTheOptionalMembers(t *testing.T) {
|
|||
}
|
||||
|
||||
// TestSweepHonorsAnExplicitProtectReferencedFalse is the other half of the
|
||||
// default: opting OUT still works, and it has to be spelled. Without this the
|
||||
// defaults test alone could be satisfied by a handler that ignored the member
|
||||
// entirely and hard-coded protection on.
|
||||
// default: opting OUT still works. Without this the defaults test alone could be
|
||||
// satisfied by a handler that hard-coded protection on.
|
||||
func TestSweepHonorsAnExplicitProtectReferencedFalse(t *testing.T) {
|
||||
sweeper := &roleSweeper{}
|
||||
ts := newTestServer(t, rolesConfig(Config{Sweeper: sweeper}))
|
||||
|
|
@ -138,10 +135,9 @@ func TestSweepHonorsAnExplicitProtectReferencedFalse(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestSweepPublishesTheWholeResult pins the projection, which exists because
|
||||
// SweepResult is deliberately not x-go-type-pinned: there is no compile-time
|
||||
// tie between the role's result and this body, so a field added to the role and
|
||||
// forgotten here would vanish from the wire in silence.
|
||||
// TestSweepPublishesTheWholeResult pins the projection. SweepResult is
|
||||
// deliberately not x-go-type-pinned, so a field added to the role and forgotten
|
||||
// here would vanish from the wire in silence.
|
||||
func TestSweepPublishesTheWholeResult(t *testing.T) {
|
||||
sweeper := &roleSweeper{result: issueops.SweepResult{
|
||||
DryRun: true,
|
||||
|
|
@ -213,8 +209,8 @@ func TestSweepOmitsAnEmptyReferencedSample(t *testing.T) {
|
|||
}
|
||||
|
||||
// TestSweepRefusesTheDocumentedBodies walks the 400 table. Every case names the
|
||||
// member it is about in `param`, which is the whole reason the handler decodes
|
||||
// member by member instead of unmarshaling the generated struct.
|
||||
// member it is about in `param`, which is why the handler decodes member by
|
||||
// member instead of unmarshaling the generated struct.
|
||||
func TestSweepRefusesTheDocumentedBodies(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
|
|
@ -259,12 +255,10 @@ func TestSweepRefusesTheDocumentedBodies(t *testing.T) {
|
|||
}
|
||||
|
||||
// TestSweepPublishesTheRolesRefusalAsA400 is the reason failSweepErr exists.
|
||||
//
|
||||
// The require-a-filter gate, the tier vocabulary and the glob are all refused
|
||||
// BELOW the wire, by issueops.Sweeper — that is what makes this endpoint
|
||||
// incapable of an unguarded mass delete. A role refusal reaching the client as
|
||||
// a 500 would tell it the server was broken when the request was, and would
|
||||
// hide the one sentence that says what to send instead.
|
||||
// a 500 would hide the one sentence that says what to send instead.
|
||||
func TestSweepPublishesTheRolesRefusalAsA400(t *testing.T) {
|
||||
// The sentinel has to MATCH, not merely be mentioned in the text.
|
||||
sweeper := &roleSweeper{err: wrapValidation("a durable sweep requires a closed-before cutoff or an id pattern")}
|
||||
|
|
@ -290,10 +284,9 @@ func TestSweepPublishesTheRolesRefusalAsA400(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestSweepRefusesAForeignMediaType: the CSRF control the claim documents
|
||||
// applies here for a sharper reason. A JSON content type is not CORS-"simple",
|
||||
// TestSweepRefusesAForeignMediaType: a JSON content type is not CORS-"simple",
|
||||
// so a cross-origin sweep always triggers a preflight this server never
|
||||
// approves; accepting text/plain would let an attacker's page drive a mass
|
||||
// approves. Accepting text/plain would let an attacker's page drive a mass
|
||||
// delete from any browser on the host.
|
||||
func TestSweepRefusesAForeignMediaType(t *testing.T) {
|
||||
sweeper := &roleSweeper{}
|
||||
|
|
|
|||
|
|
@ -15,23 +15,18 @@ import (
|
|||
// CONSTRUCTOR beats an accessor: `uow.NewSweeper(p)` binds the role to the
|
||||
// wrapper, so every unit of work it opens goes through timedProvider.NewUOW and
|
||||
// lands in the request's uow_ms. `p.inner.Sweeper()` would return a role bound
|
||||
// to the untimed provider, and the measurement would silently read zero. The
|
||||
// comment on IssueReader records that a reviewer once proposed exactly that
|
||||
// change "for symmetry".
|
||||
// to the untimed provider, and the measurement would silently read zero — a
|
||||
// change the comment on IssueReader records a reviewer proposing "for
|
||||
// symmetry".
|
||||
//
|
||||
// WHY THIS TEST IS STRUCTURAL. The behavioral pins are per route: they need a
|
||||
// provider fake with a measurable delay, a valid request for that operation,
|
||||
// and a log line to read. Two of the thirteen roles have one
|
||||
// (TestAReadRouteTimesTheUnitsOfWorkItsReaderOpens,
|
||||
// TestAClaimTimesTheUnitsOfWorkItsClaimerOpens). The other eleven — including
|
||||
// all three WRITE roles, whose transactions are the longest this server runs —
|
||||
// had none, so the symmetric refactor could be applied to them with the whole
|
||||
// package still green.
|
||||
// WHY THIS TEST IS STRUCTURAL. The behavioral pins are per route, and only two
|
||||
// of the thirteen roles have one. The other eleven — including all three WRITE
|
||||
// roles, whose transactions are the longest this server runs — had none, so the
|
||||
// symmetric refactor could be applied to them with the whole package green.
|
||||
//
|
||||
// Reading the binding off the AST covers all thirteen at once and cannot be
|
||||
// satisfied by a passing suite. It is deliberately narrow: it says nothing
|
||||
// about what the roles DO, only that each is constructed over the receiver.
|
||||
// Keep the behavioral pins; this is not a replacement for them.
|
||||
// Reading the binding off the AST covers all thirteen at once. It says nothing
|
||||
// about what the roles DO, only that each is constructed over the receiver, so
|
||||
// it is not a replacement for the behavioral pins.
|
||||
func TestEveryTimedProviderAccessorBindsToTheWrapper(t *testing.T) {
|
||||
fset := token.NewFileSet()
|
||||
file, err := parser.ParseFile(fset, "claim.go", nil, 0)
|
||||
|
|
|
|||
|
|
@ -15,20 +15,16 @@ import (
|
|||
//
|
||||
// It is a FRONT-DOOR default rather than a role default on purpose: the role
|
||||
// refuses a zero depth outright, because an uninitialized recursive walk must
|
||||
// not mean "walk the whole graph". Each front door supplies its own visible
|
||||
// default instead, and the two happen to agree because the number is the same
|
||||
// safety limit.
|
||||
// not mean "walk the whole graph".
|
||||
const defaultTreeDepth = 50
|
||||
|
||||
// handleDependencyTree answers GET /v0/beads/dependencies/tree.
|
||||
//
|
||||
// WHAT IS NOT HERE IS THE POINT, as it is for the cycle report next door. No
|
||||
// graph is walked, no depth is counted, no visited set is kept, no `both` merge
|
||||
// is performed and no status prune is applied: every one of those is inside
|
||||
// issueops.TreeWalker's implementation, which `bd dep tree` reaches through the
|
||||
// same accessor. A handler that merged the two directions for itself would be a
|
||||
// second definition of what `direction=both` means, and the two surfaces would
|
||||
// drift the first time either was edited.
|
||||
// No graph is walked, no depth counted, no visited set kept, no `both` merge
|
||||
// performed and no status prune applied: all of that is inside
|
||||
// issueops.TreeWalker, which `bd dep tree` reaches through the same accessor. A
|
||||
// handler that merged the two directions for itself would be a second
|
||||
// definition of what `direction=both` means.
|
||||
//
|
||||
// The element type is an ALIAS of types.TreeNode — the same struct the CLI's
|
||||
// --json marshals — so there is no second wire struct here and there must never
|
||||
|
|
@ -51,10 +47,9 @@ func (s *Server) handleDependencyTree(w http.ResponseWriter, r *http.Request) {
|
|||
return
|
||||
}
|
||||
// `root_id` is required by the document, and its absence is refused HERE
|
||||
// rather than left to the role. The role would refuse it too — an empty root
|
||||
// is ErrValidation — but a missing REQUIRED PARAMETER and a parameter sent
|
||||
// empty are one fact on the wire and the client's recovery is the same, so
|
||||
// naming the parameter is worth more than forwarding the role's prose.
|
||||
// rather than left to the role: a missing required parameter and one sent
|
||||
// empty are the same fact on the wire, and naming the parameter is worth
|
||||
// more than forwarding the role's prose.
|
||||
if req.RootID == "" {
|
||||
requestInfo(r.Context()).refuse("root_id")
|
||||
s.fail(w, r, InvalidArgument("root_id", ReasonInvalidValue, "root_id is required and must be an exact issue id"))
|
||||
|
|
@ -75,10 +70,9 @@ func (s *Server) handleDependencyTree(w http.ResponseWriter, r *http.Request) {
|
|||
writeJSON(w, apigen.DependencyTreePage{
|
||||
Items: wireTreeNodes(result.Nodes),
|
||||
// Always false: this operation takes no limit, so nothing truncates the
|
||||
// answer — `max_depth` bounds the DESCENT instead. It is emitted rather
|
||||
// than omitted because the document types it as required, and because a
|
||||
// client must not have to tell "not truncated" from "this server does not
|
||||
// say".
|
||||
// answer — `max_depth` bounds the DESCENT instead. Emitted rather than
|
||||
// omitted so a client never has to tell "not truncated" from "this
|
||||
// server does not say".
|
||||
HasMore: false,
|
||||
})
|
||||
}
|
||||
|
|
@ -92,15 +86,13 @@ func (s *Server) handleDependencyTree(w http.ResponseWriter, r *http.Request) {
|
|||
// The 400 names `direction` or `max_depth` rather than always naming the same
|
||||
// parameter, because `param` is what a client dispatches on and the two have
|
||||
// different recoveries. Which one comes from the REQUEST the handler still
|
||||
// holds, the way failEdgeReadErr reads its own: only a non-positive depth can
|
||||
// have produced a depth refusal, and only a value outside the closed set a
|
||||
// direction one.
|
||||
// holds: only a non-positive depth can have produced a depth refusal, and only
|
||||
// a value outside the closed set a direction one.
|
||||
//
|
||||
// Both of those are cases the handler could almost have caught itself — q.oneOf
|
||||
// already refuses an unknown direction — and that is deliberate rather than
|
||||
// redundant. The role is the definition of the vocabulary; this mapping exists
|
||||
// so that a refusal reaching the wire from BELOW the handler still arrives
|
||||
// attributed instead of as an unattributed 400.
|
||||
// The handler could almost have caught both itself — q.oneOf already refuses an
|
||||
// unknown direction — but the role is the definition of the vocabulary, and
|
||||
// this mapping is what makes a refusal from BELOW the handler arrive attributed
|
||||
// rather than as an unattributed 400.
|
||||
func (s *Server) failTreeWalkErr(w http.ResponseWriter, r *http.Request, err error, req issueops.WalkTreeRequest) {
|
||||
switch {
|
||||
case errors.Is(err, storage.ErrNotFound):
|
||||
|
|
@ -126,9 +118,8 @@ func (s *Server) failTreeWalkErr(w http.ResponseWriter, r *http.Request, err err
|
|||
// pointers and does nothing else.
|
||||
//
|
||||
// It exists for the one thing that is not free: the document says `items` is an
|
||||
// empty array and never null, and the role's slice is already empty rather than
|
||||
// nil for a successful call. Making the guarantee here as well means the wire
|
||||
// promise does not depend on the role keeping its own.
|
||||
// empty array and never null. Making that guarantee here means the wire promise
|
||||
// does not depend on the role keeping its own.
|
||||
func wireTreeNodes(nodes []*issueops.TreeNode) []apigen.TreeNode {
|
||||
out := make([]apigen.TreeNode, 0, len(nodes))
|
||||
for _, node := range nodes {
|
||||
|
|
|
|||
|
|
@ -16,8 +16,7 @@ import (
|
|||
const treePath = "/v0/beads/dependencies/tree"
|
||||
|
||||
// treeServer binds a roles-backed server whose tree walker answers with walker.
|
||||
// The rest of the role set is inert: this operation touches none of it, but
|
||||
// Listen requires a COMPLETE source, so rolesConfig fills them in.
|
||||
// Listen requires a COMPLETE source, so rolesConfig fills in the rest.
|
||||
func treeServer(t *testing.T, walker *roleTreeWalker) *testServer {
|
||||
t.Helper()
|
||||
return newTestServer(t, rolesConfig(Config{TreeWalker: walker}))
|
||||
|
|
@ -34,11 +33,10 @@ func treeNode(id string, depth int, parentID string, edge types.DependencyType)
|
|||
|
||||
// TestTreeCarriesTheRolesAnswerToTheWire is the whole point of the operation:
|
||||
// the body is the role's node list projected onto the envelope, in order, with
|
||||
// no shaping in between.
|
||||
//
|
||||
// It asserts the JSON rather than the Go value because the alias is what makes
|
||||
// them the same thing — apigen.TreeNode IS types.TreeNode — so the only way for
|
||||
// this to fail is a handler that reordered, renamed or dropped something.
|
||||
// no shaping in between. It asserts the JSON rather than the Go value because
|
||||
// the alias is what makes them the same thing — apigen.TreeNode IS
|
||||
// types.TreeNode — so the only way for this to fail is a handler that reordered,
|
||||
// renamed or dropped something.
|
||||
func TestTreeCarriesTheRolesAnswerToTheWire(t *testing.T) {
|
||||
ts := treeServer(t, &roleTreeWalker{result: issueops.TreeResult{Nodes: []*types.TreeNode{
|
||||
treeNode("bd-root", 0, "", ""),
|
||||
|
|
@ -82,8 +80,7 @@ func TestTreeCarriesTheRolesAnswerToTheWire(t *testing.T) {
|
|||
}
|
||||
}
|
||||
// The root carries no edge, so `edge_from_parent` is omitted rather than
|
||||
// emitted empty — the same "absent means not set" rule the rest of this
|
||||
// surface reads.
|
||||
// emitted empty.
|
||||
root, _ := items[0].(map[string]any)
|
||||
if _, present := root["edge_from_parent"]; present {
|
||||
t.Errorf("the root carries an edge_from_parent key (%#v); it was reached from nothing", root["edge_from_parent"])
|
||||
|
|
@ -170,8 +167,8 @@ func TestTreeAnswersAnEmptyArrayRatherThanNull(t *testing.T) {
|
|||
}
|
||||
|
||||
// TestTreeRefusesTheDocumentedBadRequests pins each 400 the operation can raise
|
||||
// AND which parameter it attributes it to, because `param` is what a client
|
||||
// dispatches on and the three have different recoveries.
|
||||
// AND which parameter it attributes it to: `param` is what a client dispatches
|
||||
// on, and the three have different recoveries.
|
||||
func TestTreeRefusesTheDocumentedBadRequests(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
|
|
@ -253,8 +250,7 @@ func TestTreeAnswers404ForARootThatIsNotThere(t *testing.T) {
|
|||
}
|
||||
|
||||
// TestTreeMapsARoleFailureThroughTheOneErrorMapping keeps the walk on the same
|
||||
// classification every other route uses, rather than inventing a status for a
|
||||
// graph read.
|
||||
// classification every other route uses.
|
||||
func TestTreeMapsARoleFailureThroughTheOneErrorMapping(t *testing.T) {
|
||||
ts := treeServer(t, &roleTreeWalker{err: errors.New("backend is unreachable")})
|
||||
|
||||
|
|
@ -269,8 +265,7 @@ func TestTreeMapsARoleFailureThroughTheOneErrorMapping(t *testing.T) {
|
|||
|
||||
// TestTreeReachesTheProviderAccessor covers the OTHER database source: the
|
||||
// handler must reach the role through uow.TreeWalkerSource on the timed
|
||||
// provider, not through a constructor and not through the roles fields, which
|
||||
// are nil on this server.
|
||||
// provider, not through the roles fields, which are nil on this server.
|
||||
func TestTreeReachesTheProviderAccessor(t *testing.T) {
|
||||
ts := newTestServer(t, Config{})
|
||||
|
||||
|
|
@ -280,8 +275,7 @@ func TestTreeReachesTheProviderAccessor(t *testing.T) {
|
|||
if strings.Contains(ts.stderr.String(), "event=panic") {
|
||||
t.Fatalf("the handler panicked; it read a role this source does not set:\n%s", ts.stderr.String())
|
||||
}
|
||||
// What the fake provider answers is its own business; that the request got
|
||||
// past the accessor is the assertion.
|
||||
// That the request got past the accessor is the assertion.
|
||||
if resp.StatusCode == http.StatusInternalServerError {
|
||||
t.Fatalf("status = 500 from the provider-backed source: %s", readAll(t, resp))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,10 +14,9 @@ import (
|
|||
// embedded wiring is the same body on a different engine.
|
||||
//
|
||||
// The cases are subtests of one parent so the whole role suite shares one store
|
||||
// and one copy-on-write branch: each Run namespaces its ids under the fixture
|
||||
// prefix, and the history cases take a before/after delta, which is only
|
||||
// meaningful while the subtests run sequentially. setupTestStore already marks
|
||||
// the PARENT parallel; no subtest here calls t.Parallel.
|
||||
// and one copy-on-write branch: the history cases take a before/after delta,
|
||||
// which is only meaningful while the subtests run sequentially. setupTestStore
|
||||
// already marks the PARENT parallel; no subtest here calls t.Parallel.
|
||||
func TestBatchCreatorContract(t *testing.T) {
|
||||
fixture, ctx, cleanup := newDoltBatchCreatorFixture(t, "bcr")
|
||||
defer cleanup()
|
||||
|
|
|
|||
|
|
@ -19,10 +19,7 @@ func (s *DoltStore) BlockingAnnotator() (issueops.BlockingAnnotator, error) {
|
|||
//
|
||||
// It is unexported for the reason newEdgeReader beside it is: a command holds
|
||||
// the storage.DoltStorage interface and reaches the role through the accessor
|
||||
// above, which is where each decorator adds its layer. There is no shared
|
||||
// constructor for the cmd-bd-role-constructors depguard rule to deny here
|
||||
// because the shared body is an InTx function — it needs a transaction this
|
||||
// store owns, so no front door can reach it at all.
|
||||
// above, which is where each decorator adds its layer.
|
||||
func newBlockingAnnotator(store *DoltStore) (issueops.BlockingAnnotator, error) {
|
||||
if store == nil {
|
||||
return nil, &storage.ErrUnsupported{Op: "newBlockingAnnotator", Backend: "nil"}
|
||||
|
|
|
|||
|
|
@ -26,9 +26,6 @@ func (s *DoltStore) Bootstrapper() (issueops.Bootstrapper, error) {
|
|||
// one level down instead — this body and the embedded store's are a few lines
|
||||
// each around issueops.BootstrapInTx — and two wrappers over one body is still
|
||||
// ONE vote, which the conformance contract says out loud.
|
||||
//
|
||||
// A front door cannot construct this: the type is unexported and the accessor
|
||||
// is the only door.
|
||||
type bootstrapper struct{ store *DoltStore }
|
||||
|
||||
var _ issueops.Bootstrapper = (*bootstrapper)(nil)
|
||||
|
|
|
|||
|
|
@ -12,12 +12,11 @@ import (
|
|||
// against the server-backed store.
|
||||
//
|
||||
// The cases are subtests of one parent so the whole role suite shares one store
|
||||
// and one copy-on-write branch. Sharing matters here the way it does for the
|
||||
// settings and version roles and not the way it does for the issue roles: the
|
||||
// identity is GLOBAL to a workspace and cannot be namespaced under the fixture
|
||||
// prefix, so every case seeds it explicitly instead of relying on what the case
|
||||
// before it left. setupTestStore already marks the PARENT parallel; no subtest
|
||||
// here calls t.Parallel, because two of them take a log delta.
|
||||
// and one copy-on-write branch. The identity is GLOBAL to a workspace and
|
||||
// cannot be namespaced under the fixture prefix, so every case seeds it
|
||||
// explicitly instead of relying on what the case before it left. setupTestStore
|
||||
// already marks the PARENT parallel; no subtest here calls t.Parallel, because
|
||||
// two of them take a log delta.
|
||||
func TestBootstrapperContract(t *testing.T) {
|
||||
fixture, ctx, cleanup := newDoltBootstrapperFixture(t)
|
||||
defer cleanup()
|
||||
|
|
@ -80,11 +79,10 @@ func newDoltBootstrapperFixture(t *testing.T) (conformance.BootstrapperFixture,
|
|||
fixture := conformance.BootstrapperFixture{
|
||||
Bootstrapper: bootstrapper,
|
||||
InitVerifier: verifier,
|
||||
// Past both roles, through the store's own config and metadata seams.
|
||||
// This is the hook the frozen kit cannot supply: it can SET a prefix but
|
||||
// has no way to unset one, and an unidentified substrate is the state a
|
||||
// bootstrap needs to be reachable at all on a database setupTestStore
|
||||
// already initialized.
|
||||
// Past both roles, through the store's own config and metadata seams:
|
||||
// the frozen kit can SET a prefix but has no way to unset one, and an
|
||||
// unidentified substrate is the state a bootstrap needs on a database
|
||||
// setupTestStore already initialized.
|
||||
SeedIdentity: func(ctx context.Context, prefix, projectID string) error {
|
||||
if err := store.SetConfig(ctx, workapi.ConfigKeyIssuePrefix, prefix); err != nil {
|
||||
return err
|
||||
|
|
|
|||
|
|
@ -19,18 +19,13 @@ func (s *DoltStore) CycleDetector() (issueops.CycleDetector, error) {
|
|||
|
||||
// cycleDetector answers the cycle report from one read transaction.
|
||||
//
|
||||
// There is no shared constructor package for this role the way there is for the
|
||||
// count role, and that is not an omission. The work is a graph read plus a
|
||||
// hydration, both of which need a TRANSACTION — the two planes must be read as
|
||||
// one snapshot — and a transaction is not reachable through storage.DoltStorage.
|
||||
// So the sharing happens one level down instead: this body and the embedded
|
||||
// store's are five lines each around issueops.DetectCycleReportInTx, which is
|
||||
// the same function both stores' legacy DetectCycles already call. Two wrappers
|
||||
// over one body is still ONE vote, and the conformance contract says so.
|
||||
//
|
||||
// A front door cannot construct this: the type is unexported and the accessor is
|
||||
// the only door, which is what the cmd-bd-role-constructors depguard rule buys
|
||||
// the roles whose bodies live in an importable package.
|
||||
// There is no shared constructor package for this role: the work is a graph
|
||||
// read plus a hydration, both of which need a TRANSACTION — the two planes must
|
||||
// be read as one snapshot — and a transaction is not reachable through
|
||||
// storage.DoltStorage. The sharing happens one level down instead: this body
|
||||
// and the embedded store's are five lines each around
|
||||
// issueops.DetectCycleReportInTx. Two wrappers over one body is still ONE vote,
|
||||
// and the conformance contract says so.
|
||||
type cycleDetector struct{ store *DoltStore }
|
||||
|
||||
var _ issueops.CycleDetector = (*cycleDetector)(nil)
|
||||
|
|
|
|||
|
|
@ -12,11 +12,10 @@ import (
|
|||
// server-backed store.
|
||||
//
|
||||
// The cases are subtests of one parent so the whole role suite shares one store
|
||||
// and one copy-on-write branch. They are also SEQUENTIAL by necessity rather
|
||||
// than by convention: the report is global, so each case's cycles stay visible
|
||||
// to the ones after it, and every assertion is scoped by member set for that
|
||||
// reason. setupTestStore already marks the PARENT parallel; no subtest here
|
||||
// calls t.Parallel.
|
||||
// and one copy-on-write branch. They are also SEQUENTIAL by necessity: the
|
||||
// report is global, so each case's cycles stay visible to the ones after it and
|
||||
// every assertion is scoped by member set. setupTestStore already marks the
|
||||
// PARENT parallel; no subtest here calls t.Parallel.
|
||||
func TestCycleDetectorContract(t *testing.T) {
|
||||
fixture, ctx, cleanup := newDoltCycleDetectorFixture(t, "cyc")
|
||||
defer cleanup()
|
||||
|
|
@ -65,7 +64,7 @@ func newDoltCycleDetectorFixture(t *testing.T, prefix string) (conformance.Cycle
|
|||
CreateWisp: kit.CreateWisp,
|
||||
// The frozen kit exposes reads only, so the raw write this role's cases
|
||||
// need is supplied here — over the same *sql.DB the kit's QueryScalar
|
||||
// reads through, which on this backend is the test's own branch.
|
||||
// reads through.
|
||||
//
|
||||
// One PINNED CONNECTION for the whole script: the pool would otherwise
|
||||
// hand the inserts a different session than the foreign_key_checks
|
||||
|
|
|
|||
|
|
@ -22,16 +22,12 @@ func (s *DoltStore) Deleter() (issueops.Deleter, error) {
|
|||
|
||||
// deleter erases named rows inside ONE transaction.
|
||||
//
|
||||
// There is no shared constructor package for this role, for the reason sweeper
|
||||
// gives: the work is an existence probe, a guard, a delete and a text rewrite
|
||||
// that must all see one snapshot, and a transaction is not reachable through
|
||||
// storage.DoltStorage. The sharing happens one level down instead — this body
|
||||
// and the embedded store's are a few lines each around
|
||||
// issueops.DeleteInTx — and two wrappers over one body is still ONE vote,
|
||||
// which the conformance contract says out loud.
|
||||
//
|
||||
// A front door cannot construct this: the type is unexported and the accessor
|
||||
// is the only door.
|
||||
// There is no shared constructor package for this role: the work is an
|
||||
// existence probe, a guard, a delete and a text rewrite that must all see one
|
||||
// snapshot, and a transaction is not reachable through storage.DoltStorage. The
|
||||
// sharing happens one level down instead — this body and the embedded store's
|
||||
// are a few lines each around issueops.DeleteInTx — so two wrappers over one
|
||||
// body is still ONE vote.
|
||||
type deleter struct{ store *DoltStore }
|
||||
|
||||
var _ issueops.Deleter = (*deleter)(nil)
|
||||
|
|
@ -48,11 +44,10 @@ var _ issueops.Deleter = (*deleter)(nil)
|
|||
// like a mutation to everything watching the store.
|
||||
//
|
||||
// THE VERSION-CONTROL ENTRY IS ONE PER DELETION, recorded here rather than in
|
||||
// the shared body because only this backend records one at all: the embedded
|
||||
// store commits outside the SQL transaction and the unit-of-work provider
|
||||
// labels its own. A deletion confined to the wisp tables touches only tables
|
||||
// this plane ignores, so DOLT_COMMIT finds nothing to commit and records no
|
||||
// entry — the "at most one" the role promises, not "exactly one".
|
||||
// the shared body because only this backend records one at all. A deletion
|
||||
// confined to the wisp tables touches only tables this plane ignores, so
|
||||
// DOLT_COMMIT finds nothing to commit and records no entry — the "at most one"
|
||||
// the role promises, not "exactly one".
|
||||
func (s *deleter) Delete(ctx context.Context, req issueops.DeleteRequest) (issueops.DeleteResult, error) {
|
||||
if err := workapi.ValidateDeleteRequest(req); err != nil {
|
||||
return issueops.DeleteResult{}, err
|
||||
|
|
@ -79,9 +74,8 @@ func (s *deleter) Delete(ctx context.Context, req issueops.DeleteRequest) (issue
|
|||
if result.Deleted == 0 {
|
||||
return nil
|
||||
}
|
||||
// The same tables a sweep stages, because a delete IS a sweep of a
|
||||
// named set — plus the neighbor rewrite, which lands in `issues` and
|
||||
// is already on the list.
|
||||
// The same tables a sweep stages; the neighbor rewrite lands in
|
||||
// `issues`, which is already on the list.
|
||||
for _, table := range sweptTables {
|
||||
_ = schema.DrainCall(ctx, tx, "CALL DOLT_ADD(?)", table)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,11 +13,10 @@ import (
|
|||
// for a deletion.
|
||||
//
|
||||
// The cases are subtests of one parent so the whole role suite shares one store
|
||||
// and one copy-on-write branch. That sharing is why every case namespaces its
|
||||
// seeds under fixture.IssuePrefix plus its own tag. setupTestStore already
|
||||
// marks the PARENT parallel; no subtest here calls t.Parallel, and
|
||||
// RecordsAtMostOneHistoryEntry takes a before/after delta that is only
|
||||
// meaningful while they run sequentially.
|
||||
// and one copy-on-write branch, which is why every case namespaces its seeds
|
||||
// under fixture.IssuePrefix plus its own tag. setupTestStore already marks the
|
||||
// PARENT parallel; no subtest here calls t.Parallel, because
|
||||
// RecordsAtMostOneHistoryEntry takes a before/after delta.
|
||||
func TestDeleterContract(t *testing.T) {
|
||||
fixture, ctx, cleanup := newDoltDeleterFixture(t, "del")
|
||||
defer cleanup()
|
||||
|
|
|
|||
|
|
@ -16,12 +16,9 @@ func (s *DoltStore) EdgeReader() (issueops.EdgeReader, error) {
|
|||
|
||||
// newEdgeReader returns guarded stored-edge reads backed by store.
|
||||
//
|
||||
// It is unexported, unlike NewIssueRelations beside it: a command holds the
|
||||
// storage.DoltStorage interface and reaches the role through the accessor
|
||||
// above, which is where each decorator adds its layer. There is no shared
|
||||
// constructor for the cmd-bd-role-constructors depguard rule to deny here
|
||||
// because the shared body is an InTx function — it needs a transaction this
|
||||
// store owns, so no front door can reach it at all.
|
||||
// It is unexported, unlike NewIssueRelations beside it: the shared body is an
|
||||
// InTx function that needs a transaction this store owns, so no front door can
|
||||
// reach it at all.
|
||||
func newEdgeReader(store *DoltStore) (issueops.EdgeReader, error) {
|
||||
if store == nil {
|
||||
return nil, &storage.ErrUnsupported{Op: "newEdgeReader", Backend: "nil"}
|
||||
|
|
|
|||
|
|
@ -12,11 +12,10 @@ import (
|
|||
// seam that renders LIMIT without OFFSET.
|
||||
//
|
||||
// The cases are subtests of one parent so the whole role suite shares one store
|
||||
// and one copy-on-write branch: each Run namespaces its ids and its label under
|
||||
// the fixture prefix and scopes its own EXPRESSION to that label, and
|
||||
// WritesNothing takes a before/after history delta, which is only meaningful
|
||||
// while the subtests run sequentially. setupTestStore already marks the PARENT
|
||||
// parallel; no subtest here calls t.Parallel.
|
||||
// and one copy-on-write branch: each Run scopes its own EXPRESSION to a label
|
||||
// under the fixture prefix, and WritesNothing takes a before/after history
|
||||
// delta, which is only meaningful while the subtests run sequentially.
|
||||
// setupTestStore already marks the PARENT parallel; no subtest calls t.Parallel.
|
||||
func TestQuerierContract(t *testing.T) {
|
||||
fixture, ctx, cleanup := newDoltQuerierFixture(t, "qry")
|
||||
defer cleanup()
|
||||
|
|
|
|||
|
|
@ -16,22 +16,15 @@ const oldQueryWindow = 100
|
|||
|
||||
// TestAPredicateQueryFindsAMatchBeyondTheOldWindow is the end-to-end proof of
|
||||
// the defect this role shipped to fix, and it lives HERE — one backend, not the
|
||||
// portable contract — on purpose.
|
||||
//
|
||||
// Making the old window observable needs more than a hundred candidate rows in
|
||||
// one store. That is a few seconds at this backend and would be a few seconds
|
||||
// times three if it were a conformance case, for one bit of information about
|
||||
// arithmetic that is identical in both bodies: they execute the same
|
||||
// workapi.QueryPlan, whose predicate branch carries no row limit at all, and
|
||||
// TestBuildQueryPlanLeavesAPredicateQueryUNBOUNDED pins that in microseconds.
|
||||
// What no unit test can show is that the whole path — plan, SQL, predicate,
|
||||
// page — actually returns the row, so exactly one backend runs it.
|
||||
// portable contract — because making the old window observable needs more than
|
||||
// a hundred candidate rows, which would cost three times as much as a
|
||||
// conformance case for arithmetic already pinned in microseconds by
|
||||
// TestBuildQueryPlanLeavesAPredicateQueryUNBOUNDED.
|
||||
//
|
||||
// THE SHAPE OF THE OLD FAILURE, which is what the seeding reproduces. With
|
||||
// --limit 1 the old code fetched 100 candidate rows and applied the predicate
|
||||
// to those; a match sitting at row 101 of the query's own order was therefore
|
||||
// absent from the page AND unreported by has-more, so the caller was handed an
|
||||
// empty answer to a question with a match in it. The single matching row is
|
||||
// absent from the page AND unreported by has-more. The single matching row is
|
||||
// seeded at the WORST priority so the default order (priority ASC, created
|
||||
// DESC, id ASC) puts it last, behind a full window of rows the predicate
|
||||
// rejects.
|
||||
|
|
|
|||
|
|
@ -11,12 +11,11 @@ import (
|
|||
// server-backed store, which reaches the cheap indexed COUNT(*) path
|
||||
// (internal/workapi/storereadycounter over CountReadyWorkInTx).
|
||||
//
|
||||
// The cases are subtests of one parent so the whole role suite shares one
|
||||
// store and one copy-on-write branch: each Run namespaces its ids and labels
|
||||
// under the fixture prefix and scopes its own request to them, and
|
||||
// WritesNothing takes a before/after history delta, which is only meaningful
|
||||
// while the subtests run sequentially. setupTestStore already marks the PARENT
|
||||
// parallel; no subtest here calls t.Parallel.
|
||||
// The cases are subtests of one parent so the whole role suite shares one store
|
||||
// and one copy-on-write branch. WritesNothing takes a before/after history
|
||||
// delta, which is only meaningful while the subtests run sequentially:
|
||||
// setupTestStore already marks the PARENT parallel, and no subtest here calls
|
||||
// t.Parallel.
|
||||
func TestReadyCounterContract(t *testing.T) {
|
||||
fixture, ctx, cleanup := newDoltReadyCounterFixture(t, "rdc")
|
||||
defer cleanup()
|
||||
|
|
|
|||
|
|
@ -24,34 +24,27 @@ func (s *DoltStore) Sweeper() (issueops.Sweeper, error) {
|
|||
//
|
||||
// There is no shared constructor package for this role, for the reason
|
||||
// cycleDetector gives: the work is a candidate query, a recheck, an optional
|
||||
// reference scan and a delete that must all see one snapshot, and a
|
||||
// transaction is not reachable through storage.DoltStorage. The sharing
|
||||
// happens one level down instead — this body and the embedded store's are a
|
||||
// few lines each around issueops.SweepInTx — and two wrappers over one body is
|
||||
// still ONE vote, which the conformance contract says out loud.
|
||||
//
|
||||
// A front door cannot construct this: the type is unexported and the accessor
|
||||
// is the only door.
|
||||
// reference scan and a delete that must all see one snapshot, and a transaction
|
||||
// is not reachable through storage.DoltStorage. The sharing happens one level
|
||||
// down — this body and the embedded store's are a few lines each around
|
||||
// issueops.SweepInTx — and two wrappers over one body is still ONE vote.
|
||||
type sweeper struct{ store *DoltStore }
|
||||
|
||||
var _ issueops.Sweeper = (*sweeper)(nil)
|
||||
|
||||
// Sweep clears the request's tier.
|
||||
//
|
||||
// VALIDATION HAPPENS BEFORE THE TRANSACTION, so a refused request costs no
|
||||
// database work — which is what makes issueops.Sweeper's "a refusal changes
|
||||
// nothing" true of the connection as well as of the rows.
|
||||
// VALIDATION HAPPENS BEFORE THE TRANSACTION, which makes issueops.Sweeper's "a
|
||||
// refusal changes nothing" true of the connection as well as of the rows.
|
||||
//
|
||||
// A DRY RUN TAKES A READ TRANSACTION. It writes nothing by construction, so
|
||||
// giving it a write transaction and an empty commit would make the preview
|
||||
// look like a mutation to everything watching the store.
|
||||
//
|
||||
// THE VERSION-CONTROL ENTRY IS ONE PER SWEEP, recorded here rather than in the
|
||||
// shared body because only this backend records one at all: the embedded store
|
||||
// commits outside the SQL transaction and the unit-of-work provider labels its
|
||||
// own. An ephemeral sweep touches only the wisp tables, which this plane
|
||||
// ignores, so DOLT_COMMIT finds nothing to commit and the sweep records no
|
||||
// entry — the "at most one" the role promises, not "exactly one".
|
||||
// shared body because only this backend records one at all. An ephemeral sweep
|
||||
// touches only the wisp tables, which this plane ignores, so DOLT_COMMIT finds
|
||||
// nothing to commit — the "at most one" the role promises, not "exactly one".
|
||||
func (s *sweeper) Sweep(ctx context.Context, req issueops.SweepRequest) (issueops.SweepResult, error) {
|
||||
if err := workapi.ValidateSweepRequest(req); err != nil {
|
||||
return issueops.SweepResult{}, 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