diff --git a/backend/conformance/batch_creator_contract.go b/backend/conformance/batch_creator_contract.go index 723769845..c2c3c5aa2 100644 --- a/backend/conformance/batch_creator_contract.go +++ b/backend/conformance/batch_creator_contract.go @@ -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 diff --git a/backend/conformance/blocking_annotator_contract.go b/backend/conformance/blocking_annotator_contract.go index b176d8957..523b05037 100644 --- a/backend/conformance/blocking_annotator_contract.go +++ b/backend/conformance/blocking_annotator_contract.go @@ -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 { diff --git a/backend/conformance/bootstrapper_contract.go b/backend/conformance/bootstrapper_contract.go index df921999d..5d6a9ab97 100644 --- a/backend/conformance/bootstrapper_contract.go +++ b/backend/conformance/bootstrapper_contract.go @@ -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() diff --git a/backend/conformance/counter_contract.go b/backend/conformance/counter_contract.go index 6de4e2153..12196647e 100644 --- a/backend/conformance/counter_contract.go +++ b/backend/conformance/counter_contract.go @@ -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 { diff --git a/backend/conformance/cycle_detector_contract.go b/backend/conformance/cycle_detector_contract.go index e82c2a475..d6c60c7df 100644 --- a/backend/conformance/cycle_detector_contract.go +++ b/backend/conformance/cycle_detector_contract.go @@ -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 diff --git a/backend/conformance/deleter_contract.go b/backend/conformance/deleter_contract.go index aa1461bc9..0dd492e08 100644 --- a/backend/conformance/deleter_contract.go +++ b/backend/conformance/deleter_contract.go @@ -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:]` -// 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:]`, 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 { diff --git a/backend/conformance/edge_reader_contract.go b/backend/conformance/edge_reader_contract.go index 2fc4a8200..b368af7c8 100644 --- a/backend/conformance/edge_reader_contract.go +++ b/backend/conformance/edge_reader_contract.go @@ -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 { diff --git a/backend/conformance/issue_operations_contract.go b/backend/conformance/issue_operations_contract.go index 0f0a8f975..d9ac39b20 100644 --- a/backend/conformance/issue_operations_contract.go +++ b/backend/conformance/issue_operations_contract.go @@ -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 -// ` 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 ` 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() diff --git a/backend/conformance/querier_contract.go b/backend/conformance/querier_contract.go index 799f966ad..9898a55c4 100644 --- a/backend/conformance/querier_contract.go +++ b/backend/conformance/querier_contract.go @@ -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...) diff --git a/backend/conformance/reader_contract.go b/backend/conformance/reader_contract.go index ecb8ee628..46aee46c4 100644 --- a/backend/conformance/reader_contract.go +++ b/backend/conformance/reader_contract.go @@ -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}, diff --git a/backend/conformance/ready_counter_contract.go b/backend/conformance/ready_counter_contract.go index 68ba0e7f0..f09a22168 100644 --- a/backend/conformance/ready_counter_contract.go +++ b/backend/conformance/ready_counter_contract.go @@ -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) diff --git a/backend/conformance/stats_reporter_contract.go b/backend/conformance/stats_reporter_contract.go index 18b4082a4..3f7777eaf 100644 --- a/backend/conformance/stats_reporter_contract.go +++ b/backend/conformance/stats_reporter_contract.go @@ -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 { diff --git a/backend/conformance/sweeper_contract.go b/backend/conformance/sweeper_contract.go index 090d80a91..c30c8665f 100644 --- a/backend/conformance/sweeper_contract.go +++ b/backend/conformance/sweeper_contract.go @@ -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: `x` must NOT protect anything, and the parenthesised + // The near-miss `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...) diff --git a/backend/conformance/workspaceconfig_contract.go b/backend/conformance/workspaceconfig_contract.go index 3f44a07e6..2b7b2c674 100644 --- a/backend/conformance/workspaceconfig_contract.go +++ b/backend/conformance/workspaceconfig_contract.go @@ -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 ` 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 ` 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. diff --git a/cmd/bd/cascade_parity_proxied_integration_test.go b/cmd/bd/cascade_parity_proxied_integration_test.go index 8c84d4f57..5c55e1be2 100644 --- a/cmd/bd/cascade_parity_proxied_integration_test.go +++ b/cmd/bd/cascade_parity_proxied_integration_test.go @@ -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 --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 --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 --force`, and // `bd gate create --blocks ` makes the gated bead a DEPENDENT of the // gate, so that step destroyed the work it had just unblocked. diff --git a/cmd/bd/closed_delete_candidates.go b/cmd/bd/closed_delete_candidates.go index d32316363..777603b49 100644 --- a/cmd/bd/closed_delete_candidates.go +++ b/cmd/bd/closed_delete_candidates.go @@ -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 diff --git a/cmd/bd/config.go b/cmd/bd/config.go index c507d0405..7e5d6a831 100644 --- a/cmd/bd/config.go +++ b/cmd/bd/config.go @@ -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)) diff --git a/cmd/bd/config_proxied_server.go b/cmd/bd/config_proxied_server.go index 165fe2f59..aeeb0de1a 100644 --- a/cmd/bd/config_proxied_server.go +++ b/cmd/bd/config_proxied_server.go @@ -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. diff --git a/cmd/bd/count.go b/cmd/bd/count.go index fb3ad5f44..0028490f7 100644 --- a/cmd/bd/count.go +++ b/cmd/bd/count.go @@ -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 { diff --git a/cmd/bd/count_filter_test.go b/cmd/bd/count_filter_test.go index 6818686b6..448822083 100644 --- a/cmd/bd/count_filter_test.go +++ b/cmd/bd/count_filter_test.go @@ -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 { diff --git a/cmd/bd/create_markdown_batch_test.go b/cmd/bd/create_markdown_batch_test.go index 08bf03c77..79c6a01f7 100644 --- a/cmd/bd/create_markdown_batch_test.go +++ b/cmd/bd/create_markdown_batch_test.go @@ -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 == "" { diff --git a/cmd/bd/create_proxied_server.go b/cmd/bd/create_proxied_server.go index d71a77615..2894441a6 100644 --- a/cmd/bd/create_proxied_server.go +++ b/cmd/bd/create_proxied_server.go @@ -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") diff --git a/cmd/bd/delete.go b/cmd/bd/delete.go index d304d7c4f..5d4b6e598 100644 --- a/cmd/bd/delete.go +++ b/cmd/bd/delete.go @@ -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 --json` - // consumer already parses. + // list here, which is what every `bd delete --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{}{ diff --git a/cmd/bd/delete_proxied_integration_test.go b/cmd/bd/delete_proxied_integration_test.go index dee8343e5..e785f75ca 100644 --- a/cmd/bd/delete_proxied_integration_test.go +++ b/cmd/bd/delete_proxied_integration_test.go @@ -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() diff --git a/cmd/bd/delete_proxied_server.go b/cmd/bd/delete_proxied_server.go index a7200d3ed..2c0090f08 100644 --- a/cmd/bd/delete_proxied_server.go +++ b/cmd/bd/delete_proxied_server.go @@ -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) diff --git a/cmd/bd/dep.go b/cmd/bd/dep.go index 0f9fa98a4..3e2841b19 100644 --- a/cmd/bd/dep.go +++ b/cmd/bd/dep.go @@ -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 - // --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. diff --git a/cmd/bd/dep_cycles.go b/cmd/bd/dep_cycles.go index 51c9b8d06..a33ff6f46 100644 --- a/cmd/bd/dep_cycles.go +++ b/cmd/bd/dep_cycles.go @@ -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 diff --git a/cmd/bd/dep_cycles_test.go b/cmd/bd/dep_cycles_test.go index 6078b2412..b8df20525 100644 --- a/cmd/bd/dep_cycles_test.go +++ b/cmd/bd/dep_cycles_test.go @@ -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 diff --git a/cmd/bd/dep_edge_reader_test.go b/cmd/bd/dep_edge_reader_test.go index aaba0a9c1..7d7e095ed 100644 --- a/cmd/bd/dep_edge_reader_test.go +++ b/cmd/bd/dep_edge_reader_test.go @@ -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 " 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 " 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}}}, diff --git a/cmd/bd/dep_proxied_server.go b/cmd/bd/dep_proxied_server.go index d3c61c4d3..4a5607adf 100644 --- a/cmd/bd/dep_proxied_server.go +++ b/cmd/bd/dep_proxied_server.go @@ -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 " 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 " 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 { diff --git a/cmd/bd/dep_tree.go b/cmd/bd/dep_tree.go index b49ae374e..ffce21492 100644 --- a/cmd/bd/dep_tree.go +++ b/cmd/bd/dep_tree.go @@ -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 } diff --git a/cmd/bd/init.go b/cmd/bd/init.go index 17d57efe2..c86d95491 100644 --- a/cmd/bd/init.go +++ b/cmd/bd/init.go @@ -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) diff --git a/cmd/bd/init_proxied_server.go b/cmd/bd/init_proxied_server.go index f31198f99..3d4deadd9 100644 --- a/cmd/bd/init_proxied_server.go +++ b/cmd/bd/init_proxied_server.go @@ -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 { diff --git a/cmd/bd/init_team_server_test.go b/cmd/bd/init_team_server_test.go index d9a21bd4a..b65f222ef 100644 --- a/cmd/bd/init_team_server_test.go +++ b/cmd/bd/init_team_server_test.go @@ -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 diff --git a/cmd/bd/list.go b/cmd/bd/list.go index 8b6de0f9e..8933f83c4 100644 --- a/cmd/bd/list.go +++ b/cmd/bd/list.go @@ -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 diff --git a/cmd/bd/list_proxied_server.go b/cmd/bd/list_proxied_server.go index 8d41bba64..a57c7e1de 100644 --- a/cmd/bd/list_proxied_server.go +++ b/cmd/bd/list_proxied_server.go @@ -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 diff --git a/cmd/bd/list_roles.go b/cmd/bd/list_roles.go index 4ab78b303..4244bcd72 100644 --- a/cmd/bd/list_roles.go +++ b/cmd/bd/list_roles.go @@ -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") diff --git a/cmd/bd/list_roles_test.go b/cmd/bd/list_roles_test.go index 3f14d6d76..40b00b3ff 100644 --- a/cmd/bd/list_roles_test.go +++ b/cmd/bd/list_roles_test.go @@ -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"}, diff --git a/cmd/bd/markdown.go b/cmd/bd/markdown.go index bef08f47f..5891caccb 100644 --- a/cmd/bd/markdown.go +++ b/cmd/bd/markdown.go @@ -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 diff --git a/cmd/bd/purge.go b/cmd/bd/purge.go index 7012e1c38..e60996c69 100644 --- a/cmd/bd/purge.go +++ b/cmd/bd/purge.go @@ -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 { diff --git a/cmd/bd/query.go b/cmd/bd/query.go index dc203f98b..67c689778 100644 --- a/cmd/bd/query.go +++ b/cmd/bd/query.go @@ -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 } diff --git a/cmd/bd/query_proxied_integration_test.go b/cmd/bd/query_proxied_integration_test.go index c21cb2caf..bc1e0362f 100644 --- a/cmd/bd/query_proxied_integration_test.go +++ b/cmd/bd/query_proxied_integration_test.go @@ -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") { diff --git a/cmd/bd/query_proxied_server.go b/cmd/bd/query_proxied_server.go index af7472f6a..aff1a9e5e 100644 --- a/cmd/bd/query_proxied_server.go +++ b/cmd/bd/query_proxied_server.go @@ -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 { diff --git a/cmd/bd/ready.go b/cmd/bd/ready.go index a4beda84e..17dbcda01 100644 --- a/cmd/bd/ready.go +++ b/cmd/bd/ready.go @@ -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 { diff --git a/cmd/bd/ready_input.go b/cmd/bd/ready_input.go index 6aa73052f..f3cda8fbc 100644 --- a/cmd/bd/ready_input.go +++ b/cmd/bd/ready_input.go @@ -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 diff --git a/cmd/bd/ready_proxied_server.go b/cmd/bd/ready_proxied_server.go index 8741244b6..1beba8335 100644 --- a/cmd/bd/ready_proxied_server.go +++ b/cmd/bd/ready_proxied_server.go @@ -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") diff --git a/cmd/bd/ready_role_request_test.go b/cmd/bd/ready_role_request_test.go index 88b671084..4dfc5af21 100644 --- a/cmd/bd/ready_role_request_test.go +++ b/cmd/bd/ready_role_request_test.go @@ -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) diff --git a/cmd/bd/reopen_proxied_integration_test.go b/cmd/bd/reopen_proxied_integration_test.go index 6e627a615..ecd83ae07 100644 --- a/cmd/bd/reopen_proxied_integration_test.go +++ b/cmd/bd/reopen_proxied_integration_test.go @@ -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") diff --git a/cmd/bd/reopen_proxied_server.go b/cmd/bd/reopen_proxied_server.go index 4d4874080..1fea9d375 100644 --- a/cmd/bd/reopen_proxied_server.go +++ b/cmd/bd/reopen_proxied_server.go @@ -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 " 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 diff --git a/cmd/bd/serve.go b/cmd/bd/serve.go index d23214388..99a993a46 100644 --- a/cmd/bd/serve.go +++ b/cmd/bd/serve.go @@ -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 diff --git a/cmd/bd/serve_source_test.go b/cmd/bd/serve_source_test.go index e2bfc9658..6e7dd5835 100644 --- a/cmd/bd/serve_source_test.go +++ b/cmd/bd/serve_source_test.go @@ -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 diff --git a/cmd/bd/serve_store_identity_test.go b/cmd/bd/serve_store_identity_test.go index 060b96f0c..299fc11f8 100644 --- a/cmd/bd/serve_store_identity_test.go +++ b/cmd/bd/serve_store_identity_test.go @@ -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 } diff --git a/cmd/bd/status.go b/cmd/bd/status.go index 838952d10..20404aa8e 100644 --- a/cmd/bd/status.go +++ b/cmd/bd/status.go @@ -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() diff --git a/cmd/bd/update_close_policy_proxied_integration_test.go b/cmd/bd/update_close_policy_proxied_integration_test.go index b6b6983dd..c53b8ba9a 100644 --- a/cmd/bd/update_close_policy_proxied_integration_test.go +++ b/cmd/bd/update_close_policy_proxied_integration_test.go @@ -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. // diff --git a/cmd/bd/update_proxied_integration_test.go b/cmd/bd/update_proxied_integration_test.go index 61b76c13c..0e96adae0 100644 --- a/cmd/bd/update_proxied_integration_test.go +++ b/cmd/bd/update_proxied_integration_test.go @@ -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) } diff --git a/cmd/bd/update_proxied_server.go b/cmd/bd/update_proxied_server.go index 8f5e9e7a1..c4509c32b 100644 --- a/cmd/bd/update_proxied_server.go +++ b/cmd/bd/update_proxied_server.go @@ -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): diff --git a/cmd/bd/update_proxied_server_test.go b/cmd/bd/update_proxied_server_test.go index ccd3439a1..9fe7e1c3c 100644 --- a/cmd/bd/update_proxied_server_test.go +++ b/cmd/bd/update_proxied_server_test.go @@ -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{ diff --git a/cmd/bd/version_proxied_server.go b/cmd/bd/version_proxied_server.go index 41d986226..817f91e5e 100644 --- a/cmd/bd/version_proxied_server.go +++ b/cmd/bd/version_proxied_server.go @@ -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 diff --git a/cmd/bd/version_tracking.go b/cmd/bd/version_tracking.go index 0541b7e9e..c8f70496e 100644 --- a/cmd/bd/version_tracking.go +++ b/cmd/bd/version_tracking.go @@ -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 { diff --git a/internal/httpapi/batch_create.go b/internal/httpapi/batch_create.go index 927653619..256b4d0ae 100644 --- a/internal/httpapi/batch_create.go +++ b/internal/httpapi/batch_create.go @@ -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, diff --git a/internal/httpapi/batch_create_test.go b/internal/httpapi/batch_create_test.go index 01c4c1238..38c725be6 100644 --- a/internal/httpapi/batch_create_test.go +++ b/internal/httpapi/batch_create_test.go @@ -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) diff --git a/internal/httpapi/blocking.go b/internal/httpapi/blocking.go index 08cb3a9ed..62ceb0c03 100644 --- a/internal/httpapi/blocking.go +++ b/internal/httpapi/blocking.go @@ -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{}} diff --git a/internal/httpapi/blocking_test.go b/internal/httpapi/blocking_test.go index 97e522f8c..2dfd38822 100644 --- a/internal/httpapi/blocking_test.go +++ b/internal/httpapi/blocking_test.go @@ -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{}) diff --git a/internal/httpapi/claim.go b/internal/httpapi/claim.go index 2757aa378..754ab75a4 100644 --- a/internal/httpapi/claim.go +++ b/internal/httpapi/claim.go @@ -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) } diff --git a/internal/httpapi/cycles.go b/internal/httpapi/cycles.go index cc69c04ed..370a035ec 100644 --- a/internal/httpapi/cycles.go +++ b/internal/httpapi/cycles.go @@ -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{} diff --git a/internal/httpapi/cycles_test.go b/internal/httpapi/cycles_test.go index 450b8f608..1b5950d02 100644 --- a/internal/httpapi/cycles_test.go +++ b/internal/httpapi/cycles_test.go @@ -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{}) diff --git a/internal/httpapi/delete.go b/internal/httpapi/delete.go index 34550ba7a..d0f68a55f 100644 --- a/internal/httpapi/delete.go +++ b/internal/httpapi/delete.go @@ -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, diff --git a/internal/httpapi/delete_test.go b/internal/httpapi/delete_test.go index 6fb150892..afdc322fe 100644 --- a/internal/httpapi/delete_test.go +++ b/internal/httpapi/delete_test.go @@ -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})) diff --git a/internal/httpapi/edges.go b/internal/httpapi/edges.go index f49ae9cf2..8053cafa1 100644 --- a/internal/httpapi/edges.go +++ b/internal/httpapi/edges.go @@ -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{}, diff --git a/internal/httpapi/edges_test.go b/internal/httpapi/edges_test.go index edb4afcc1..16b79cf20 100644 --- a/internal/httpapi/edges_test.go +++ b/internal/httpapi/edges_test.go @@ -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 diff --git a/internal/httpapi/pinning.go b/internal/httpapi/pinning.go index 6f6583c29..896118ead 100644 --- a/internal/httpapi/pinning.go +++ b/internal/httpapi/pinning.go @@ -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 diff --git a/internal/httpapi/problem.go b/internal/httpapi/problem.go index ff022cd53..6a0aafa82 100644 --- a/internal/httpapi/problem.go +++ b/internal/httpapi/problem.go @@ -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 diff --git a/internal/httpapi/reads.go b/internal/httpapi/reads.go index 73ad63eb2..12b0c9b19 100644 --- a/internal/httpapi/reads.go +++ b/internal/httpapi/reads.go @@ -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()) diff --git a/internal/httpapi/ready_count_test.go b/internal/httpapi/ready_count_test.go index 90e27e4fc..8ebfbd8c2 100644 --- a/internal/httpapi/ready_count_test.go +++ b/internal/httpapi/ready_count_test.go @@ -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" + diff --git a/internal/httpapi/roles.go b/internal/httpapi/roles.go index ce714a988..036086d82 100644 --- a/internal/httpapi/roles.go +++ b/internal/httpapi/roles.go @@ -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 diff --git a/internal/httpapi/roles_test.go b/internal/httpapi/roles_test.go index 7ac93ba05..179e46461 100644 --- a/internal/httpapi/roles_test.go +++ b/internal/httpapi/roles_test.go @@ -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) diff --git a/internal/httpapi/routes.go b/internal/httpapi/routes.go index 557c2f896..01789fbe5 100644 --- a/internal/httpapi/routes.go +++ b/internal/httpapi/routes.go @@ -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 diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index e9ad5ec70..39e0b17af 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -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 diff --git a/internal/httpapi/server_test.go b/internal/httpapi/server_test.go index 492576dae..a886b5881 100644 --- a/internal/httpapi/server_test.go +++ b/internal/httpapi/server_test.go @@ -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 diff --git a/internal/httpapi/settings.go b/internal/httpapi/settings.go index ee2afc4d1..509f757f8 100644 --- a/internal/httpapi/settings.go +++ b/internal/httpapi/settings.go @@ -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. diff --git a/internal/httpapi/stats.go b/internal/httpapi/stats.go index 8fcec4eaa..26c6df6e7 100644 --- a/internal/httpapi/stats.go +++ b/internal/httpapi/stats.go @@ -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, }) diff --git a/internal/httpapi/stats_test.go b/internal/httpapi/stats_test.go index 5f61b11a5..26cf5979a 100644 --- a/internal/httpapi/stats_test.go +++ b/internal/httpapi/stats_test.go @@ -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{}})) diff --git a/internal/httpapi/sweep.go b/internal/httpapi/sweep.go index ae029e3e9..8283fd703 100644 --- a/internal/httpapi/sweep.go +++ b/internal/httpapi/sweep.go @@ -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 diff --git a/internal/httpapi/sweep_test.go b/internal/httpapi/sweep_test.go index 02ef632e8..9942733c6 100644 --- a/internal/httpapi/sweep_test.go +++ b/internal/httpapi/sweep_test.go @@ -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{} diff --git a/internal/httpapi/timed_provider_binding_test.go b/internal/httpapi/timed_provider_binding_test.go index 750191696..0d2b8f9c0 100644 --- a/internal/httpapi/timed_provider_binding_test.go +++ b/internal/httpapi/timed_provider_binding_test.go @@ -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) diff --git a/internal/httpapi/tree.go b/internal/httpapi/tree.go index cb589c084..968be9846 100644 --- a/internal/httpapi/tree.go +++ b/internal/httpapi/tree.go @@ -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 { diff --git a/internal/httpapi/tree_test.go b/internal/httpapi/tree_test.go index d14c35d8a..8bd763a9d 100644 --- a/internal/httpapi/tree_test.go +++ b/internal/httpapi/tree_test.go @@ -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)) } diff --git a/internal/storage/dolt/batch_creator_contract_test.go b/internal/storage/dolt/batch_creator_contract_test.go index 7bfb29755..aa84b70e5 100644 --- a/internal/storage/dolt/batch_creator_contract_test.go +++ b/internal/storage/dolt/batch_creator_contract_test.go @@ -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() diff --git a/internal/storage/dolt/blockingannotator.go b/internal/storage/dolt/blockingannotator.go index e6a37b883..95665f3fc 100644 --- a/internal/storage/dolt/blockingannotator.go +++ b/internal/storage/dolt/blockingannotator.go @@ -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"} diff --git a/internal/storage/dolt/bootstrapper.go b/internal/storage/dolt/bootstrapper.go index e8e7ef36c..dc6f941fb 100644 --- a/internal/storage/dolt/bootstrapper.go +++ b/internal/storage/dolt/bootstrapper.go @@ -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) diff --git a/internal/storage/dolt/bootstrapper_contract_test.go b/internal/storage/dolt/bootstrapper_contract_test.go index 16818bf8c..4b0e88fd3 100644 --- a/internal/storage/dolt/bootstrapper_contract_test.go +++ b/internal/storage/dolt/bootstrapper_contract_test.go @@ -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 diff --git a/internal/storage/dolt/cycle_detector.go b/internal/storage/dolt/cycle_detector.go index f23fb90b0..fd562d859 100644 --- a/internal/storage/dolt/cycle_detector.go +++ b/internal/storage/dolt/cycle_detector.go @@ -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) diff --git a/internal/storage/dolt/cycle_detector_contract_test.go b/internal/storage/dolt/cycle_detector_contract_test.go index 0aee93b27..e3cbb5149 100644 --- a/internal/storage/dolt/cycle_detector_contract_test.go +++ b/internal/storage/dolt/cycle_detector_contract_test.go @@ -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 diff --git a/internal/storage/dolt/deleter.go b/internal/storage/dolt/deleter.go index 39d3a776b..7b4c281b5 100644 --- a/internal/storage/dolt/deleter.go +++ b/internal/storage/dolt/deleter.go @@ -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) } diff --git a/internal/storage/dolt/deleter_contract_test.go b/internal/storage/dolt/deleter_contract_test.go index ccf79818c..98a4239b9 100644 --- a/internal/storage/dolt/deleter_contract_test.go +++ b/internal/storage/dolt/deleter_contract_test.go @@ -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() diff --git a/internal/storage/dolt/edgereader.go b/internal/storage/dolt/edgereader.go index 7e33f2efa..3af03da2e 100644 --- a/internal/storage/dolt/edgereader.go +++ b/internal/storage/dolt/edgereader.go @@ -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"} diff --git a/internal/storage/dolt/querier_contract_test.go b/internal/storage/dolt/querier_contract_test.go index c6677ae10..4d3ab2047 100644 --- a/internal/storage/dolt/querier_contract_test.go +++ b/internal/storage/dolt/querier_contract_test.go @@ -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() diff --git a/internal/storage/dolt/querier_over_the_old_window_test.go b/internal/storage/dolt/querier_over_the_old_window_test.go index c503e0a52..de4f24b00 100644 --- a/internal/storage/dolt/querier_over_the_old_window_test.go +++ b/internal/storage/dolt/querier_over_the_old_window_test.go @@ -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. diff --git a/internal/storage/dolt/ready_counter_contract_test.go b/internal/storage/dolt/ready_counter_contract_test.go index 66842abc7..5929e58ef 100644 --- a/internal/storage/dolt/ready_counter_contract_test.go +++ b/internal/storage/dolt/ready_counter_contract_test.go @@ -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() diff --git a/internal/storage/dolt/sweeper.go b/internal/storage/dolt/sweeper.go index 16e0e08e1..352000bae 100644 --- a/internal/storage/dolt/sweeper.go +++ b/internal/storage/dolt/sweeper.go @@ -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 diff --git a/internal/storage/dolt/sweeper_contract_test.go b/internal/storage/dolt/sweeper_contract_test.go index a4f28418e..a0da37050 100644 --- a/internal/storage/dolt/sweeper_contract_test.go +++ b/internal/storage/dolt/sweeper_contract_test.go @@ -13,12 +13,10 @@ import ( // for a sweep. // // The cases are subtests of one parent so the whole role suite shares one -// store and one copy-on-write branch. That sharing is what makes the id -// pattern in every case load-bearing rather than tidy: a sweep is asked of a -// whole TIER, so a case that swept without one would delete the next case's -// seeds. 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. +// store and one copy-on-write branch. 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. func TestSweeperContract(t *testing.T) { fixture, ctx, cleanup := newDoltSweeperFixture(t, "swp") defer cleanup() diff --git a/internal/storage/dolt/tree_walker.go b/internal/storage/dolt/tree_walker.go index e79bf4a7e..aecfdd17a 100644 --- a/internal/storage/dolt/tree_walker.go +++ b/internal/storage/dolt/tree_walker.go @@ -19,17 +19,12 @@ func (s *DoltStore) TreeWalker() (issueops.TreeWalker, error) { // treeWalker answers a dependency-tree walk from one read transaction. // -// There is no shared constructor package for this role, for the reason -// cycleDetector gives next door: the work is a root probe, a recursion of -// adjacency reads and a hydration per node, all of which must see ONE snapshot — -// and for a `both` walk that covers two directions. A transaction is not -// reachable through storage.DoltStorage, so the sharing happens one level down -// at issueops.WalkDependencyTreeInTx and this body is five lines around it. 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. +// There is no shared constructor package for this role: the work is a root +// probe, a recursion of adjacency reads and a hydration per node, all of which +// must see ONE snapshot — and for a `both` walk that covers two directions. A +// transaction is not reachable through storage.DoltStorage, so the sharing +// happens one level down at issueops.WalkDependencyTreeInTx. Two wrappers over +// one body is still ONE vote, and the conformance contract says so. type treeWalker struct{ store *DoltStore } var _ issueops.TreeWalker = (*treeWalker)(nil) diff --git a/internal/storage/dolt/tree_walker_contract_test.go b/internal/storage/dolt/tree_walker_contract_test.go index 0f108ba86..52a41cda7 100644 --- a/internal/storage/dolt/tree_walker_contract_test.go +++ b/internal/storage/dolt/tree_walker_contract_test.go @@ -12,10 +12,8 @@ import ( // store. // // The cases are subtests of one parent so the whole role suite shares one store -// and one copy-on-write branch. Every case seeds ids under its own prefix and -// asserts only about those, so the order they run in does not matter; -// setupTestStore already marks the PARENT parallel and no subtest here calls -// t.Parallel. +// and one copy-on-write branch. setupTestStore already marks the PARENT +// parallel and no subtest here calls t.Parallel. func TestTreeWalkerContract(t *testing.T) { fixture, ctx, cleanup := newDoltTreeWalkerFixture(t, "twk") defer cleanup() @@ -92,9 +90,8 @@ func newDoltTreeWalkerFixture(t *testing.T, prefix string) (conformance.TreeWalk AddDependency: kit.AddDependency, // The frozen kit exposes reads only, so the raw write the cycle case // needs is supplied here — over the same *sql.DB the kit's QueryScalar - // reads through, which on this backend is the test's own branch. One - // PINNED CONNECTION for the whole script, as the cycle-detector wiring - // does, so a multi-statement seed cannot be split across sessions. + // reads through. One PINNED CONNECTION for the whole script, so a + // multi-statement seed cannot be split across sessions. Exec: func(ctx context.Context, statements []conformance.SQLStatement) error { conn, err := store.db.Conn(ctx) if err != nil { diff --git a/internal/storage/dolt/version_reconciler_contract_test.go b/internal/storage/dolt/version_reconciler_contract_test.go index 0ee203769..f059d407d 100644 --- a/internal/storage/dolt/version_reconciler_contract_test.go +++ b/internal/storage/dolt/version_reconciler_contract_test.go @@ -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. Sharing matters here the way it does for the -// settings role and not the way it does for the issue roles: the two version -// markers are GLOBAL to a workspace and cannot be namespaced under the fixture -// prefix, so every case seeds both of them explicitly instead of relying on -// what the case before it left. setupTestStore already marks the PARENT +// and one copy-on-write branch. The two version markers are GLOBAL to a +// workspace and cannot be namespaced under the fixture prefix, so every case +// seeds both of them explicitly instead of relying on what the case before it +// left. setupTestStore already marks the PARENT // parallel; no subtest here calls t.Parallel, because the no-history case takes // a log delta. func TestVersionReconcilerContract(t *testing.T) { diff --git a/internal/storage/dolt/workspace_config_contract_test.go b/internal/storage/dolt/workspace_config_contract_test.go index 75883a9cb..31f40489a 100644 --- a/internal/storage/dolt/workspace_config_contract_test.go +++ b/internal/storage/dolt/workspace_config_contract_test.go @@ -11,13 +11,12 @@ 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. That sharing matters more here than it does for -// a read role: config keys are GLOBAL to a workspace, so the cases namespace -// their probe keys under the fixture prefix and the two projected keys -// (status.custom, types.custom) are written by name and asserted exactly. The -// refused-write case takes a 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. Config keys are GLOBAL to a workspace, so the +// cases namespace their probe keys under the fixture prefix and the two +// projected keys (status.custom, types.custom) are written by name and asserted +// exactly. The refused-write case takes a history delta, which is only +// meaningful while the subtests run sequentially. setupTestStore already marks +// the PARENT parallel; no subtest here calls t.Parallel. func TestWorkspaceConfigContract(t *testing.T) { fixture, ctx, cleanup := newDoltWorkspaceConfigFixture(t, "wcfg") defer cleanup() @@ -77,8 +76,8 @@ func newDoltWorkspaceConfigFixture(t *testing.T, prefix string) (conformance.Wor t.Fatalf("WorkspaceConfig(): %v", err) } kit := newDoltRoleFixtureKit(store, prefix) - // The protected-key cases need an issue_prefix to remove and restore, and - // they need it written PAST the role, which refuses to write it. + // The protected-key cases need an issue_prefix to remove and restore, + // written PAST the role, which refuses to write it. if err := kit.SetConfig(ctx, "issue_prefix", prefix); err != nil { cancel() storeCleanup() diff --git a/internal/storage/domain/config.go b/internal/storage/domain/config.go index 04899013a..3be035526 100644 --- a/internal/storage/domain/config.go +++ b/internal/storage/domain/config.go @@ -43,16 +43,12 @@ type ConfigUseCase interface { GetAllConfig(ctx context.Context) (map[string]string, error) GetMetadata(ctx context.Context, key string) (string, error) // SetMetadata writes one durable metadata value inside the caller's unit of - // work. It is the write half of the GetMetadata above it, published for the - // same reason SetLocalMetadata was: issueops.Bootstrapper's unit-of-work - // body reads the identity, refuses over an identified substrate and writes - // the new one in ONE transaction, and a refusal decided outside the - // transaction that writes is a refusal two racing inits both pass. - // - // It replaces BootstrapUseCase, which held its own copy of which keys an - // identity is made of — a copy the direct route never used and no test - // compared against it. The keys are named once in internal/workapi now and - // this seam moves bytes. + // work. It is the write half of the GetMetadata above it: + // issueops.Bootstrapper's unit-of-work body reads the identity, refuses over + // an identified substrate and writes the new one in ONE transaction, and a + // refusal decided outside the transaction that writes is a refusal two + // racing inits both pass. The identity's keys are named once, in + // internal/workapi; this seam moves bytes. SetMetadata(ctx context.Context, key, value string) error GetLocalMetadata(ctx context.Context, key string) (string, error) // SetLocalMetadata writes one clone-local, dolt-ignored value inside the @@ -62,11 +58,9 @@ type ConfigUseCase interface { // writes them back — all in ONE transaction, which is what makes the read // it qualifies and the write it plans see the same snapshot. // - // The DECISION is deliberately not here. It used to be, as a - // ReconcileVersion method on this use case, and that left the rule for - // which version may overwrite which stated twice: once here for the - // proxied route and once in cmd/bd for the direct one. Both now plan - // through workapi.PlanVersionReconcile and this seam moves bytes. + // The DECISION is deliberately not here: both routes plan through + // workapi.PlanVersionReconcile, so the rule for which version may overwrite + // which is stated once. SetLocalMetadata(ctx context.Context, key, value string) error } diff --git a/internal/storage/domain/db/config.go b/internal/storage/domain/db/config.go index 98e2a92a0..cea2ccf96 100644 --- a/internal/storage/domain/db/config.go +++ b/internal/storage/domain/db/config.go @@ -92,8 +92,7 @@ func (r *configSQLRepositoryImpl) SetConfig(ctx context.Context, key, value stri // success and `bd create -t ` kept answering "invalid issue // type", with doctor re-verifying against the string and reporting all-OK. // - // The caller supplies a transactional runner (every production - // construction is internal/storage/uow's), so the row and its projection + // The caller supplies a transactional runner, so the row and its projection // commit together or neither does. switch key { case "status.custom": diff --git a/internal/storage/domain/db/config_test.go b/internal/storage/domain/db/config_test.go index b0e15e091..fe08886da 100644 --- a/internal/storage/domain/db/config_test.go +++ b/internal/storage/domain/db/config_test.go @@ -522,14 +522,10 @@ func (s *testSuite) resetLocalMetadata() { // issueops.VersionReconciler's unit-of-work body reads and writes its two // markers that way, inside one transaction. // -// WHAT USED TO BE HERE was seven subtests of a ReconcileVersion method on this -// use case: a fresh install, an upgrade, two refused downgrades, a catch-up to -// the high-water mark. That method held one of the TWO copies of the version -// decision — cmd/bd/version_tracking.go held the other, and nothing compared -// them — and both are now workapi.PlanVersionReconcile, whose table is pinned -// exhaustively and without a database in +// The version decision the ReconcileVersion subtests used to cover is now +// workapi.PlanVersionReconcile, pinned exhaustively and without a database in // internal/workapi/versionreconcile_test.go. What only a real backend can -// show, that the markers persist and that a refusal writes nothing, is +// show — that the markers persist and that a refusal writes nothing — is // asserted at all three backends by TestVersionReconcilerContract. func (s *testSuite) configLocalMetadataRoundTrip() { s.resetLocalMetadata() diff --git a/internal/storage/domain/dependency.go b/internal/storage/domain/dependency.go index 5edc2908b..d20e79f8c 100644 --- a/internal/storage/domain/dependency.go +++ b/internal/storage/domain/dependency.go @@ -151,14 +151,14 @@ type DependencySQLRepository interface { // DetectCycleReport answers the same walk in the shape issueops.CycleDetector // publishes: canonically ordered, and carrying every member of a cycle // whether or not this database can describe it. DetectCycles above is the - // lossy legacy shape and stays for the callers that still read it. + // lossy legacy shape. DetectCycleReport(ctx context.Context) (issueops.CycleReport, error) GetTree(ctx context.Context, rootID string, opts DepTreeOpts) ([]*types.TreeNode, error) // WalkDependencyTree answers the tree walk in the shape issueops.TreeWalker // publishes: validated, rooted, pruned by status and capped, with both // directions of a `both` request inside ONE transaction. GetTree above is the - // unvalidated shape and stays for the callers that still read it. + // unvalidated shape. WalkDependencyTree(ctx context.Context, req issueops.WalkTreeRequest) (issueops.TreeResult, error) CycleThroughEdges(ctx context.Context, edges [][2]string) (string, error) GetDependencyRecordsForIssues(ctx context.Context, issueIDs []string) (map[string][]*types.Dependency, error) @@ -621,10 +621,8 @@ func (u *dependencyUseCaseImpl) DetectCycleReport(ctx context.Context) (issueops // WalkDependencyTree passes the request straight through. // // No pre-check and no error wrapping, unlike GetDependencyTree below: the -// request's whole vocabulary is validated inside the shared body — one place, so -// all three backends refuse in the same words — and its refusals are typed -// sentinels both front doors classify. See the repository method for why the -// wrap is absent. +// request's whole vocabulary is validated inside the shared body, and its +// refusals are typed sentinels both front doors classify. func (u *dependencyUseCaseImpl) WalkDependencyTree(ctx context.Context, req issueops.WalkTreeRequest) (issueops.TreeResult, error) { return u.depRepo.WalkDependencyTree(ctx, req) } diff --git a/internal/storage/embeddeddolt/bootstrapper.go b/internal/storage/embeddeddolt/bootstrapper.go index 0cf6987a5..9a55a01d2 100644 --- a/internal/storage/embeddeddolt/bootstrapper.go +++ b/internal/storage/embeddeddolt/bootstrapper.go @@ -21,13 +21,10 @@ func (s *EmbeddedDoltStore) Bootstrapper() (issueops.Bootstrapper, error) { } // bootstrapper seeds a substrate's identity inside one connection's -// transaction. -// -// It is a sibling of the server-backed store's body rather than a shared -// package for the reason that one gives: the work needs a TRANSACTION, which -// storage.DoltStorage does not publish, so the sharing happens below both of -// them at issueops.BootstrapInTx. The two stores differ here only in how they -// reach a transaction. +// transaction. It is a sibling of the server-backed store's body rather than a +// shared package because the work needs a TRANSACTION, which +// storage.DoltStorage does not publish; the sharing happens below both of them +// at issueops.BootstrapInTx. type bootstrapper struct{ store *EmbeddedDoltStore } var _ issueops.Bootstrapper = (*bootstrapper)(nil) diff --git a/internal/storage/embeddeddolt/bootstrapper_contract_test.go b/internal/storage/embeddeddolt/bootstrapper_contract_test.go index 9b3449378..0d00b2b31 100644 --- a/internal/storage/embeddeddolt/bootstrapper_contract_test.go +++ b/internal/storage/embeddeddolt/bootstrapper_contract_test.go @@ -18,9 +18,8 @@ import ( // on the bodies. // // One environment for the whole suite, and here that is a correctness -// requirement rather than only a runtime one: the identity is global to a -// workspace, so the subtests run sequentially over one plane, each seeding the -// state it asserts about. +// requirement: the identity is global to a workspace, so the subtests run +// sequentially over one plane, each seeding the state it asserts about. func TestBootstrapperContract(t *testing.T) { skipUnlessEmbeddedDolt(t) te := newTestEnv(t, "boot") diff --git a/internal/storage/embeddeddolt/cycle_detector_contract_test.go b/internal/storage/embeddeddolt/cycle_detector_contract_test.go index 2334d18e1..fa4922a3a 100644 --- a/internal/storage/embeddeddolt/cycle_detector_contract_test.go +++ b/internal/storage/embeddeddolt/cycle_detector_contract_test.go @@ -13,9 +13,8 @@ import ( // TestCycleDetectorContract runs the CycleDetector contract against the embedded // store. It reaches the same tx-level body the server-backed store reaches -// (issueops.DetectCycleReportInTx) and differs only in the engine underneath; -// that is what this wiring catches, and it is not an independent vote on the -// body. +// (issueops.DetectCycleReportInTx) and differs only in the engine underneath, so +// it is an engine check rather than an independent vote on the body. // // One environment for the whole suite, and the subtests are sequential: the // report is global, so each case's cycles stay visible to the ones after it. @@ -63,10 +62,8 @@ func newEmbeddedCycleDetectorFixture(t *testing.T, te *testEnv, prefix string) c Detector: detector, CreateIssue: kit.CreateIssue, CreateWisp: kit.CreateWisp, - // The frozen kit exposes reads only. This is the write half of the same - // short-lived raw connection its QueryScalar opens, and RETURNS the - // error rather than failing the test, so the contract's own seeding - // failure message is the one a reader sees. + // The frozen kit exposes reads only, so this is the write half of the + // same short-lived raw connection its QueryScalar opens. // // One PINNED CONNECTION for the whole script, for the reason the // server-backed wiring gives: a foreign_key_checks toggle and the insert diff --git a/internal/storage/embeddeddolt/stats_reporter_contract_test.go b/internal/storage/embeddeddolt/stats_reporter_contract_test.go index e8c81f608..59f109374 100644 --- a/internal/storage/embeddeddolt/stats_reporter_contract_test.go +++ b/internal/storage/embeddeddolt/stats_reporter_contract_test.go @@ -15,8 +15,7 @@ import ( // vote rather than an engine check. The two stores share the role body // (internal/workapi/storestats), but the statistics QUERIES underneath are this // package's own: embeddeddolt/statistics.go writes its own blocked count and -// ready subtraction, in one connection where the server-backed store spends two -// read transactions. Only the status tally is shared code. +// ready subtraction. Only the status tally is shared code. // // One environment for the whole suite: booting an embedded engine per case // would dominate the runtime, and the delta assertions need the subtests diff --git a/internal/storage/embeddeddolt/sweeper.go b/internal/storage/embeddeddolt/sweeper.go index ed7897cc2..5e61265e3 100644 --- a/internal/storage/embeddeddolt/sweeper.go +++ b/internal/storage/embeddeddolt/sweeper.go @@ -20,15 +20,12 @@ func (s *EmbeddedDoltStore) Sweeper() (issueops.Sweeper, error) { return &sweeper{store: s}, nil } -// sweeper clears closed rows from one tier inside one connection's -// transaction. -// -// It is a sibling of the server-backed store's body rather than a shared -// package for the reason that one gives: the work needs a TRANSACTION, which -// storage.DoltStorage does not publish, so the sharing happens below both of -// them at issueops.SweepInTx. The two stores differ here only in how they -// reach a transaction and in whether they record a version-control entry — -// this one's commit runs outside the SQL transaction, so it records none. +// sweeper clears closed rows from one tier inside one connection's transaction. +// The work needs a TRANSACTION, which storage.DoltStorage does not publish, so +// the sharing with the server-backed store happens at issueops.SweepInTx. The +// two differ only in how they reach a transaction and in whether they record a +// version-control entry — this one's commit runs outside the SQL transaction, +// so it records none. type sweeper struct{ store *EmbeddedDoltStore } var _ issueops.Sweeper = (*sweeper)(nil) diff --git a/internal/storage/embeddeddolt/tree_walker_contract_test.go b/internal/storage/embeddeddolt/tree_walker_contract_test.go index 64e5d9f28..36f0d8a3c 100644 --- a/internal/storage/embeddeddolt/tree_walker_contract_test.go +++ b/internal/storage/embeddeddolt/tree_walker_contract_test.go @@ -15,8 +15,7 @@ import ( // store. It reaches the same tx-level body the server-backed store reaches // (issueops.WalkDependencyTreeInTx) and differs only in the engine underneath; // that is what this wiring catches, and it is NOT an independent vote on the -// body — see the note at the top of the contract file, which says so for all -// three legs of this particular role. +// body. // // One environment for the whole suite. Every case seeds ids under its own prefix // and asserts only about those, so the subtests are order-independent. @@ -93,10 +92,10 @@ func newEmbeddedTreeWalkerFixture(t *testing.T, te *testEnv, prefix string) conf CreateWisp: kit.CreateWisp, AddDependency: kit.AddDependency, // The frozen kit exposes reads only. This is the write half of the same - // short-lived raw connection its QueryScalar opens, and RETURNS the error - // rather than failing the test, so the contract's own seeding failure + // short-lived raw connection its QueryScalar opens, and RETURNS the + // error rather than failing the test, so the contract's own seeding // message is the one a reader sees. One PINNED CONNECTION for the whole - // script, as the server-backed wiring does. + // script. Exec: func(ctx context.Context, statements []conformance.SQLStatement) error { db, cleanup, err := embeddeddolt.OpenSQL(ctx, te.dataDir, te.database, "main") if err != nil { diff --git a/internal/storage/embeddeddolt/version_reconciler_contract_test.go b/internal/storage/embeddeddolt/version_reconciler_contract_test.go index 30c6283fa..bfba24b57 100644 --- a/internal/storage/embeddeddolt/version_reconciler_contract_test.go +++ b/internal/storage/embeddeddolt/version_reconciler_contract_test.go @@ -16,10 +16,9 @@ import ( // SetLocalMetadata, differing only in the engine underneath. That is what this // wiring catches; it is not an independent vote on the body. // -// One environment for the whole suite, and here that is a correctness -// requirement rather than only a runtime one: the two version markers are -// global to a workspace, so the subtests have to run sequentially over one -// plane, each seeding the state it asserts about. +// One environment for the whole suite, and that is a correctness requirement: +// the two version markers are global to a workspace, so the subtests have to +// run sequentially over one plane, each seeding the state it asserts about. func TestVersionReconcilerContract(t *testing.T) { skipUnlessEmbeddedDolt(t) te := newTestEnv(t, "vrec") diff --git a/internal/storage/embeddeddolt/workspace_config_contract_test.go b/internal/storage/embeddeddolt/workspace_config_contract_test.go index af713d161..6dba96c0f 100644 --- a/internal/storage/embeddeddolt/workspace_config_contract_test.go +++ b/internal/storage/embeddeddolt/workspace_config_contract_test.go @@ -10,15 +10,13 @@ import ( // TestWorkspaceConfigContract runs the WorkspaceConfig contract against the // embedded store, which hands back the SAME body the server-backed store does -// (internal/workapi/storeworkspaceconfig) and projects through the same -// SetConfig, differing only in the engine underneath. That is what this wiring -// catches; it is not an independent vote on the body. +// (internal/workapi/storeworkspaceconfig), differing only in the engine +// underneath. It is not an independent vote on the body. // -// One environment for the whole suite, and here that is a correctness -// requirement rather than only a runtime one: config keys are global to a -// workspace, the two projected keys are written by name, and the refused-write -// case takes a history delta — all of which need the subtests sequential over -// one plane. +// One environment for the whole suite, and here that is a CORRECTNESS +// requirement: config keys are global to a workspace, the two projected keys +// are written by name, and the refused-write case takes a history delta — all +// of which need the subtests sequential over one plane. func TestWorkspaceConfigContract(t *testing.T) { skipUnlessEmbeddedDolt(t) te := newTestEnv(t, "wcfg") diff --git a/internal/storage/hook_batch_creator.go b/internal/storage/hook_batch_creator.go index 752c7af5f..c56059dcc 100644 --- a/internal/storage/hook_batch_creator.go +++ b/internal/storage/hook_batch_creator.go @@ -27,10 +27,9 @@ type hookBatchCreator struct { // CreateBatch fires the create hook once PER ITEM, in request order, and fires // nothing at all when the batch refused — the batch is all or nothing, so a -// refusal created no issue for a script to be told about. Per item rather than -// once for the batch because a hook script is written against one issue: -// collapsing N creates into one firing would silently stop reporting N-1 of -// them. +// refusal created no issue for a script to be told about. Per item because a +// hook script is written against one issue: collapsing N creates into one +// firing would silently stop reporting N-1 of them. // // The edge list per item comes from the REQUEST, exactly as the single create's // does, because a reverse edge never appears in the created issue's own diff --git a/internal/storage/hook_bootstrapper.go b/internal/storage/hook_bootstrapper.go index 8341b0489..1cc8a274f 100644 --- a/internal/storage/hook_bootstrapper.go +++ b/internal/storage/hook_bootstrapper.go @@ -6,16 +6,13 @@ import ( // Bootstrapper returns the inner store's identity-seeding surface. // -// IT RECURSES UNWRAPPED even though the role WRITES, which is the same -// statement hook_sweeper.go makes and for the same reason: the decision is about -// the hook VOCABULARY, not about whether the role writes. This decorator -// publishes on_create, on_update and on_close, and every one of those hands a -// hook script an ISSUE. A bootstrap creates no issue — it makes a database into -// a workspace — so there is nothing this layer could fire that a hook script -// could read. +// IT RECURSES UNWRAPPED even though the role WRITES, as hook_sweeper.go does: +// the decision is about the hook VOCABULARY, not about whether the role writes. +// This decorator publishes on_create, on_update and on_close, and every one of +// those hands a hook script an ISSUE. A bootstrap creates no issue — it makes a +// database into a workspace. // -// There is a second reason here that the sweep does not have. A bootstrap -// happens on a workspace whose hooks are not installed yet: `bd init` writes +// There is a second reason here that the sweep does not have: `bd init` writes // .beads/hooks/ AFTER the identity lands, so a hook fired from this accessor // would run whatever the previous project in that directory left behind, or // nothing at all. The accessor still EXISTS on the decorator rather than being diff --git a/internal/storage/hook_deleter.go b/internal/storage/hook_deleter.go index 5b0fbcfa1..b9792d5a6 100644 --- a/internal/storage/hook_deleter.go +++ b/internal/storage/hook_deleter.go @@ -6,20 +6,16 @@ import ( // Deleter returns the inner store's named-row erasure surface. // -// IT RECURSES UNWRAPPED, for the reason hook_sweeper.go gives at length and -// which applies here unchanged: internal/hooks publishes on_create, on_update -// and on_close, and a deletion is none of them. Firing on_update for a row that -// no longer exists would hand a user's script an id it cannot read back, and -// the result this role returns carries counts rather than rows, so there is no -// issue to hand a hook script even if one existed. +// IT RECURSES UNWRAPPED, for the reason hook_sweeper.go gives: internal/hooks +// publishes on_create, on_update and on_close, and a deletion is none of them. // // THE ONE CASE THAT LOOKS LIKE AN EXCEPTION IS NOT. A deletion rewrites its // neighbors' text, and those rows survive an update — so an on_update hook // could in principle fire for them. It does not, deliberately: the rewrite is // a consequence of the deletion rather than an update a user asked for, and a // `bd delete` of one bead that fired a subprocess per neighbor would be a new -// failure mode wearing a feature's clothes. The direct CLI route this role -// replaces fired no hook for those updates either. +// failure mode. The direct CLI route this role replaces fired no hook for those +// updates either. // // So the accessor EXISTS on this decorator — declared, never inherited, which // the reflection test in role_accessor_decorator_test.go asserts — and adds no diff --git a/internal/storage/hook_sweeper.go b/internal/storage/hook_sweeper.go index 8fa6a410a..a205c25b5 100644 --- a/internal/storage/hook_sweeper.go +++ b/internal/storage/hook_sweeper.go @@ -6,19 +6,11 @@ import ( // Sweeper returns the inner store's bulk-clearance surface. // -// IT RECURSES UNWRAPPED, and this is the one WRITE role that does. The -// read roles recurse because nothing completed; this one completes plenty and -// still has no hook to fire, for two reasons that are both about the hook -// vocabulary rather than about the sweep: -// -// - there is no on_delete hook. internal/hooks publishes on_create, -// on_update and on_close, and a sweep is none of them. Firing on_update -// for a row that no longer exists would hand a user's script an id it -// cannot read back. -// - a hook script is handed an ISSUE, and a sweep's result carries counts -// rather than rows — deliberately, because a sweep of ten thousand wisps -// that materialized all ten thousand to fire a subprocess each would be a -// new failure mode rather than a feature. +// IT RECURSES UNWRAPPED, and this is the one WRITE role that does. There is no +// on_delete hook — internal/hooks publishes on_create, on_update and on_close, +// and firing on_update for a row that no longer exists would hand a user's +// script an id it cannot read back — and a hook script is handed an ISSUE where +// a sweep's result carries counts. // // So the accessor EXISTS on this decorator — declared, never inherited, which // the reflection test in role_accessor_decorator_test.go asserts — and adds no diff --git a/internal/storage/hook_version_reconciler.go b/internal/storage/hook_version_reconciler.go index eff82dbe5..81c6cb68b 100644 --- a/internal/storage/hook_version_reconciler.go +++ b/internal/storage/hook_version_reconciler.go @@ -6,19 +6,14 @@ import ( // VersionReconciler returns the inner store's version-marker surface. // -// It recurses, like every other accessor on this decorator, rather than being -// absent: the accessor set is uniform across the chain, so a caller never has -// to know which decorators a store is wearing. What it does NOT do is wrap the -// result, and here that is the same statement hook_workspace_config.go makes -// about a role that WRITES. -// -// This decorator's vocabulary is on_create / on_update / on_close, and every -// one of those hands a hook script an ISSUE. Recording which binary opened the -// workspace has no issue to name and no bead to describe, so there is nothing -// this layer could fire that a hook script could read. There is a second reason -// here that the settings role does not have: this one runs from PersistentPreRun -// on every startup, so a hook fired here would run a user's script before every -// command — including the ones that go on to fail on their own arguments. +// It recurses rather than being absent: the accessor set is uniform across the +// chain, so a caller never has to know which decorators a store is wearing. +// What it does NOT do is wrap the result. This decorator's vocabulary is +// on_create / on_update / on_close, and every one of those hands a hook script +// an ISSUE; recording which binary opened the workspace has no issue to name. +// There is a second reason the settings role does not have: this one runs from +// PersistentPreRun on every startup, so a hook fired here would run a user's +// script before every command. func (h *HookFiringStore) VersionReconciler() (issueops.VersionReconciler, error) { return h.inner.VersionReconciler() } diff --git a/internal/storage/hook_workspace_config.go b/internal/storage/hook_workspace_config.go index 802696b8f..ac20d22d1 100644 --- a/internal/storage/hook_workspace_config.go +++ b/internal/storage/hook_workspace_config.go @@ -6,19 +6,13 @@ import ( // WorkspaceConfig returns the inner store's workspace-settings surface. // -// It recurses, like every other accessor on this decorator, rather than being -// absent: the accessor set is uniform across the chain, so a caller never has -// to know which decorators a store is wearing. What it does NOT do is wrap the -// result, and here that is a statement about a WRITE role rather than the -// read-role statement hook_counter.go makes. -// -// This decorator's vocabulary is on_create / on_update / on_close, and every -// one of those hands the hook script an ISSUE. A settings write has no issue to -// name — it changes the workspace, not a bead — so there is nothing this layer -// could fire that a hook script could read. The legacy config path +// It recurses like every other accessor on this decorator rather than being +// absent, and does NOT wrap the result. This decorator's vocabulary is +// on_create / on_update / on_close, and every one of those hands the hook script +// an ISSUE; a settings write has no issue to name, so there is nothing this +// layer could fire that a hook script could read. The legacy config path // (HookFiringStore inherits SetConfig and DeleteConfig unchanged) fires nothing -// either, so wrapping here would not restore a hook that stopped firing; it -// would invent one. +// either, so wrapping here would not restore a hook — it would invent one. func (h *HookFiringStore) WorkspaceConfig() (issueops.WorkspaceConfig, error) { return h.inner.WorkspaceConfig() } diff --git a/internal/storage/issueops/blocking_annotation.go b/internal/storage/issueops/blocking_annotation.go index cf9fd6a6d..49ef3a99c 100644 --- a/internal/storage/issueops/blocking_annotation.go +++ b/internal/storage/issueops/blocking_annotation.go @@ -11,11 +11,8 @@ import ( // ValidateBlockingRequest applies the one request rule every BlockingAnnotator // implementation shares: an empty id entry is refused rather than answered -// with a nameless annotation. -// -// There is nothing else to validate. This role has no filter, no direction and -// no type vocabulary, and an empty ID SLICE asks about nothing and gets nothing -// back rather than being an error. +// with a nameless annotation. An empty ID SLICE asks about nothing and gets +// nothing back rather than being an error. func ValidateBlockingRequest(request publicops.BlockingRequest) error { for i, id := range request.IDs { if id == "" { @@ -30,11 +27,10 @@ func ValidateBlockingRequest(request publicops.BlockingRequest) error { // // It is one function rather than two copies for the reason FinishEdgeRead is: // the entry-per-id shape, the pinned order and the collapse of repeats are the -// whole observable contract of this role, and an implementation that applied -// them for itself is one the two will eventually disagree about. Both bodies -// below it answer with maps whose slice values arrive in query order and can -// carry the same id twice — once from each dependency tier — so this is also -// where that stops being visible. +// whole observable contract of this role, and two implementations applying them +// separately will eventually disagree. Both bodies below it answer with maps +// whose slice values arrive in query order and can carry the same id twice — +// once from each dependency tier. // // The maps are read, never written: the store body's caller owns them. func FinishBlockingAnnotation( diff --git a/internal/storage/issueops/bootstrap.go b/internal/storage/issueops/bootstrap.go index f981bac83..db97714bd 100644 --- a/internal/storage/issueops/bootstrap.go +++ b/internal/storage/issueops/bootstrap.go @@ -13,29 +13,23 @@ import ( // They live here rather than in an importable internal/workapi/store // package for the reason SweepInTx and DetectCycleReportInTx do: the work is a // read and the write it QUALIFIES, and those two must see one snapshot or the -// refusal is a suggestion. storage.DoltStorage publishes methods, not -// transactions, so a body written against it could only check-then-act. The two -// Dolt-backed stores share these bodies and differ only in how they reach a -// transaction, so they are ONE vote and the unit-of-work provider is the -// second. There is nothing here a front door could construct — both functions -// take a transaction — so no depguard entry is needed to keep them out of -// cmd/bd. +// refusal is a suggestion. The two Dolt-backed stores share these bodies and +// differ only in how they reach a transaction, so they are ONE vote and the +// unit-of-work provider is the second. // BootstrapInTx seeds an unidentified substrate's identity, refusing an // identified one, inside ONE transaction. // // It assumes a request already normalized and refused by -// workapi.ValidateBootstrapRequest. The accessors validate BEFORE opening a -// transaction, so a refused request costs no database work. +// workapi.ValidateBootstrapRequest, which the accessors run BEFORE opening a +// transaction. // // THE READ AND THE WRITE SHARE THE TRANSACTION, which is the whole reason this -// body is shaped as a function over a *sql.Tx. Two inits racing against one -// shared database is not hypothetical — it is the ordinary case for a -// bts-provisioned server and for two rigs pointed at one Dolt database — and a +// body is shaped as a function over a *sql.Tx: two inits racing against one +// shared database is the ordinary case for a bts-provisioned server, and a // refusal decided outside the transaction that writes is one both racers pass. // -// The per-clone bookkeeping `bd init` seeds alongside the identity — the -// fingerprints, the synced-at marker, the recorded binary version — is not here +// The per-clone bookkeeping `bd init` seeds alongside the identity is not here // and not on the role; see issueops.Bootstrapper for why. func BootstrapInTx(ctx context.Context, tx DBTX, req publicops.BootstrapRequest) (publicops.BootstrapResult, error) { prefix, projectID, err := verifyIdentityInTx(ctx, tx) @@ -66,10 +60,9 @@ func VerifyIdentityInTx(ctx context.Context, tx DBTX) (publicops.VerifyIdentityR } // verifyIdentityInTx reads the pair the bootstrap refusal and the verifier both -// ask about, so the two cannot come to disagree about what "identified" means. -// -// Both reads happen even when the first already decides the outcome: the -// verifier publishes the pair, and the refusal names both values. +// ask about, so the two cannot disagree about what "identified" means. Both +// reads happen even when the first already decides the outcome: the verifier +// publishes the pair, and the refusal names both values. func verifyIdentityInTx(ctx context.Context, tx DBTX) (prefix, projectID string, err error) { prefix, err = GetConfigInTx(ctx, tx, workapi.ConfigKeyIssuePrefix) if err != nil { diff --git a/internal/storage/issueops/create_batch.go b/internal/storage/issueops/create_batch.go index 1eac22768..6c559d78e 100644 --- a/internal/storage/issueops/create_batch.go +++ b/internal/storage/issueops/create_batch.go @@ -26,15 +26,13 @@ func CloneCreateBatchRequest(request publicops.CreateBatchRequest) publicops.Cre } // ValidateCreateBatchRequest applies the request rules every BatchCreator -// implementation shares, so a rule is a contract rather than one backend's -// habit. It runs BEFORE any transaction opens: everything it checks is -// knowable from the request alone, and a batch refused here has provably -// written nothing. +// implementation shares. It runs BEFORE any transaction opens: everything it +// checks is knowable from the request alone, so a batch refused here has +// provably written nothing. // // Per-item CONTENT rules are not here. They need the workspace's configured -// prefix, statuses and types, so they run against the create context inside the -// transaction — through the same PreparePublicCreateRequest a single create -// runs, which is what keeps an item's rules identical to Lifecycle.Create's. +// prefix, statuses and types, so they run inside the transaction through the +// same PreparePublicCreateRequest a single create runs. func ValidateCreateBatchRequest(request publicops.CreateBatchRequest) error { if request.Actor == "" { return fmt.Errorf("%w: create batch requires an actor", storage.ErrValidation) @@ -51,9 +49,8 @@ func ValidateCreateBatchRequest(request publicops.CreateBatchRequest) error { } // CreateBatchItemRequest projects one item onto the single-create request the -// shared preparation and validation speak. It is the whole reason an item does -// not have to restate CreateRequest's field rules: both front doors and both -// bodies read an item through this one projection. +// shared preparation and validation speak. Both front doors and both bodies read +// an item through it, so no item restates CreateRequest's field rules. func CreateBatchItemRequest(request publicops.CreateBatchRequest, item publicops.BatchCreateItem) publicops.CreateRequest { return publicops.CreateRequest{ Actor: request.Actor, @@ -64,8 +61,7 @@ func CreateBatchItemRequest(request publicops.CreateBatchRequest, item publicops } // CreateBatchItemError names the item a batch refusal came from. The role -// promises the index appears in the message and nowhere else, so this is the -// one place that spells it. +// promises the index appears in the message and nowhere else. func CreateBatchItemError(index int, err error) error { return fmt.Errorf("create batch item %d: %w", index, err) } @@ -73,19 +69,14 @@ func CreateBatchItemError(index int, err error) error { // CreateBatchCommitMessage is the history entry a batch records: the caller's // own label when it supplied one, otherwise a default naming how much landed. // -// IT NAMES A COUNT AND NEVER AN ID, which is where it differs from -// CloseBatchCommitMessage. A close batch names the ids it closed because a -// close is a fact about rows the reader already knows; a create batch's ids are -// new, there can be hundreds of them from one file, and the entry that named -// them all would be the diff written out twice. +// IT NAMES A COUNT AND NEVER AN ID: a create batch's ids are new, there can be +// hundreds from one file, and an entry naming them all is the diff written twice. // -// The ephemeral wording is not decoration. An all-ephemeral batch writes only -// to the dolt-ignored wisp tables, so the store-backed bodies stage nothing and -// record no entry whatever this returns — but the unit-of-work backend reads "" -// as "roll this attempt back", so a wisp-only batch must still hand it a -// message or the wisps it created are discarded. That is the same trap -// CloseBatchCommitMessage documents, and the count is how both are answered -// without naming a wisp id in a durable entry. +// An all-ephemeral batch writes only to the dolt-ignored wisp tables, so the +// store-backed bodies stage nothing and record no entry whatever this returns — +// but the unit-of-work backend reads "" as "roll this attempt back", so a +// wisp-only batch must still hand it a message or the wisps it created are +// discarded. That is the same trap CloseBatchCommitMessage documents. func CreateBatchCommitMessage(request publicops.CreateBatchRequest, result publicops.CreateBatchResult) string { durable, ephemeral := 0, 0 for _, issue := range result.Issues { @@ -110,21 +101,17 @@ func CreateBatchCommitMessage(request publicops.CreateBatchRequest, result publi } // ExecuteCreateBatch creates every item in tx and reports the durable tables -// changed. It is the store-backed body behind the BatchCreator accessor; the -// unit-of-work provider has its own, for the same reason Lifecycle does. +// changed. It is the store-backed body behind the BatchCreator accessor. // -// THE ITEMS ARE PREPARED FIRST AND WRITTEN ONCE. Each item goes through the -// same PreparePublicCreateRequest a single create goes through — so an item's -// content rules ARE Lifecycle.Create's, rather than a second copy of them — and -// each is assigned its id before any row is written, which is what lets an -// item's edge name an item created earlier in the same batch. The rows and -// their edges then land through ONE CreateIssuesInTxWithResult, which is what -// makes the batch one act rather than N. +// THE ITEMS ARE PREPARED FIRST AND WRITTEN ONCE. Each goes through the same +// PreparePublicCreateRequest a single create goes through, and each is assigned +// its id before any row is written, which is what lets an item's edge name an +// item created earlier in the same batch. The rows and their edges then land +// through ONE CreateIssuesInTxWithResult. // // ANY error returns, and the enclosing transaction rolls the whole batch back. // That includes an edge the engine declined to write: the batch engine drops a -// dangling edge so a partial import can still land, and this role refuses -// instead, exactly as ExecuteCreate does and for the reason it gives. +// dangling edge so a partial import can still land, and this role refuses. func ExecuteCreateBatch(ctx context.Context, tx *sql.Tx, request publicops.CreateBatchRequest) (publicops.CreateBatchResult, ChangedTables, error) { attempt := CloneCreateBatchRequest(request) if err := ValidateCreateBatchRequest(attempt); err != nil { @@ -155,9 +142,8 @@ func ExecuteCreateBatch(ctx context.Context, tx *sql.Tx, request publicops.Creat } issue := prepared.Issue // Configured infra types live in the wisp tables, the same routing - // ExecuteCreate applies. Mark the issue before its ID is assigned so ID - // generation, the create-only guard and table routing all agree on the - // destination; a no-history create keeps its own retention mode. + // ExecuteCreate applies. Mark the issue BEFORE its ID is assigned so ID + // generation, the create-only guard and table routing all agree. if !issue.Ephemeral && !issue.NoHistory && infraTypes[string(issue.IssueType)] { issue.Ephemeral = true } @@ -182,8 +168,7 @@ func ExecuteCreateBatch(ctx context.Context, tx *sql.Tx, request publicops.Creat // CreateIssuesDirtyTables reports the child_counters advance itself, from // the reconciliation the batch engine already ran, so there is no separate - // counter bookkeeping here the way ExecuteCreate needs for the parent it - // mints a child id under. + // counter bookkeeping here. tables := ChangedTables{} tables.Merge(CreateIssuesDirtyTables(ctx, issues, created)) result := publicops.CreateBatchResult{Issues: make([]*types.Issue, len(issues))} diff --git a/internal/storage/issueops/cycle_report.go b/internal/storage/issueops/cycle_report.go index 8f53b1b18..cc772173c 100644 --- a/internal/storage/issueops/cycle_report.go +++ b/internal/storage/issueops/cycle_report.go @@ -11,26 +11,20 @@ import ( // The cycle REPORT: the shared body behind issueops.CycleDetector on all three // backends, split into a pure half and a transactional half so the part that // decides what the answer MEANS is testable without a database. -// // CanonicalCyclePaths holds the determinism ruling and BuildCycles the -// honest-partial one; both are pure, so both are pinned in -// cycle_report_test.go without a database. DetectCycleReportInTx is the only -// part that needs a transaction. +// honest-partial one; both are pinned in cycle_report_test.go. // CanonicalCyclePaths returns the cycles of a blocking graph as id paths, in a // canonical form: each path rotated so its lowest id comes first, and the paths // sorted against each other. // // EVERY SOURCE OF NONDETERMINISM IS REMOVED HERE, not just the order of the -// answer, because ordering the answer would not have been enough. A depth-first -// cycle enumeration records one cycle per BACK EDGE, and which edges are back -// edges depends on the walk: the roots came off a Go map and the adjacency lists -// came out of an unordered SQL read, so two runs against an unchanged database -// could disagree about which cycles exist at all, not merely about their order. -// Sorting the roots and the neighbors fixes the walk; rotating and sorting fix -// the presentation. +// answer. A depth-first cycle enumeration records one cycle per BACK EDGE, and +// which edges are back edges depends on the walk: the roots came off a Go map +// and the adjacency lists came out of an unordered SQL read, so two runs against +// an unchanged database could disagree about which cycles exist at all. // -// Duplicate neighbors are collapsed. A parallel edge adds nothing to +// Duplicate neighbors are collapsed: a parallel edge adds nothing to // reachability, and left in place it would make the same back edge report the // same cycle twice. // @@ -87,10 +81,9 @@ func CanonicalCyclePaths(graph map[string][]string) [][]string { } // rotateToLowest returns a copy of a cycle path rotated so its lowest id comes -// first, preserving edge order. -// -// The members of a cycle are distinct — the path it is taken from is a simple -// path — so the lowest id is unique and names exactly one rotation. +// first, preserving edge order. The members of a cycle are distinct — the path +// it is taken from is a simple path — so the lowest id is unique and names +// exactly one rotation. func rotateToLowest(path []string) []string { lowest := 0 for i, id := range path { @@ -109,13 +102,11 @@ func rotateToLowest(path []string) []string { // // A LOOKUP THAT FINDS NOTHING DOES NOT FAIL THE REPORT and does not shorten the // path: hydrate answers nil, the member keeps its id, and the cycle is marked -// partial. Both halves of that are deliberate. Failing outright would throw away -// what the walk learned about every other cycle over one unreadable row — and -// the rows that are unreadable here are the ordinary ones: an edge into another +// partial. The unreadable rows are the ordinary ones — an edge into another // repository's namespace, an "external:" reference, a row whose edges outlived // it. Dropping the member instead, which is what this used to do, rendered a // three-node cycle as a two-node one and dropped a wholly unreadable cycle out -// of the report and out of its count entirely. +// of the report entirely. // // hydrate is a plain lookup rather than a transaction so that the rule above is // testable without a database; DetectCycleReportInTx supplies the real one. @@ -141,19 +132,17 @@ func BuildCycles(paths [][]string, hydrate func(id string) *types.Issue) []publi } // DetectCycleReportInTx is the whole read: build the blocking graph across both -// planes, canonicalize it, and hydrate what it can. -// -// It reads the same two tables and the same two edge types DetectCyclesInTx -// reads, because it is the same question — this is the shape the answer has now. +// planes, canonicalize it, and hydrate what it can. It reads the same two tables +// and the same two edge types DetectCyclesInTx reads, because it is the same +// question. func DetectCycleReportInTx(ctx context.Context, tx DBTX) (publicops.CycleReport, error) { graph := make(map[string][]string) if err := AppendBlockingGraphInTx(ctx, tx, cycleDetectionTables(), graph); err != nil { return publicops.CycleReport{}, err } hydrate := func(id string) *types.Issue { - // The error is deliberately not distinguished from a miss. Neither is - // something a caller could act on differently, and both mean the same - // thing to the answer: this database did not describe the node. + // The error is deliberately not distinguished from a miss: both mean the + // same thing to the answer, that this database did not describe the node. issue, _ := GetIssueInTx(ctx, tx, id) return issue } diff --git a/internal/storage/issueops/cycle_report_test.go b/internal/storage/issueops/cycle_report_test.go index dcd959607..985418558 100644 --- a/internal/storage/issueops/cycle_report_test.go +++ b/internal/storage/issueops/cycle_report_test.go @@ -14,10 +14,9 @@ import ( // in pure functions precisely so they can be pinned here, in milliseconds, // instead of only through three backends that each need a server. // -// The conformance contract in backend/conformance still runs the same clauses -// against real storage. What it cannot do is seed a graph that exercises the -// walk itself: cycles are refused at write time on every backend, so a contract -// case can build one small cycle and not the branchy graphs below. +// The conformance contract in backend/conformance runs the same clauses against +// real storage, but cycles are refused at write time on every backend, so a +// contract case can seed one small cycle and not the branchy graphs below. func TestCanonicalCyclePathsRotatesEachCycleToItsLowestID(t *testing.T) { // One 3-cycle, spelled starting from each of its three nodes. The walk's @@ -50,12 +49,10 @@ func TestCanonicalCyclePathsSortsTheCycles(t *testing.T) { // TestCanonicalCyclePathsIsIndependentOfMapOrder is the case Q4 exists for. // -// It re-runs the SAME graph, rebuilt each time with its keys and adjacency -// lists in a fresh random order, and demands byte-identical answers. The -// previous implementation walked the graph map directly and appended neighbours -// in SQL row order, so the answer moved between runs — including under --json, -// where a caller diffing two snapshots of an unchanged database saw changes that -// were not changes. +// The previous implementation walked the graph map directly and appended +// neighbours in SQL row order, so the answer moved between runs — including +// under --json, where a caller diffing two snapshots of an unchanged database +// saw changes that were not changes. // // The graph is deliberately branchy and multi-cyclic: with one isolated cycle // nondeterminism can only reorder the answer, but with overlapping cycles a diff --git a/internal/storage/issueops/delete.go b/internal/storage/issueops/delete.go index e77effe76..6764f6e8f 100644 --- a/internal/storage/issueops/delete.go +++ b/internal/storage/issueops/delete.go @@ -76,23 +76,19 @@ func deleteIssueRowInTx(ctx context.Context, tx *sql.Tx, id string, isWisp bool) // DeletionSet is the EXACT set of rows one delete removes, split by the plane // each row lives in. // -// IT EXISTS BECAUSE THE SET USED TO BE COMPUTED TWICE. DeleteInTx expanded the -// cascade from every named id while DeleteIssuesInTx expanded it from the -// DURABLE named ids only, so `bd delete --cascade` left a durable row -// reachable only through that wisp alive and then rewrote its neighbors' text -// to say `[deleted:]` about it. Resolving once and passing the value down -// is what makes that class of drift impossible rather than merely fixed: the -// neighborhood read, the deletion and the reference rewrite all take THIS -// value. +// IT EXISTS BECAUSE THE SET USED TO BE COMPUTED TWICE, from different roots, so +// `bd delete --cascade` left a durable row reachable only through that +// wisp alive and then rewrote its neighbors' text to say `[deleted:]` about +// it. The neighborhood read, the deletion and the reference rewrite all take +// THIS value. type DeletionSet struct { // WispIDs and RegularIDs partition All by plane. The two tiers are deleted // through different tables and their associated rows counted from // different ones, so the split is carried rather than recomputed. WispIDs []string RegularIDs []string - // All is the whole set in one slice. It is what a caller scopes a - // neighborhood read or a citation rewrite to, and it is the answer to - // "which rows is this delete about" that nothing else may recompute. + // All is the whole set in one slice — what a caller scopes a neighborhood + // read or a citation rewrite to, and what nothing else may recompute. All []string } @@ -102,13 +98,9 @@ type DeletionSet struct { // // THE CASCADE IS ROOTED AT EVERY NAMED ID, WISPS INCLUDED. Rooting it at the // durable half is what made `bd wisp gc` (which hardcodes cascade) silently -// under-delete, and it is the half of the drift that cost rows rather than -// text. It matches what DeleteRequest.Cascade promises — "the TRANSITIVE -// CLOSURE of everything that depends on the named rows, in both planes" — and -// what domain.issueUseCase.deleteMany, the other Deleter body, already did. -// -// It does not read the caller's slice destructively: the non-cascade set is a -// copy, because DeleteRequest promises IDs is never sorted in place. +// under-delete. It does not read the caller's slice destructively either: the +// non-cascade set is a copy, because DeleteRequest promises IDs is never +// sorted in place. func ResolveDeletionSetInTx(ctx context.Context, tx DBTX, ids []string, cascade bool) (DeletionSet, error) { all := append([]string(nil), ids...) if cascade { @@ -140,9 +132,6 @@ func DeleteIssuesInTx(ctx context.Context, tx *sql.Tx, ids []string, cascade boo var orphaned []string if !cascade { - // Without cascade the set is exactly the named ids, so set.RegularIDs - // is their durable half. - // // The guard here is the STORAGE SEAM's, and it stays durable-only: the // server-backed store peels wisps off before it ever reaches this // function (dolt/issues.go DeleteIssues), so widening it would make the @@ -152,10 +141,9 @@ func DeleteIssuesInTx(ctx context.Context, tx *sql.Tx, ids []string, cascade boo for _, id := range ids { idSet[id] = true } - // One scan of the dependency planes answers both modes: the guard - // needs to know WHICH id is blocked, and the forced path needs the - // union of what it orphans. ExternalDependentsBySourceInTx gives the - // per-source shape both read. + // One scan of the dependency planes answers both modes: the guard needs + // to know WHICH id is blocked, and the forced path needs the union of + // what it orphans. external, err := ExternalDependentsBySourceInTx(ctx, tx, set.RegularIDs, idSet) if err != nil { return nil, fmt.Errorf("get dependents: %w", err) @@ -191,8 +179,7 @@ func DeleteIssuesInTx(ctx context.Context, tx *sql.Tx, ids []string, cascade boo // // It is split out of DeleteIssuesInTx so the role body can read the // neighborhood BEFORE the delete and rewrite it AFTER against the SAME -// DeletionSet the delete was handed. A caller that recomputed either end of -// that instead is the bug DeletionSet documents. +// DeletionSet the delete was handed. // //nolint:gosec // G201: inClause contains only ? placeholders func DeleteResolvedSetInTx(ctx context.Context, tx *sql.Tx, set DeletionSet, dryRun bool) (*types.DeleteIssuesResult, error) { diff --git a/internal/storage/issueops/delete_role.go b/internal/storage/issueops/delete_role.go index 6d79689dc..0920f8180 100644 --- a/internal/storage/issueops/delete_role.go +++ b/internal/storage/issueops/delete_role.go @@ -17,30 +17,22 @@ import ( // // It lives here rather than in an importable internal/workapi/store // package for the reason SweepInTx does: the work is several reads and several -// writes that must see one snapshot, and storage.DoltStorage publishes -// methods, not transactions. The two Dolt-backed stores share this body and -// differ only in how they reach a transaction, so they are ONE vote and the -// unit-of-work provider is the second. There is nothing here a front door -// could construct — the function takes a transaction — so no depguard entry is -// needed to keep it out of cmd/bd. +// writes that must see one snapshot. // // It assumes a request already refused by workapi.ValidateDeleteRequest and // already normalized by workapi.NormalizeDeleteIDs. The accessors do both // BEFORE opening a transaction, so a malformed request costs no database work. // -// THE REWRITE IS INSIDE THE TRANSACTION, and that is what this body adds over -// the code it replaces. The direct CLI route's batch path deleted the rows in -// one transaction and then rewrote the neighbors' text through the store -// afterwards, discarding each update's error; a failure between the two left a -// workspace whose rows were gone and whose descriptions still cited them. +// THE REWRITE IS INSIDE THE TRANSACTION. A route that deleted the rows in one +// transaction and rewrote the neighbors' text afterwards left, on a failure +// between the two, a workspace whose rows were gone and whose descriptions +// still cited them. func DeleteInTx(ctx context.Context, tx *sql.Tx, req publicops.DeleteRequest) (publicops.DeleteResult, error) { ids := req.IDs result := publicops.DeleteResult{DryRun: req.DryRun} // The existence probe comes FIRST, so `bd delete typo real` reports the // typo rather than whatever the graph says about the id that resolved. - // It doubles as the hydration the rewrite needs later: an id present here - // is a row in one of the two planes. wispSet, err := WispIDSetInTx(ctx, tx, ids) if err != nil { return publicops.DeleteResult{}, fmt.Errorf("delete: classify planes: %w", err) @@ -74,10 +66,7 @@ func DeleteInTx(ctx context.Context, tx *sql.Tx, req publicops.DeleteRequest) (p // about dependents. Under Cascade there is nothing outside the set by // construction, which is why the expansion below is not asked about it. // - // IT ASKS ABOUT EVERY NAMED ID, IN BOTH PLANES. It used to ask only about - // the durable half, so a wisp named with a durable dependent was neither - // refused unforced nor reported as orphaning when forced, and the - // cross-plane edge it removed went uncounted. The leaf says "a NAMED ROW + // IT ASKS ABOUT EVERY NAMED ID, IN BOTH PLANES: the leaf says "a NAMED ROW // that some row OUTSIDE the request depends on is refused" with no wisp // exemption, and the unit-of-work body has always read it that way. if !req.Cascade { @@ -107,16 +96,11 @@ func DeleteInTx(ctx context.Context, tx *sql.Tx, req publicops.DeleteRequest) (p } } - // THE DELETION SET IS RESOLVED ONCE, HERE, and the same value reaches all - // three of the reads and writes that must agree about it: the - // neighborhood read, the deletion, and the citation rewrite. - // - // It used to be resolved twice — once here for the rewrite from ALL ids, - // once inside DeleteIssuesInTx for the deletion from the DURABLE ids — and - // the two drifted. A cascade rooted at a wisp put the wisp's dependents in - // the rewrite set and not in the delete, so those rows survived and their - // neighbors' descriptions were rewritten to call them deleted. See - // DeletionSet. + // THE DELETION SET IS RESOLVED ONCE, HERE, and the same value reaches the + // neighborhood read, the deletion and the citation rewrite. Resolving it + // twice drifts: a cascade rooted at a wisp landed in the rewrite set and not + // in the delete, so those rows survived and their neighbors' descriptions + // were rewritten to call them deleted. See DeletionSet. set, err := ResolveDeletionSetInTx(ctx, tx, ids, req.Cascade) if err != nil { return publicops.DeleteResult{}, fmt.Errorf("delete: %w", err) @@ -132,8 +116,7 @@ func DeleteInTx(ctx context.Context, tx *sql.Tx, req publicops.DeleteRequest) (p } // No guard argument to pass: this body has ALREADY answered the guard - // question above and holds the orphan list it produced, and - // DeleteResolvedSetInTx deletes what it is handed without asking again. + // question above, and DeleteResolvedSetInTx deletes what it is handed. deleted, err := DeleteResolvedSetInTx(ctx, tx, set, req.DryRun) if err != nil { return publicops.DeleteResult{}, err @@ -162,10 +145,8 @@ func DeleteInTx(ctx context.Context, tx *sql.Tx, req publicops.DeleteRequest) (p // dependents that idSet does not contain — the rows a forced delete orphans // and an unforced one refuses over. // -// It reads both dependency planes and skips a missing wisp plane, the way -// every other cross-plane read here does. The per-source shape is what lets -// the unforced refusal name ONE blocked id instead of a flat union that -// answers "something is blocked". +// The per-source shape is what lets the unforced refusal name ONE blocked id +// instead of a flat union that answers "something is blocked". // //nolint:gosec // G201: inClause contains only ? placeholders func ExternalDependentsBySourceInTx(ctx context.Context, tx DBTX, ids []string, idSet map[string]bool) (map[string][]string, error) { @@ -223,9 +204,8 @@ func ExternalDependentsBySourceInTx(ctx context.Context, tx DBTX, ids []string, // by a dependency edge in either direction — the rows whose text the deletion // rewrites. // -// One query per plane over the whole set rather than the two per deleted id -// the CLI route used, because the neighborhood of a `--from-file` batch is -// asked for once here and the route asked for it 2N times. +// One query per plane over the whole set, so a `--from-file` batch costs two +// queries rather than two per deleted id. // //nolint:gosec // G201: inClause contains only ? placeholders func deleteNeighborsInTx(ctx context.Context, tx DBTX, ids []string) ([]*types.Issue, error) { diff --git a/internal/storage/issueops/edges.go b/internal/storage/issueops/edges.go index 7e3426f97..686a8861c 100644 --- a/internal/storage/issueops/edges.go +++ b/internal/storage/issueops/edges.go @@ -12,13 +12,10 @@ import ( ) // ValidateEdgeReadRequest applies the request rules every EdgeReader -// implementation shares. -// -// There are only two, and both are about telling a caller's mistake from a -// legitimately empty answer. An empty ID entry names nothing, so it is refused -// rather than reported as a missing anchor with no name; an unusable dependency -// type is refused rather than becoming a filter that silently matches nothing. -// An empty ID SLICE is neither: it asks about no anchors and gets none back. +// implementation shares. Both tell a caller's mistake from a legitimately empty +// answer: an empty ID entry names nothing, and an unusable dependency type would +// become a filter that silently matches nothing. An empty ID SLICE is neither — +// it asks about no anchors and gets none back. func ValidateEdgeReadRequest(request publicops.EdgeReadRequest) error { for i, id := range request.IDs { if id == "" { @@ -37,15 +34,10 @@ func ValidateEdgeReadRequest(request publicops.EdgeReadRequest) error { // EdgeReadAnchors is the de-duplicated anchor list a read runs against: the // request's ids with repeats collapsed onto their first mention. // -// It is a shared function rather than a loop in each implementation because the -// de-duplication decides the SHAPE of the answer — one entry per distinct id, -// in first-mention order — and an implementation that skipped it would return a -// different number of anchors than its sibling for the same request. -// -// Every batch-anchored role collapses its ids this way and reaches it here: -// BlockingAnnotator makes the same promise over the same shape of request -// (blocking_annotation.go), and the two making it out of one function is what -// keeps "repeats collapse" from meaning two things. +// It is shared rather than a loop in each implementation because the +// de-duplication decides the SHAPE of the answer — one entry per distinct id, in +// first-mention order. BlockingAnnotator makes the same promise over the same +// shape of request (blocking_annotation.go) and reaches it here too. func EdgeReadAnchors(ids []string) []string { seen := make(map[string]struct{}, len(ids)) out := make([]string, 0, len(ids)) @@ -62,16 +54,13 @@ func EdgeReadAnchors(ids []string) []string { // FinishEdgeRead assembles the per-anchor answer from the two things every // implementation reads: which anchors exist, and the edges keyed by source. // -// It is one function rather than two copies for the reason FinishRelatedPage -// is: the type filter, the pinned order and the empty-versus-absent -// distinction are the whole observable contract of this role, and an -// implementation that applied them for itself is one the two will eventually -// disagree about. +// It is one function rather than two copies because the type filter, the pinned +// order and the empty-versus-absent distinction are the whole observable +// contract of this role. // // THE ORDER is ascending by target id, with the edge type breaking a tie. The // row's own surrogate key is deliberately not a third term — the source-keyed -// read does not select it, so it is empty on every row here and sorting by it -// would be sorting by nothing. +// read does not select it, so it is empty on every row here. func FinishEdgeRead(anchors []string, present map[string]struct{}, edges map[string][]*types.Dependency, depTypes []types.DependencyType) publicops.EdgeReadResult { allowed := make(map[types.DependencyType]struct{}, len(depTypes)) for _, depType := range depTypes { @@ -84,8 +73,7 @@ func FinishEdgeRead(anchors []string, present map[string]struct{}, edges map[str entry := publicops.AnchorEdges{ID: id, Missing: !exists, Edges: []*types.Dependency{}} // A missing anchor carries no edges even if rows are keyed to it: a // dependency row whose source has been deleted is orphaned data, and - // reporting it under an anchor this call just said does not exist would - // contradict the flag beside it. + // reporting it would contradict the flag beside it. if exists { for _, edge := range edges[id] { if edge == nil { @@ -112,13 +100,12 @@ func FinishEdgeRead(anchors []string, present map[string]struct{}, edges map[str // ExecuteEdgeRead returns each anchor's stored outgoing edges in tx. It is the // store-backed body behind the EdgeReader accessor; the unit-of-work provider -// has its own, which reaches the same two reads through its use cases. +// reaches the same two reads through its use cases. // // The existence probe and the edge read share ONE transaction, which is what // lets AnchorEdges.Missing mean what it says: a probe in its own transaction -// could report an anchor missing and then a second transaction could return -// that anchor's edges, and the answer would contradict itself in a single -// response body. +// could report an anchor missing while a second transaction returned that +// anchor's edges, contradicting itself in one response body. func ExecuteEdgeRead(ctx context.Context, tx DBTX, request publicops.EdgeReadRequest) (publicops.EdgeReadResult, error) { anchors := EdgeReadAnchors(request.IDs) if len(anchors) == 0 { @@ -137,9 +124,8 @@ func ExecuteEdgeRead(ctx context.Context, tx DBTX, request publicops.EdgeReadReq // PresentIssueOrWispIDsInTx reports which of ids exist, on either plane. It is // the batched form of RequireIssueOrWispInTx, and it answers with a set rather -// than an error for the same reason the role reports Missing per anchor: a -// batch that failed on the first absent id would throw away the answers for the -// ids that were found. +// than an error because a batch that failed on the first absent id would throw +// away the answers for the ids that were found. // // A missing wisps table is "no wisps", exactly as the single-id probe treats // it: older schemas predate that plane and an anchor there is simply not one. diff --git a/internal/storage/issueops/sweep.go b/internal/storage/issueops/sweep.go index a0505f0bf..a99b67474 100644 --- a/internal/storage/issueops/sweep.go +++ b/internal/storage/issueops/sweep.go @@ -15,25 +15,19 @@ import ( // transaction. // // It lives here rather than in an importable internal/workapi/store -// package for the reason DetectCycleReportInTx does: the work is several reads -// and a write that must see one snapshot, and storage.DoltStorage publishes -// methods, not transactions. The two Dolt-backed stores share this body and -// differ only in how they reach a transaction, so they are ONE vote and the -// unit-of-work provider is the second. There is nothing here a front door -// could construct — the function takes a transaction — so no depguard entry is -// needed to keep it out of cmd/bd. +// package because the work is several reads and a write that must see one +// snapshot, and storage.DoltStorage publishes methods, not transactions. The +// two Dolt-backed stores share this body, so they are ONE vote and the +// unit-of-work provider is the second. // // It assumes a request already refused by workapi.ValidateSweepRequest. The // accessors validate BEFORE opening a transaction, so a refusal costs no -// database work and, as issueops.Sweeper promises, changes nothing. +// database work. // -// ONE TRANSACTION IS THE POINT. The direct CLI route this replaces searched in -// one transaction and deleted in another, so a row closed, unpinned or cited -// between the two was reported as one thing and treated as another. It is also -// what this gives up: the server-backed store's own DeleteIssues splits large -// wisp deletions into batched transactions to stay inside Dolt's write -// timeout, and a sweep cannot both do that and promise that the set it counted -// is the set it deleted. It promises the latter. +// WHAT ONE TRANSACTION GIVES UP: the server-backed store's own DeleteIssues +// splits large wisp deletions into batched transactions to stay inside Dolt's +// write timeout, and a sweep cannot both do that and promise that the set it +// counted is the set it deleted. It promises the latter. func SweepInTx(ctx context.Context, tx *sql.Tx, req publicops.SweepRequest) (publicops.SweepResult, error) { result := publicops.SweepResult{DryRun: req.DryRun} @@ -65,12 +59,9 @@ func SweepInTx(ctx context.Context, tx *sql.Tx, req publicops.SweepRequest) (pub } // cascade=false, force=true: a sweep deletes what it selected and ORPHANS - // dependents outside the selection, which is what the direct route has - // always done for a real run. The DRY RUN passes the same flags rather - // than the force=false the route used to pass, so a preview reports what - // the sweep would do instead of refusing over dependents the sweep would - // have orphaned — the old dry run could fail where the real run succeeded, - // and the CLI answered that failure with zeros. + // dependents outside the selection. The DRY RUN passes the same flags rather + // than the force=false the direct route used to pass, so a preview cannot + // fail where the real run would succeed. deleted, err := DeleteIssuesInTx(ctx, tx, ids, false, true, req.DryRun) if err != nil { return publicops.SweepResult{}, err @@ -86,10 +77,10 @@ func SweepInTx(ctx context.Context, tx *sql.Tx, req publicops.SweepRequest) (pub // is not done, reading the not-done set and its comments on the SAME // transaction the candidates came off. // -// Reading the workspace's custom statuses is required rather than -// best-effort: an error propagates and aborts the sweep, because a scan that -// silently missed a custom active status would under-protect and delete a bead -// a live bead still cites (issueops.SweepRequest.ProtectReferenced). +// Reading the workspace's custom statuses is required rather than best-effort: +// an error aborts the sweep, because a scan that silently missed a custom active +// status would under-protect and delete a bead a live bead still cites +// (issueops.SweepRequest.ProtectReferenced). func sweepReferencedInTx(ctx context.Context, tx *sql.Tx, candidates []*types.Issue) (map[string]bool, error) { if len(candidates) == 0 { return nil, nil diff --git a/internal/storage/issueops/tree_walk.go b/internal/storage/issueops/tree_walk.go index bc58e5eb7..9a7bc0970 100644 --- a/internal/storage/issueops/tree_walk.go +++ b/internal/storage/issueops/tree_walk.go @@ -14,19 +14,14 @@ import ( // // ValidateWalkTreeRequest holds the request vocabulary, PruneTreeByStatus the // ancestor-keeping rule and MergeBidirectionalTree the two-walk concatenation; -// all three are pure and pinned in tree_walk_test.go. WalkDependencyTreeInTx is -// the only part that needs a transaction, and the reason it needs one is the -// whole reason this is not a store package: the root probe, the recursion -// and the hydration must see one database state, and for a `both` walk that -// covers BOTH directions — which no arrangement of storage.DoltStorage calls can -// promise, because that interface publishes methods rather than transactions. +// all three are pure and pinned in tree_walk_test.go. WalkDependencyTreeInTx +// needs a transaction because the root probe, the recursion and the hydration +// must see one database state, and for a `both` walk that covers BOTH +// directions. // ValidateWalkTreeRequest checks a walk request against the vocabulary -// issueops.WalkTreeRequest documents and returns the normalized direction. -// -// It is pure and shared so the refusal is one sentence rather than three: every -// implementation validates through here, and the conformance contract can cite -// the leaf doc knowing all three backends refuse in the same words. +// issueops.WalkTreeRequest documents and returns the normalized direction. It is +// pure and shared so that all three backends refuse in the same words. func ValidateWalkTreeRequest(req publicops.WalkTreeRequest) (publicops.TreeDirection, error) { if req.RootID == "" { return "", fmt.Errorf("%w: root id must not be empty", publicops.ErrValidation) @@ -84,8 +79,8 @@ func PruneTreeByStatus(nodes []*types.TreeNode, status types.Status) []*types.Tr keep[node.ID] = true // Walk to the root, stopping on a repeat so a parent chain that loops // back on itself cannot spin here. The walk's own first-visit rule makes - // that unreachable today; the guard is cheap and this function is also - // called from tests with hand-built input. + // that unreachable today, but this function is also called with + // hand-built input. for current := node.ID; ; { parent, ok := parentOf[current] if !ok || parent == current || keep[parent] { @@ -109,15 +104,13 @@ func PruneTreeByStatus(nodes []*types.TreeNode, status types.Status) []*types.Tr // whole down tree beginning with the root. // // THE ROOT IS TAKEN FROM THE DOWN WALK, once. Both walks start at it, so -// dropping it from the up half is what keeps it from appearing twice — and the -// down half is the one that keeps it because the down tree is the main tree -// every renderer draws, with the dependents shown above it. +// dropping it from the up half is what keeps it from appearing twice; the down +// tree is the main tree every renderer draws, with the dependents above it. // // NOTHING ELSE IS DE-DUPLICATED. A node that both blocks the root and is blocked // by it legitimately appears in both halves, with a different Depth and a // different ParentID in each, because those are two different facts about it. -// issueops.TreeResult.Nodes says so, so a caller aggregating the list does not -// assume the ids are distinct. +// issueops.TreeResult.Nodes says so. // // The up nodes are COPIED rather than shared, so a caller mutating one half // cannot reach into the other walk's slice. @@ -134,13 +127,9 @@ func MergeBidirectionalTree(downTree, upTree []*types.TreeNode, rootID string) [ } // WalkDependencyTreeInTx is the whole read: validate, probe the root, walk each -// requested direction, prune, and enforce the defensive cap. -// -// It is the single body behind all three implementations of -// issueops.TreeWalker. Each store package wraps it in five lines around its own -// transaction and the unit of work reaches it through the domain repository, so -// "three backends agree" here is ONE VOTE plus an engine check — the wrappers -// are the only part that differs. +// requested direction, prune, and enforce the defensive cap. It is the single +// body behind all three implementations of issueops.TreeWalker, so "three +// backends agree" here is ONE VOTE plus an engine check. func WalkDependencyTreeInTx(ctx context.Context, tx DBTX, req publicops.WalkTreeRequest) (publicops.TreeResult, error) { direction, err := ValidateWalkTreeRequest(req) if err != nil { @@ -149,9 +138,8 @@ func WalkDependencyTreeInTx(ctx context.Context, tx DBTX, req publicops.WalkTree // The root's existence is probed BEFORE the walk and inside the same // transaction, so an absent root is ErrNotFound rather than an empty tree. - // The walk itself would surface the same miss for a `down` or `up` request, - // but not for `both`: two walks would each fail and the caller would see - // whichever error came first, wrapped differently. One probe is one answer. + // The walk would surface the same miss for a `down` or `up` request but not + // for `both`, where two walks fail separately. One probe is one answer. if _, err := GetIssueInTx(ctx, tx, req.RootID); err != nil { return publicops.TreeResult{}, err } diff --git a/internal/storage/issueops/tree_walk_test.go b/internal/storage/issueops/tree_walk_test.go index bc884359c..4a855d90c 100644 --- a/internal/storage/issueops/tree_walk_test.go +++ b/internal/storage/issueops/tree_walk_test.go @@ -15,9 +15,7 @@ import ( // asks for when a role's body has to live at transaction level. // // TestPruneTreeByStatus and the TestMergeBidirectionalTree_* family MOVED HERE -// from cmd/bd/dep_test.go with the functions they exercise. They were written -// against two CLI helpers that both routes each carried a call to; the helpers -// are now one shared body below the role, so the tests belong beside it. +// from cmd/bd/dep_test.go with the functions they exercise. func TestPruneTreeByStatus(t *testing.T) { tree := []*types.TreeNode{ diff --git a/internal/storage/role_accessor_decorator_test.go b/internal/storage/role_accessor_decorator_test.go index 4751e4815..d2984c40b 100644 --- a/internal/storage/role_accessor_decorator_test.go +++ b/internal/storage/role_accessor_decorator_test.go @@ -298,22 +298,19 @@ func (*roleAccessorSentinel) RemoveDependency(context.Context, issueops.RemoveDe // satisfying DoltStorage, and silently stops every completion hook on that // role. // -// THE PASS-THROUGH ROLES are asserted the other way round on purpose, and the -// table below is the list — one paragraph rather than the four near-identical -// ones four wave-2 slices each appended (bd-8ri3m is the same defect in the -// spec's own comments). Reads fire no completion hooks, so IssueReader, -// IssueRelations, Counter, StatsReporter, CycleDetector, EdgeReader, -// BlockingAnnotator, TreeWalker, ReadyCounter, Querier and InitVerifier -// deliberately return the inner surface unwrapped, each in its own hook_*.go. -// The ones in that column that are NOT reads are WorkspaceConfig, -// VersionReconciler, Bootstrapper and Deleter: a settings write changes the -// workspace rather than a bead, a version marker names no bead at all, a -// bootstrap makes a database into a workspace, and the hook vocabulary has no -// name for a deletion — so this decorator's issue-shaped hook vocabulary has -// nothing to hand a hook script (hook_workspace_config.go, -// hook_version_reconciler.go, hook_bootstrapper.go, hook_deleter.go). This test -// pins every one of them as a decision rather than leaving it -// indistinguishable from the regression above. +// THE PASS-THROUGH ROLES are asserted the other way round on purpose, in one +// paragraph rather than four near-identical ones (bd-8ri3m). Reads fire no +// completion hooks, so IssueReader, IssueRelations, Counter, StatsReporter, +// CycleDetector, EdgeReader, BlockingAnnotator, TreeWalker, ReadyCounter, +// Querier and InitVerifier deliberately return the inner surface unwrapped, +// each in its own hook_*.go. The ones in that column that are NOT reads are +// WorkspaceConfig, VersionReconciler, Bootstrapper, Sweeper and Deleter: a +// settings write changes the workspace rather than a bead, a version marker +// names no bead at all, a bootstrap lands on a workspace whose hooks are not +// installed yet, a swept row is gone, and the hook vocabulary has no name for a +// deletion — so this decorator's issue-shaped hook vocabulary has nothing to +// hand a hook script. This test pins every one of them as a decision rather +// than leaving it indistinguishable from the regression above. func TestHookFiringStoreWrapsTheWriteRolesAndPassesTheReadsThrough(t *testing.T) { inner := newRoleAccessorStore() store := NewHookFiringStore(inner, nil) @@ -342,16 +339,7 @@ func TestHookFiringStoreWrapsTheWriteRolesAndPassesTheReadsThrough(t *testing.T) {"CycleDetector", func() (any, error) { return store.CycleDetector() }, inner.cycles, false}, {"ReadyCounter", func() (any, error) { return store.ReadyCounter() }, inner.readyCounter, false}, {"Querier", func() (any, error) { return store.Querier() }, inner.querier, false}, - // The WRITE roles in the unwrapped column, and the reason is the hook - // vocabulary rather than the role. There is no on_delete hook to fire - // and a swept row is gone, so hook_sweeper.go recurses; a bootstrap - // names no bead and lands on a workspace whose hooks are not installed - // yet, so hook_bootstrapper.go does too. Asserting them here is what - // keeps those decisions. {"Sweeper", func() (any, error) { return store.Sweeper() }, inner.sweeper, false}, - // The other WRITE role in the unwrapped column, for the same reason: - // hook_deleter.go recurses because the hook vocabulary has no name for - // a deletion, not because the role reads. {"Deleter", func() (any, error) { return store.Deleter() }, inner.deleter, false}, {"Bootstrapper", func() (any, error) { return store.Bootstrapper() }, inner.bootstrapper, false}, {"InitVerifier", func() (any, error) { return store.InitVerifier() }, inner.verifier, false}, diff --git a/internal/storage/sqlbuild/counts.go b/internal/storage/sqlbuild/counts.go index f78a817a0..1d45f5ffe 100644 --- a/internal/storage/sqlbuild/counts.go +++ b/internal/storage/sqlbuild/counts.go @@ -21,8 +21,7 @@ const DepJSONObject = `JSON_OBJECT( )` // CountsHydration selects which per-row aggregates the counts mega-query -// computes. Both members are opt-OUTs: the zero value hydrates everything, -// which is what every caller that has not been told otherwise wants. +// computes. Both members are opt-OUTs: the zero value hydrates everything. // // Neither one changes WHICH ROWS come back or in what order — the aggregates // hang off LEFT JOINs that preserve every driver row, so dropping one drops a @@ -34,7 +33,7 @@ const DepJSONObject = `JSON_OBJECT( // SkipLabels leaves labels_json NULL, which the scan turns into no labels. // SkipCounts leaves the three cardinalities 0, which a caller must read as // unknown rather than as none — the promise issueops.ListRequest.SkipCounts -// states for the callers above storage. +// makes above storage. type CountsHydration struct { SkipLabels bool SkipCounts bool @@ -172,10 +171,9 @@ func SearchCountsSQL(tables FilterTables, ids []string, whereSQL, orderBySQL, li reverseBlockerSelect, tables.Comments, ccWhere) if hyd.SkipCounts { - // Constants in the same three positions: the scan reads these - // columns by index, and the rc join above is the one the embedded - // engine cannot index (see the by-IDs rationale above), so dropping - // it is the whole point of the knob. + // Constants in the same three positions: the scan reads these columns + // by index, and the rc join above is the one the embedded engine + // cannot index (see the by-IDs rationale above). countsSelect = `0 AS dep_count, 0 AS rdep_count, 0 AS comment_count` diff --git a/internal/storage/storage.go b/internal/storage/storage.go index dc14cef97..ba62b9917 100644 --- a/internal/storage/storage.go +++ b/internal/storage/storage.go @@ -139,8 +139,7 @@ type Storage interface { // BatchCreator returns the guarded create-many surface for this store: the // other role whose REQUEST is the transaction boundary. It is its own role // rather than a Create overload because a batch is ALL OR NOTHING where a - // batch close keeps its survivors, and one method cannot make both - // promises. + // batch close keeps its survivors. BatchCreator() (issueops.BatchCreator, error) // DependencyEditor returns the guarded dependency-edge surface for this @@ -157,12 +156,9 @@ type Storage interface { // Counter returns the guarded issue-count surface for this store. It is // its own role rather than a fourth IssueReader method because a count is // a NUMBER about a set where the reader answers with pages of issues: - // there is no order, no page and no cursor in the question, and a request - // carrying those would invite a caller to believe a limit bounded the - // answer. + // there is no order, no page and no cursor in the question. // - // Reads fire no hooks, so the hook decorator's answer is its inner store's - // unchanged, as it is for IssueReader. + // Reads fire no hooks, as for IssueReader. Counter() (issueops.Counter, error) // StatsReporter returns the guarded summary-statistics surface for this @@ -184,63 +180,52 @@ type Storage interface { // store: the durable key-value plane `bd config` reads and writes. It is // its own role rather than more verbs elsewhere because it answers about // the WORKSPACE rather than about an issue, and because a write here can - // re-project a value into a normalized lookup table — a side effect no - // issue role has anywhere to describe. + // re-project a value into a normalized lookup table. WorkspaceConfig() (issueops.WorkspaceConfig, error) // VersionReconciler returns the clone-local version markers for this store: // the dolt-ignored pair recording which bd binary last opened this // workspace and the highest one that ever has. It is its own role rather // than two more keys on WorkspaceConfig because settings are durable and - // travel with the database while these two are deliberately per-clone, and - // it is the one role here that belongs to no command — it answers a startup - // hook, so its failure costs every invocation rather than one. + // travel with the database while these two are deliberately per-clone. VersionReconciler() (issueops.VersionReconciler, error) // CycleDetector returns the guarded cycle-report surface for this store: its // own role because it is asked of the WHOLE graph and answers with paths, // where every Relations request names one anchor and answers with that - // anchor's neighbors. Reads fire no hooks, so the hook decorator's answer is - // its inner store's unchanged, as it is for IssueReader. + // anchor's neighbors. Reads fire no hooks, as for IssueReader. CycleDetector() (issueops.CycleDetector, error) // EdgeReader returns the guarded stored-edge surface for this store: raw // dependency rows for many anchors at once, keyed by source, with a - // per-anchor miss. Its own role rather than a second IssueRelations method - // because that one is single-anchor, answers with hydrated issues, and - // refuses a missing anchor outright. Reads fire no hooks, as for - // IssueReader. + // per-anchor miss. Its own role rather than a second IssueRelations method, + // which is single-anchor, answers with hydrated issues, and refuses a + // missing anchor outright. Reads fire no hooks, as for IssueReader. EdgeReader() (issueops.EdgeReader, error) // BlockingAnnotator returns the guarded blocking-decoration surface for this // store: the open blockers, the issues blocked and the parent of a page of // ids, which is what a listing prints beside each row. Its own role rather // than a second EdgeReader method because that one answers with STORED ROWS - // of every type, targets spelled as stored and a per-anchor miss, where this - // one answers a DERIVED summary of two edge types with closed blockers - // dropped and no existence probe at all. Reads fire no hooks, as for - // IssueReader. + // where this one answers a DERIVED summary of two edge types with closed + // blockers dropped. Reads fire no hooks, as for IssueReader. BlockingAnnotator() (issueops.BlockingAnnotator, error) // TreeWalker returns the guarded dependency-tree surface for this store: the // recursive walk from ONE root that `bd dep tree` renders. Its own role - // rather than a mode of IssueRelations or EdgeReader because both of those - // exclude it in their own words — a recursive walk has a depth, a cycle - // policy and a node shape of its own — and rather than a CycleDetector method - // because a cycle has no anchor and a tree is nothing but its anchor. Reads - // fire no hooks, as for IssueReader. + // rather than a mode of IssueRelations or EdgeReader because a recursive + // walk has a depth, a cycle policy and a node shape of its own. Reads fire + // no hooks, as for IssueReader. TreeWalker() (issueops.TreeWalker, error) // ReadyCounter returns the guarded ready-count surface for this store: the // size of the ready set, which is the number `bd ready`'s pagination - // publishes and which no other role answers. IssueReader.Ready reports - // only whether the limit hid anything, and Counter's predicate is a filter - // over one table where the ready predicate is blocker-aware. + // publishes and which no other role answers. Counter's predicate is a + // filter over one table where the ready predicate is blocker-aware. // - // Reads fire no hooks, so the hook decorator's answer is its inner store's - // unchanged, as it is for IssueReader. + // Reads fire no hooks, as for IssueReader. ReadyCounter() (issueops.ReadyCounter, error) // Querier returns the guarded boolean-query surface for this store: `bd // query`'s expression language, which has OR, NOT and parentheses. Its own // role rather than a mode of IssueReader because a ListRequest is a - // CONJUNCTION — every field narrows — and no arrangement of its fields - // expresses a disjunction. Reads fire no hooks, as for IssueReader. + // CONJUNCTION and expresses no disjunction. Reads fire no hooks, as for + // IssueReader. Querier() (issueops.Querier, error) // Sweeper returns the guarded bulk-clearance surface for this store — // `bd purge` and `bd prune`, which are one capability over two disjoint @@ -248,20 +233,16 @@ type Storage interface { // acts on it: no Lifecycle patch names a set, and composing a count with a // delete would reopen the window this role exists to close. // - // It is the one WRITE role whose hook decorator recurses UNWRAPPED, and - // that is a fact about the hook vocabulary rather than about the role: - // there is no on_delete hook to fire (internal/hooks publishes create, - // update and close), and the rows a sweep would name it with are gone. - // See hook_sweeper.go. + // It is the one WRITE role whose hook decorator recurses UNWRAPPED: there + // is no on_delete hook to fire (internal/hooks publishes create, update + // and close), and the rows a sweep would name it with are gone. See + // hook_sweeper.go. Sweeper() (issueops.Sweeper, error) // Deleter returns the named-row erasure surface for this store — // `bd delete`. Its own role rather than a Sweeper mode because Sweeper // erases a set the caller DESCRIBED and this one erases rows the caller - // NAMED, which is what decides where each one's safety lives: a - // description can be accidentally too wide, so Sweeper carries a - // require-a-filter gate, while a list of ids cannot, so this one's guard is - // about the graph — a named row with a dependent the request did not name - // is refused unless the caller says cascade or force. + // NAMED: a named row with a dependent the request did not name is refused + // unless the caller says cascade or force. // // Its hook decorator recurses UNWRAPPED for the same reason Sweeper's // does: there is no on_delete hook to fire and the rows are gone. See @@ -269,27 +250,22 @@ type Storage interface { Deleter() (issueops.Deleter, error) // Bootstrapper returns the guarded identity-seeding surface for this store: // the one-time write that turns a database bd can connect to into a - // workspace bd can use. It is the only slice of `bd init` that is a role at - // all — the rest of init CREATES the substrate, which an accessor on a - // store cannot do — and it is its own role rather than more keys on + // workspace bd can use. It is its own role rather than more keys on // WorkspaceConfig because it REFUSES an already-identified substrate, which // is a guard no settings write has anywhere to express. // - // It is the second WRITE role whose hook decorator recurses unwrapped, and - // for the vocabulary reason Sweeper's does: a bootstrap names no issue, and - // on a workspace this new the hooks are not installed yet. See - // hook_bootstrapper.go. + // Its hook decorator recurses unwrapped for the vocabulary reason Sweeper's + // does: a bootstrap names no issue, and on a workspace this new the hooks + // are not installed yet. See hook_bootstrapper.go. Bootstrapper() (issueops.Bootstrapper, error) // InitVerifier returns the guarded identity-read surface for this store: the // prefix and project id `bd init` adopts, reconciles against, or refuses to - // invent. It is NOT Bootstrapper's read half, the way RecordedVersion is - // VersionReconciler's: bd reads this identity on paths where it is forbidden - // to write one — a bts-provisioned team database, a gateway whose credential - // may be read-only — and a caller that must not write must not be handed the - // writer. + // invent. It is NOT Bootstrapper's read half: bd reads this identity on + // paths where it is forbidden to write one — a bts-provisioned team + // database, a gateway whose credential may be read-only — and a caller that + // must not write must not be handed the writer. // - // Reads fire no hooks, so the hook decorator's answer is its inner store's - // unchanged, as it is for IssueReader. + // Reads fire no hooks, as for IssueReader. InitVerifier() (issueops.InitVerifier, error) // Issue CRUD @@ -724,13 +700,12 @@ type BackupStore interface { // len(GetReadyWorkWithCounts(filter with Limit=0)) but computed with cheap // indexed COUNT(*)s over the ready predicate. // -// THAT IDENTITY IS THIS INTERFACE'S WHOLE CONTRACT, and it is now also a public -// promise: issueops.ReadyCounter states it for every backend, and the -// store-backed body behind ReadyCounter() (internal/workapi/storereadycounter) -// is this method plus the shared filter builder. `bd ready`'s "Showing X of N" -// reaches it that way on both routes; it no longer type-asserts for the -// capability itself, because a store that cannot answer now fails to compile -// rather than falling back to an unbounded query at runtime. +// THAT IDENTITY IS THIS INTERFACE'S WHOLE CONTRACT. issueops.ReadyCounter +// states it for every backend, and the store-backed body behind ReadyCounter() +// (internal/workapi/storereadycounter) is this method plus the shared filter +// builder. `bd ready`'s "Showing X of N" reaches it that way on both routes; it +// no longer type-asserts for the capability itself, so a store that cannot +// answer fails to compile rather than falling back to an unbounded query. type ReadyWorkCounter interface { CountReadyWork(ctx context.Context, filter types.WorkFilter) (int, error) } diff --git a/internal/storage/uow/batch_creator.go b/internal/storage/uow/batch_creator.go index 22b06927c..4287d1d64 100644 --- a/internal/storage/uow/batch_creator.go +++ b/internal/storage/uow/batch_creator.go @@ -11,8 +11,7 @@ import ( ) // BatchCreatorSource is the capability accessor a unit-of-work provider offers -// for the batch-create role, the sibling of BatchCloserSource and -// IssueLifecycleSource. +// for the batch-create role. type BatchCreatorSource interface { BatchCreator() (publicops.BatchCreator, error) } @@ -37,19 +36,15 @@ func NewBatchCreator(provider UnitOfWorkProvider) (publicops.BatchCreator, error var _ publicops.BatchCreator = (*batchCreator)(nil) -// CreateBatch creates every item in ONE unit of work and commits them -// together. The request is the transaction: N items are N creates and one -// commit, which is the whole reason this is not a loop over Lifecycle.Create. +// CreateBatch creates every item in ONE unit of work and commits them together: +// N items are N creates and one commit. // // IT IS ALL OR NOTHING, unlike the batch CLOSE beside it. The first item that -// refuses returns, which rolls the attempt back with nothing created — there is -// no per-item outcome to carry a refusal in, because a create batch has no -// survivors to keep. +// refuses returns, which rolls the attempt back with nothing created. // -// THE ITEMS ARE CREATED IN ORDER, and that is load-bearing rather than -// incidental: this body writes each item's edges as it writes that item, so an -// edge naming an EARLIER item of the same batch resolves and one naming a later -// item does not. The role promises exactly the first of those. +// THE ITEMS ARE CREATED IN ORDER, and that is load-bearing: this body writes +// each item's edges as it writes that item, so an edge naming an EARLIER item +// of the same batch resolves and one naming a later item does not. func (o *batchCreator) CreateBatch(ctx context.Context, request publicops.CreateBatchRequest) (publicops.CreateBatchResult, error) { snapshot := storageissueops.CloneCreateBatchRequest(request) if err := storageissueops.ValidateCreateBatchRequest(snapshot); err != nil { @@ -76,8 +71,7 @@ func (o *batchCreator) CreateBatch(ctx context.Context, request publicops.Create // createBatchItem creates one item on the batch's unit of work, through the // same preparation, infra-type routing and error classification the single -// create runs — so an item's content rules ARE Lifecycle.Create's rather than a -// second copy of them that can drift. +// create runs — so an item's content rules ARE Lifecycle.Create's. func createBatchItem(ctx context.Context, uw UnitOfWork, request publicops.CreateBatchRequest, item publicops.BatchCreateItem, createContext domain.CreateContext) (*types.Issue, error) { prepared, err := storageissueops.PreparePublicCreateRequest( storageissueops.CreateBatchItemRequest(request, item), @@ -91,7 +85,7 @@ func createBatchItem(ctx context.Context, uw UnitOfWork, request publicops.Creat return nil, err } // Configured infra types live in the wisp tables, the same routing - // ExecuteCreateBatch applies and the single create applies above it. + // ExecuteCreateBatch and the single create apply. if !prepared.Issue.Ephemeral && !prepared.Issue.NoHistory && createContext.InfraTypes[string(prepared.Issue.IssueType)] { prepared.Issue.Ephemeral = true } diff --git a/internal/storage/uow/batch_creator_contract_test.go b/internal/storage/uow/batch_creator_contract_test.go index a93345046..735e0932b 100644 --- a/internal/storage/uow/batch_creator_contract_test.go +++ b/internal/storage/uow/batch_creator_contract_test.go @@ -17,8 +17,7 @@ import ( // // One provider for the whole suite (each newUOWRoleFixtureProvider boots a real // Dolt sql-server) and NO t.Parallel: this backend has no per-test -// copy-on-write branch, so dolt_log and the issues table are database-global and -// a parallel subtest would corrupt another subtest's history delta. +// copy-on-write branch, so dolt_log and the issues table are database-global. func TestBatchCreatorContract(t *testing.T) { ctx := context.Background() fixture := newUOWBatchCreatorFixture(t, ctx, "bcr") diff --git a/internal/storage/uow/blocking_annotator_contract_test.go b/internal/storage/uow/blocking_annotator_contract_test.go index 7e822eeef..a9df7af0c 100644 --- a/internal/storage/uow/blocking_annotator_contract_test.go +++ b/internal/storage/uow/blocking_annotator_contract_test.go @@ -10,10 +10,8 @@ import ( // TestBlockingAnnotatorContract runs the BlockingAnnotator contract against the // unit-of-work provider — the one implementation that does not call // storage/issueops.ExecuteBlockingAnnotation, so this is the wiring where a -// genuine body divergence shows up. It reads BOTH dependency tiers for every id -// and merges, where the two store backends partition the ids by plane and read -// each one's outbound edges from the tier it lives on; that makes this the -// SECOND of two votes rather than the third. +// genuine body divergence shows up. It is the SECOND of two votes, not the +// third. // // One provider for the whole suite (each newUOWRoleFixtureProvider boots a real // Dolt sql-server) and NO t.Parallel: this backend has no per-test diff --git a/internal/storage/uow/blockingannotator.go b/internal/storage/uow/blockingannotator.go index 58d8a0727..6f587a5e4 100644 --- a/internal/storage/uow/blockingannotator.go +++ b/internal/storage/uow/blockingannotator.go @@ -40,13 +40,12 @@ var _ publicops.BlockingAnnotator = (*blockingAnnotator)(nil) // two edge reads and the status lookups behind them see one snapshot — the // property the two store-backed bodies get from a shared read transaction. // -// This is the genuinely separate body. The store side partitions the ids by -// plane and reads each anchor's outbound edges from the tier it lives on; the -// use case below reads BOTH tiers for every id and merges, and it resolves -// blocker statuses only for the ids that appeared in a row rather than for the -// whole batch. The three maps it hands back are the same three maps, and -// FinishBlockingAnnotation is what makes the SHAPE of the answer — the entry per -// id, the pinned order, the collapse of repeats — one decision rather than two. +// This is the genuinely separate body: the store side partitions the ids by +// plane and reads each anchor's outbound edges from the tier it lives on, while +// the use case below reads BOTH tiers for every id and merges. The three maps +// are the same three maps, and FinishBlockingAnnotation is what makes the SHAPE +// of the answer — the entry per id, the pinned order, the collapse of repeats — +// one decision rather than two. func (a *blockingAnnotator) AnnotateBlocking(ctx context.Context, request publicops.BlockingRequest) (publicops.BlockingResult, error) { if err := storageissueops.ValidateBlockingRequest(request); err != nil { return publicops.BlockingResult{}, err diff --git a/internal/storage/uow/bootstrapper.go b/internal/storage/uow/bootstrapper.go index a7dcbede6..a9e259294 100644 --- a/internal/storage/uow/bootstrapper.go +++ b/internal/storage/uow/bootstrapper.go @@ -39,19 +39,16 @@ var _ publicops.Bootstrapper = (*bootstrapper)(nil) // Bootstrap reads the identity, refuses over an identified substrate and // writes the new one inside ONE unit of work. // -// THE REFUSAL IS INSIDE THE TRANSACTION on purpose, and this is the backend -// where that matters most: it serves a workspace several clients share, so two -// inits can arrive at one database at the same moment, and a refusal decided -// from a read outside the transaction is one both of them pass. +// THE REFUSAL IS INSIDE THE TRANSACTION, and this is the backend where that +// matters most: it serves a workspace several clients share, so two inits can +// arrive at one database at the same moment, and a refusal decided from a read +// outside the transaction is one both of them pass. // -// VALIDATION HAPPENS BEFORE THE UNIT OF WORK IS OPENED, for the reason -// workspaceConfig.SetSetting gives — a refused bootstrap should cost no -// connection and no transaction. +// VALIDATION HAPPENS BEFORE THE UNIT OF WORK IS OPENED — a refused bootstrap +// should cost no connection and no transaction. // -// ONE VERSION-CONTROL ENTRY, which is what the role's "at most one" permits. -// The identity lands on planes that travel, so this backend — the one whose -// unit of work labels its own commit — records the bootstrap as a single entry -// rather than as one per key. +// ONE VERSION-CONTROL ENTRY, which is what the role's "at most one" permits: +// one entry rather than one per key. // // The per-clone bookkeeping `bd init` seeds alongside the identity is not here // and not on the role; see issueops.Bootstrapper for why. diff --git a/internal/storage/uow/bootstrapper_contract_test.go b/internal/storage/uow/bootstrapper_contract_test.go index 81c8c012d..90aceeaaa 100644 --- a/internal/storage/uow/bootstrapper_contract_test.go +++ b/internal/storage/uow/bootstrapper_contract_test.go @@ -14,10 +14,9 @@ import ( // genuine body divergence shows up. The two store backends share those bodies // between them, which makes this the SECOND of two votes rather than the third. // -// It is also the only wiring where "the identity is still there afterwards" is -// a question with a hard answer: this body reads, refuses and writes inside ONE -// transaction and every assertion reads back through a NEW one, so a write that -// never committed shows up here and nowhere else. +// This body reads, refuses and writes inside ONE transaction and every +// assertion reads back through a NEW one, so a write that never committed shows +// up here and nowhere else. // // One provider for the whole suite (each newUOWRoleFixtureProvider boots a real // Dolt sql-server) and NO t.Parallel: this backend has no per-test @@ -71,9 +70,7 @@ func newUOWBootstrapperFixture(t *testing.T, ctx context.Context) conformance.Bo provider := newUOWRoleFixtureProvider(t, ctx, "boot") // Through the capability accessors, not NewBootstrapper/NewInitVerifier: a // provider that stopped offering either role is the regression, and a - // constructor call would hide it. The two sources are asserted separately - // because they ARE separate — a caller that may only read must be able to - // hold one without the other. + // constructor call would hide it. bootstrapSource, ok := provider.(BootstrapperSource) if !ok { t.Fatalf("provider %T does not offer the Bootstrapper accessor", provider) @@ -94,10 +91,9 @@ func newUOWBootstrapperFixture(t *testing.T, ctx context.Context) conformance.Bo return conformance.BootstrapperFixture{ Bootstrapper: bootstrapper, InitVerifier: verifier, - // Past both roles, through the seams their bodies write through, in - // their own committed transaction: the frozen kit can set a prefix but - // cannot unset one, and an unidentified substrate is the state a - // bootstrap needs to be reachable at all on a provisioned database. + // Past both roles, in their own committed transaction: the frozen kit + // can set a prefix but cannot unset one, and an unidentified substrate + // is the state a bootstrap needs to be reachable at all. SeedIdentity: func(ctx context.Context, prefix, projectID string) error { return RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { cfg := uw.ConfigUseCase() diff --git a/internal/storage/uow/counter.go b/internal/storage/uow/counter.go index 7f79377fa..03a155788 100644 --- a/internal/storage/uow/counter.go +++ b/internal/storage/uow/counter.go @@ -55,11 +55,10 @@ func (c *counter) Count(ctx context.Context, req publicops.CountRequest) (public // // Sharing the unit of work is free here — this seam has a transaction and the // store seam does not — so both queries see one snapshot on this backend. -// issueops.CountByGroupResult.Total deliberately does NOT promise that: the -// store-backed body cannot offer it, and a contract stating the stronger -// property would be a contract only one of the three implementations meets. -// What is shared across all three is that the total is the SCALAR count rather -// than the sum of the buckets, which is the part callers can be wrong about. +// issueops.CountByGroupResult.Total deliberately does NOT promise that, because +// the store-backed body cannot offer it. What all three implementations share is +// that the total is the SCALAR count rather than the sum of the buckets, which +// is the part callers can be wrong about. func (c *counter) CountByGroup(ctx context.Context, req publicops.CountByGroupRequest) (publicops.CountByGroupResult, error) { group, err := workapi.ValidateCountGroup(req.GroupBy) if err != nil { @@ -86,9 +85,8 @@ func (c *counter) CountByGroup(ctx context.Context, req publicops.CountByGroupRe } // countFilter builds the storage filter from the unit of work the call already -// holds, loading configuration only when IncludeInfra can read it — the same -// two decisions the store-backed body makes, for the same reasons, through the -// same builder. +// holds, loading configuration only when IncludeInfra can read it — the same two +// decisions the store-backed body makes, through the same builder. func countFilter(ctx context.Context, uw UnitOfWork, req publicops.CountRequest) (types.IssueFilter, error) { var cfg workapi.ListConfig if req.IncludeInfra { diff --git a/internal/storage/uow/counter_contract_test.go b/internal/storage/uow/counter_contract_test.go index 4afb21fc4..7a39bc265 100644 --- a/internal/storage/uow/counter_contract_test.go +++ b/internal/storage/uow/counter_contract_test.go @@ -9,9 +9,8 @@ import ( // TestCounterContract runs the Counter contract against the unit-of-work // provider — the one Counter implementation that does not hand back -// internal/workapi/storecounter, so this is the wiring where a genuine body -// divergence shows up. The two store backends share that body between them, -// which makes this the SECOND of two votes rather than the third. +// internal/workapi/storecounter. The two store backends share that body between +// them, which makes this the SECOND of two votes rather than the third. // // One provider for the whole suite (each newUOWRoleFixtureProvider boots a // real Dolt sql-server) and NO t.Parallel: this backend has no per-test @@ -63,8 +62,7 @@ func newUOWCounterFixture(t *testing.T, ctx context.Context, prefix string) conf t.Helper() provider := newUOWRoleFixtureProvider(t, ctx, prefix) // Through the capability accessor, not NewCounter: a provider that stopped - // offering the role is the regression, and a constructor call would hide - // it. + // offering the role is the regression, and a constructor call would hide it. source, ok := provider.(CounterSource) if !ok { t.Fatalf("provider %T does not offer the Counter accessor", provider) diff --git a/internal/storage/uow/cycle_detector.go b/internal/storage/uow/cycle_detector.go index fc4e18c9d..924c67395 100644 --- a/internal/storage/uow/cycle_detector.go +++ b/internal/storage/uow/cycle_detector.go @@ -35,11 +35,11 @@ var _ publicops.CycleDetector = (*cycleDetector)(nil) // DetectCycles walks the blocking graph inside ONE read-only unit of work. // -// One unit of work matters more here than it does for a count. The report is a -// graph read followed by a hydration per member, and on this backend both run on -// the same transaction — so the rows a cycle names are the rows that were on the -// cycle, rather than the rows that exist by the time the second query runs. The -// two store-backed bodies get the same property from their own read transaction. +// The report is a graph read followed by a hydration per member, and on this +// backend both run on the same transaction — so the rows a cycle names are the +// rows that were on the cycle, rather than the rows that exist by the time the +// second query runs. The two store-backed bodies get the same property from +// their own read transaction. func (c *cycleDetector) DetectCycles(ctx context.Context, _ publicops.DetectCyclesRequest) (publicops.CycleReport, error) { return RunTxRead(ctx, c.provider, func(ctx context.Context, uw UnitOfWork) (publicops.CycleReport, error) { return uw.DependencyUseCase().DetectCycleReport(ctx) diff --git a/internal/storage/uow/cycle_detector_contract_test.go b/internal/storage/uow/cycle_detector_contract_test.go index 8c1333689..286eece89 100644 --- a/internal/storage/uow/cycle_detector_contract_test.go +++ b/internal/storage/uow/cycle_detector_contract_test.go @@ -10,8 +10,7 @@ import ( // TestCycleDetectorContract runs the CycleDetector contract against the // unit-of-work provider — the one implementation that does not wrap the store's -// own transaction, so this is the wiring where a genuine seam divergence shows -// up. The two store backends share their five-line body between them, which +// own transaction. The two store backends share their five-line body, which // makes this the SECOND of two votes rather than the third. // // One provider for the whole suite and NO t.Parallel: this backend has no @@ -52,8 +51,7 @@ func newUOWCycleDetectorFixture(t *testing.T, ctx context.Context, prefix string t.Helper() provider := newUOWRoleFixtureProvider(t, ctx, prefix) // Through the capability accessor, not NewCycleDetector: a provider that - // stopped offering the role is the regression, and a constructor call would - // hide it. + // stopped offering the role is the regression a constructor call would hide. source, ok := provider.(CycleDetectorSource) if !ok { t.Fatalf("provider %T does not offer the CycleDetector accessor", provider) @@ -69,10 +67,9 @@ func newUOWCycleDetectorFixture(t *testing.T, ctx context.Context, prefix string CreateIssue: kit.CreateIssue, CreateWisp: kit.CreateWisp, // The frozen kit exposes reads only. This is the write half of the same - // unfiltered raw-SQL pass-through its QueryScalar reads through, inside - // ONE committing unit of work — which is also what gives the whole - // script one session, so a foreign_key_checks toggle covers the inserts - // it was written for. + // raw-SQL pass-through, inside ONE committing unit of work — which also + // gives the whole script one session, so a foreign_key_checks toggle + // covers the inserts it was written for. Exec: func(ctx context.Context, statements []conformance.SQLStatement) error { return RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { for _, stmt := range statements { diff --git a/internal/storage/uow/deleter.go b/internal/storage/uow/deleter.go index ce0aa94fa..b36182014 100644 --- a/internal/storage/uow/deleter.go +++ b/internal/storage/uow/deleter.go @@ -12,9 +12,7 @@ import ( ) // DeleterSource is the capability accessor a unit-of-work provider offers for -// the named-row erasure role, the sibling of SweeperSource and CounterSource. A -// consumer holding a provider by interface asks for the role here instead of -// reaching for a constructor. +// the named-row erasure role, the sibling of SweeperSource and CounterSource. type DeleterSource interface { Deleter() (publicops.Deleter, error) } @@ -45,17 +43,13 @@ var _ publicops.Deleter = (*deleter)(nil) // issueops.DeleteInTx, and this one reaches the same questions through the // domain use cases. What it must NOT do differently is which rows go and which // requests are refused — the id normalization and the request rules run through -// the same internal/workapi functions the shared body runs, and the two -// answers that need the graph are asserted equal by the conformance contract. +// the same internal/workapi functions, and the conformance contract asserts the +// two equal. // -// THE GUARD IS HERE RATHER THAN IN THE USE CASE, and that is a deliberate -// placement. domain.IssueUseCase.DeleteIssues already selects the right SET for -// both modes — Cascade expands to the transitive dependents, no Cascade deletes -// exactly what it was handed and orphans the rest — but it has never refused -// anything, and the proxied route papered over that by hardcoding Cascade for -// every call. The refusal belongs above the use case with the rest of the -// role's policy, so a future use-case caller cannot inherit the capability and -// miss the guard. +// THE GUARD IS HERE RATHER THAN IN THE USE CASE, which selects the right SET +// for both modes but has never refused anything. The refusal belongs above it +// with the rest of the role's policy, where a future use-case caller cannot +// inherit the capability and miss it. // // A DRY RUN TAKES A READ-ONLY UNIT OF WORK: it writes nothing, so it must not // take the committing path and leave a history entry describing a preview. @@ -83,9 +77,9 @@ func (d *deleter) Delete(ctx context.Context, req publicops.DeleteRequest) (publ } // deleteInUOW is the whole deletion on one unit of work, shared by the preview -// path and the committing one so the two cannot answer differently — which on -// this role is the point rather than tidiness: issueops.Deleter promises that a -// dry run refuses exactly where the real run refuses. +// path and the committing one so the two cannot answer differently: +// issueops.Deleter promises that a dry run refuses exactly where the real run +// refuses. func deleteInUOW(ctx context.Context, uw UnitOfWork, req publicops.DeleteRequest) (publicops.DeleteResult, error) { issueUC := uw.IssueUseCase() result := publicops.DeleteResult{DryRun: req.DryRun} @@ -155,9 +149,7 @@ func deleteInUOW(ctx context.Context, uw UnitOfWork, req publicops.DeleteRequest IDs: req.IDs, Cascade: req.Cascade, DryRun: req.DryRun, - // A preview rewrites nothing, so it must not ask for the rewrite; the - // use case would stop short of it anyway, and asking would make the - // intent depend on that. + // A preview rewrites nothing, so it must not ask for the rewrite. UpdateTextReferences: !req.DryRun, }, req.Actor) if err != nil { diff --git a/internal/storage/uow/deleter_contract_test.go b/internal/storage/uow/deleter_contract_test.go index 85bac5dc2..f632c9e2b 100644 --- a/internal/storage/uow/deleter_contract_test.go +++ b/internal/storage/uow/deleter_contract_test.go @@ -9,19 +9,17 @@ import ( // TestDeleterContract runs the Deleter contract against the unit-of-work // provider — the one implementation that does not run -// internal/storage/issueops.DeleteInTx, and the one that reaches the same -// questions through the domain use cases. It is the SECOND of two votes, not -// the third: the two store backends share the other body. +// internal/storage/issueops.DeleteInTx. It is the SECOND of two votes, not the +// third: the two store backends share the other body. // -// It is also the backend this role changes most. Before this commit the proxied -// route hardcoded cascade at both of its call sites and REFUSED `--cascade` as -// an unsupported flag, so there was no way to delete an issue on a team server -// without taking its dependents — the guard and the orphan mode below are new -// behaviour here rather than a re-assertion of old. +// It is also the backend this role changes most: the proxied route hardcoded +// cascade at both of its call sites and REFUSED `--cascade` as an unsupported +// flag, so there was no way to delete an issue on a team server without taking +// its dependents. The guard and the orphan mode below are new behaviour here. // // One provider for the whole suite (each newUOWRoleFixtureProvider boots a real // Dolt sql-server) and NO t.Parallel: this backend has no per-test -// copy-on-write branch, so dolt_log and the issues table are database-global. +// copy-on-write branch, so dolt_log and issues are database-global. func TestDeleterContract(t *testing.T) { ctx := context.Background() fixture := newUOWDeleterFixture(t, ctx, "del") @@ -77,8 +75,7 @@ func newUOWDeleterFixture(t *testing.T, ctx context.Context, prefix string) conf t.Helper() provider := newUOWRoleFixtureProvider(t, ctx, prefix) // Through the capability accessor, not NewDeleter: a provider that stopped - // offering the role is the regression, and a constructor call would hide - // it. + // offering the role is the regression a constructor call would hide. source, ok := provider.(DeleterSource) if !ok { t.Fatalf("provider %T does not offer the Deleter accessor", provider) diff --git a/internal/storage/uow/edge_reader_contract_test.go b/internal/storage/uow/edge_reader_contract_test.go index 87639cbae..b49159f31 100644 --- a/internal/storage/uow/edge_reader_contract_test.go +++ b/internal/storage/uow/edge_reader_contract_test.go @@ -11,14 +11,13 @@ import ( // provider — the one EdgeReader implementation that does not call // storage/issueops.ExecuteEdgeRead, so this is the wiring where a genuine body // divergence shows up. It probes anchor existence through two batched use-case -// reads, one per plane, where the two store backends run one batched EXISTS -// over both tables; that makes this the SECOND of two votes rather than the -// third. +// reads, one per plane, where the two store backends run one batched EXISTS over +// both tables; that makes this the SECOND of two votes rather than the third. // // One provider for the whole suite (each newUOWRoleFixtureProvider boots a real // Dolt sql-server) and NO t.Parallel: this backend has no per-test -// copy-on-write branch, so dolt_log and the issues table are database-global -// and a parallel subtest would corrupt another subtest's history delta. +// copy-on-write branch, so a parallel subtest would corrupt another subtest's +// history delta. func TestEdgeReaderContract(t *testing.T) { ctx := context.Background() fixture := newUOWEdgeReaderFixture(t, ctx, "edg") diff --git a/internal/storage/uow/edgereader.go b/internal/storage/uow/edgereader.go index ebde36595..bc4e456da 100644 --- a/internal/storage/uow/edgereader.go +++ b/internal/storage/uow/edgereader.go @@ -39,10 +39,9 @@ var _ publicops.EdgeReader = (*edgeReader)(nil) // store-backed bodies get from a shared read transaction. // // The probe is the two batched by-id reads, one per plane, rather than the -// per-id issue-then-wisp fallback Relations uses: this role's whole reason to -// exist is that its question is asked about many anchors at once, and a probe -// that fanned out per id would put the round trips back that the batched edge -// read removed. +// per-id issue-then-wisp fallback Relations uses: this role's question is asked +// about many anchors at once, and a probe that fanned out per id would put back +// the round trips the batched edge read removed. func (r *edgeReader) ReadEdges(ctx context.Context, request publicops.EdgeReadRequest) (publicops.EdgeReadResult, error) { if err := storageissueops.ValidateEdgeReadRequest(request); err != nil { return publicops.EdgeReadResult{}, err @@ -76,9 +75,9 @@ func (r *edgeReader) ReadEdges(ctx context.Context, request publicops.EdgeReadRe return publicops.EdgeReadResult{}, err } // The type filter and the order run HERE rather than in the reads - // above, so both implementations narrow and order through one - // function; a filter pushed into one side's query would put the - // narrowing in SQL on one backend and in Go on the other. + // above, so both implementations narrow and order through one function; + // a filter pushed into one side's query would put the narrowing in SQL + // on one backend and in Go on the other. return storageissueops.FinishEdgeRead(anchors, present, edges, request.Types), nil }) } diff --git a/internal/storage/uow/init_verifier.go b/internal/storage/uow/init_verifier.go index 4db4288bd..05eec4aab 100644 --- a/internal/storage/uow/init_verifier.go +++ b/internal/storage/uow/init_verifier.go @@ -10,12 +10,9 @@ import ( ) // InitVerifierSource is the capability accessor a unit-of-work provider offers -// for the identity read, the sibling of BootstrapperSource. -// -// It is a SEPARATE source from BootstrapperSource for the reason the two roles -// are separate: the callers that only read — a bts-provisioned team database, an -// authenticating gateway with a read-only credential — must not be able to -// reach the write. +// for the identity read, the sibling of BootstrapperSource. It is a SEPARATE +// source so that callers which only read — a bts-provisioned team database, an +// authenticating gateway with a read-only credential — cannot reach the write. type InitVerifierSource interface { InitVerifier() (publicops.InitVerifier, error) } @@ -40,9 +37,8 @@ func NewInitVerifier(provider UnitOfWorkProvider) (publicops.InitVerifier, error var _ publicops.InitVerifier = (*initVerifier)(nil) -// VerifyIdentity reads both markers inside ONE read transaction, which is what -// makes the pair a snapshot rather than two reads a concurrent bootstrap can -// land between. +// VerifyIdentity reads both markers inside ONE read transaction, so the pair is +// a snapshot rather than two reads a concurrent bootstrap can land between. func (v *initVerifier) VerifyIdentity(ctx context.Context, _ publicops.VerifyIdentityRequest) (publicops.VerifyIdentityResult, error) { return RunTxRead(ctx, v.provider, func(ctx context.Context, uw UnitOfWork) (publicops.VerifyIdentityResult, error) { prefix, projectID, err := readWorkspaceIdentity(ctx, uw.ConfigUseCase()) @@ -54,9 +50,8 @@ func (v *initVerifier) VerifyIdentity(ctx context.Context, _ publicops.VerifyIde } // readWorkspaceIdentity reads the pair the bootstrap refusal and the verifier -// both ask about, so the two cannot come to disagree about what "identified" -// means on this backend. It is this package's twin of -// issueops.verifyIdentityInTx, which serves the two store backends. +// both ask about, so the two cannot disagree about what "identified" means on +// this backend. It is this package's twin of issueops.verifyIdentityInTx. func readWorkspaceIdentity(ctx context.Context, cfg domain.ConfigUseCase) (prefix, projectID string, err error) { prefix, err = cfg.GetConfig(ctx, workapi.ConfigKeyIssuePrefix) if err != nil { diff --git a/internal/storage/uow/issue_reader.go b/internal/storage/uow/issue_reader.go index a176dd869..7ff7a11cc 100644 --- a/internal/storage/uow/issue_reader.go +++ b/internal/storage/uow/issue_reader.go @@ -70,10 +70,9 @@ func (r *issueReader) Ready(ctx context.Context, req publicops.ReadyRequest) (pu }) } -// listBackend names the backend a List refusal comes from. It is the provider -// seam rather than the engine underneath it: what cannot honor MaxRows is this -// query path (internal/storage/domain/db), which threads no cap, and every -// provider reaches the queries through it. +// listBackend names the backend a List refusal comes from: the provider seam +// rather than the engine underneath it, because what cannot honor MaxRows is +// the internal/storage/domain/db query path every provider reaches through. const listBackend = "uow-provider" func (r *issueReader) List(ctx context.Context, req publicops.ListRequest) (publicops.IssuePage, error) { @@ -85,19 +84,18 @@ func (r *issueReader) List(ctx context.Context, req publicops.ListRequest) (publ // request that cannot be answered should not cost a transaction. // // `bd list --max-rows --proxied-server` already refuses one layer up - // (cmd/bd/max_rows.go, rejectMaxRowsUnderProxiedServer) for exactly this - // reason. This is the same refusal for the callers that are not the CLI. + // (cmd/bd/max_rows.go, rejectMaxRowsUnderProxiedServer); this is the same + // refusal for the callers that are not the CLI. if req.MaxRows != 0 { return publicops.IssuePage{}, &publicops.ErrUnsupported{Op: "Reader.List(MaxRows)", Backend: listBackend} } return RunTxRead(ctx, r.provider, func(ctx context.Context, uw UnitOfWork) (publicops.IssuePage, error) { // The config source comes from the unit of work this call already // holds, so a caller reaching this method through the role has nothing - // to supply and no step to skip — which is now how `bd list - // --proxied-server` gets its page in every mode but --watch and the - // hierarchical --parent tree. Those two still open their own unit of - // work, because they consume the FILTER rather than a page; see - // issueops.Reader's doc comment. + // to supply and no step to skip. `bd list --proxied-server` gets its + // page this way in every mode but --watch and the hierarchical --parent + // tree; those two still open their own unit of work because they consume + // the FILTER rather than a page (see issueops.Reader's doc comment). cfg, err := workapi.LoadUOWListConfig(ctx, uw) if err != nil { return publicops.IssuePage{}, err diff --git a/internal/storage/uow/querier.go b/internal/storage/uow/querier.go index 29af15ecd..a8d812563 100644 --- a/internal/storage/uow/querier.go +++ b/internal/storage/uow/querier.go @@ -40,9 +40,8 @@ var _ publicops.Querier = (*querier)(nil) // this seam's capabilities rather than a second opinion about the query. It // renders OFFSET, so a filter-expressible query pushes the skip down; and it // reports HasMore natively, so the epilogue's seed is that verdict rather than -// an over-fetched row. The plan itself — which expressions need a predicate, -// what row bound each shape may carry, the default closed exclusion — is -// workapi.BuildQueryPlan, the same function the other body calls. +// an over-fetched row. The plan itself is workapi.BuildQueryPlan, the same +// function the other body calls. func (q *querier) Query(ctx context.Context, req publicops.QueryRequest) (publicops.IssuePage, error) { plan, err := workapi.BuildQueryPlan(req) if err != nil { diff --git a/internal/storage/uow/querier_contract_test.go b/internal/storage/uow/querier_contract_test.go index 904dc79a7..3fbd179b9 100644 --- a/internal/storage/uow/querier_contract_test.go +++ b/internal/storage/uow/querier_contract_test.go @@ -16,10 +16,9 @@ import ( // this seam renders OFFSET for a filter-expressible query and skips matches in // Go for a predicate one, where the store body refuses both uniformly. // -// One provider for the whole suite (each newUOWRoleFixtureProvider boots a real -// Dolt sql-server) and NO t.Parallel: this backend has no per-test -// copy-on-write branch, so dolt_log and the issues table are database-global and -// a parallel subtest would corrupt another subtest's history delta. +// One provider for the whole suite and NO t.Parallel: this backend has no +// per-test copy-on-write branch, so dolt_log and the issues table are +// database-global and a parallel subtest would corrupt another's history delta. func TestQuerierContract(t *testing.T) { ctx := context.Background() fixture := newUOWQuerierFixture(t, ctx, "qry") diff --git a/internal/storage/uow/ready_counter.go b/internal/storage/uow/ready_counter.go index 685ec6205..7940650c3 100644 --- a/internal/storage/uow/ready_counter.go +++ b/internal/storage/uow/ready_counter.go @@ -9,9 +9,7 @@ import ( ) // ReadyCounterSource is the capability accessor a unit-of-work provider offers -// for the ready-count role, the sibling of IssueReaderSource and -// ReadyClaimerSource. A consumer holding a provider by interface asks for the -// role here instead of reaching for a constructor. +// for the ready-count role. type ReadyCounterSource interface { ReadyCounter() (publicops.ReadyCounter, error) } @@ -38,21 +36,18 @@ var _ publicops.ReadyCounter = (*readyCounter)(nil) // CountReady answers one ready count inside one read-only unit of work. // -// IT COUNTS THE PAGE, and that is a deliberate choice rather than a missing -// optimization. This seam has no COUNT(*) over the ready predicate — the ready -// set is a UNION of two tables whose overlap the id query resolves in Go -// (domain/db/issue_search.go: an id present in both planes is a hard error -// here, not a de-duplication) — so a hand-rolled COUNT would be a second -// definition of the ready set on the one backend whose definition is already -// separate code. Running the SAME query Reader.Ready runs, unbounded, and -// taking its length makes the identity CountReady promises true BY -// CONSTRUCTION on this backend, including the way it fails. +// IT COUNTS THE PAGE, deliberately. This seam has no COUNT(*) over the ready +// predicate — the ready set is a UNION of two tables whose overlap the id query +// resolves in Go (domain/db/issue_search.go: an id present in both planes is a +// hard error here, not a de-duplication) — so a hand-rolled COUNT would be a +// second definition of the ready set. Running the SAME query Reader.Ready runs, +// unbounded, and taking its length makes the identity CountReady promises true +// BY CONSTRUCTION, including the way it fails. // // What that costs is the unbounded ready query the store-backed sibling avoids // with an indexed COUNT(*). Both front doors ask for this number only when a // page came back full, so the cost is paid on truncated listings and nowhere -// else; issueops.ReadyCounter promises the answer and says out loud that it -// does not promise the cost. +// else. func (c *readyCounter) CountReady(ctx context.Context, req publicops.ReadyRequest) (publicops.ReadyCountResult, error) { // The same builder the store-backed sibling runs, which is also // BuildReadyFilter with the page removed — so the refusals of a Limit and diff --git a/internal/storage/uow/ready_counter_contract_test.go b/internal/storage/uow/ready_counter_contract_test.go index 3185528b5..40d14369e 100644 --- a/internal/storage/uow/ready_counter_contract_test.go +++ b/internal/storage/uow/ready_counter_contract_test.go @@ -8,15 +8,14 @@ import ( ) // TestReadyCounterContract runs the ReadyCounter contract against the -// unit-of-work provider — the one implementation that does not hand back -// internal/workapi/storereadycounter, and the one that answers by counting the +// unit-of-work provider — the one implementation that answers by counting the // unbounded page rather than with an indexed COUNT(*). It is the SECOND of two // votes, not the third: the two store backends share the other body. // // One provider for the whole suite (each newUOWRoleFixtureProvider boots a real // Dolt sql-server) and NO t.Parallel: this backend has no per-test -// copy-on-write branch, so dolt_log and the issues table are database-global -// and a parallel subtest would corrupt another subtest's history delta. +// copy-on-write branch, so a parallel subtest would corrupt another's history +// delta. func TestReadyCounterContract(t *testing.T) { ctx := context.Background() fixture := newUOWReadyCounterFixture(t, ctx, "rdc") @@ -48,8 +47,8 @@ func newUOWReadyCounterFixture(t *testing.T, ctx context.Context, prefix string) t.Helper() provider := newUOWRoleFixtureProvider(t, ctx, prefix) // Through the capability accessors, not NewReadyCounter/NewIssueReader: a - // provider that stopped offering either role is the regression, and a - // constructor call would hide it. + // provider that stopped offering either role is the regression a constructor + // call would hide. source, ok := provider.(ReadyCounterSource) if !ok { t.Fatalf("provider %T does not offer the ReadyCounter accessor", provider) diff --git a/internal/storage/uow/stats_reporter.go b/internal/storage/uow/stats_reporter.go index d59ac7d34..c610fe7ee 100644 --- a/internal/storage/uow/stats_reporter.go +++ b/internal/storage/uow/stats_reporter.go @@ -9,8 +9,7 @@ import ( ) // StatsReporterSource is the capability accessor a unit-of-work provider offers -// for the summary-statistics role, the sibling of IssueReaderSource and -// CounterSource. +// for the summary-statistics role. type StatsReporterSource interface { StatsReporter() (publicops.StatsReporter, error) } @@ -38,14 +37,10 @@ var _ publicops.StatsReporter = (*statsReporter)(nil) // Stats answers the workspace summary inside one read-only unit of work. // -// IT DOES NOT TAKE THE SkipBlocked HINT, and that is a property of this seam -// rather than an oversight: domain.IssueUseCase publishes GetStatistics and no -// no-blocked variant, so there is no cheaper query to run. The alternative — -// running the full query and then nilling the two numbers it just computed — -// would answer more slowly and tell the caller less, so the hint is ignored -// and the full summary is returned. issueops.StatsRequest.SkipBlocked states -// that possibility from the caller's side: BlockedIssues being non-nil is how -// a caller learns the hint was not taken. +// IT DOES NOT TAKE THE SkipBlocked HINT: domain.IssueUseCase publishes +// GetStatistics and no no-blocked variant, so there is no cheaper query to run +// and the full summary is returned. BlockedIssues being non-nil is how a caller +// learns the hint was not taken. func (r *statsReporter) Stats(ctx context.Context, _ publicops.StatsRequest) (publicops.StatsResult, error) { return RunTxRead(ctx, r.provider, func(ctx context.Context, uw UnitOfWork) (publicops.StatsResult, error) { summary, err := uw.IssueUseCase().GetStatistics(ctx) @@ -64,10 +59,9 @@ func (r *statsReporter) Stats(ctx context.Context, _ publicops.StatsRequest) (pu // what makes "your work" mean one thing on both `bd status --assigned` routes. // // BOTH QUERIES SHARE ONE UNIT OF WORK here, where the store seam has no -// transaction to share, so this backend's two halves see one snapshot. The -// role deliberately does NOT promise that: a contract clause only one of the -// implementations can meet is not a contract. What all three share is the -// definition of the numbers. +// transaction to share, so this backend's two halves see one snapshot. The role +// deliberately does NOT promise that: a contract clause only one of the +// implementations can meet is not a contract. func (r *statsReporter) AssigneeStats(ctx context.Context, req publicops.AssigneeStatsRequest) (publicops.StatsResult, error) { assignee, err := workapi.ValidateStatsAssignee(req.Assignee) if err != nil { diff --git a/internal/storage/uow/stats_reporter_contract_test.go b/internal/storage/uow/stats_reporter_contract_test.go index f25b8cf97..91ebc5a0d 100644 --- a/internal/storage/uow/stats_reporter_contract_test.go +++ b/internal/storage/uow/stats_reporter_contract_test.go @@ -11,8 +11,7 @@ import ( // unit-of-work provider — the THIRD independent body for this role, not the // second. Both Dolt stores hand back internal/workapi/storestats, but each of // the three spells the blocked count and the ready subtraction itself -// (domain/db/issue.go here), so this suite is the only place a disagreement -// between the two stores and the use case can surface. +// (domain/db/issue.go here). // // One provider for the whole suite (each newUOWRoleFixtureProvider boots a real // Dolt sql-server) and NO t.Parallel: the workspace-wide cases assert @@ -67,8 +66,7 @@ func newUOWStatsReporterFixture(t *testing.T, ctx context.Context, prefix string t.Helper() provider := newUOWRoleFixtureProvider(t, ctx, prefix) // Through the capability accessor, not NewStatsReporter: a provider that - // stopped offering the role is the regression, and a constructor call would - // hide it. + // stopped offering the role is the regression. source, ok := provider.(StatsReporterSource) if !ok { t.Fatalf("provider %T does not offer the StatsReporter accessor", provider) diff --git a/internal/storage/uow/sweeper.go b/internal/storage/uow/sweeper.go index 972743c9c..d9340a4dc 100644 --- a/internal/storage/uow/sweeper.go +++ b/internal/storage/uow/sweeper.go @@ -11,9 +11,7 @@ import ( ) // SweeperSource is the capability accessor a unit-of-work provider offers for -// the bulk-clearance role, the sibling of CounterSource and IssueReaderSource. -// A consumer holding a provider by interface asks for the role here instead of -// reaching for a constructor. +// the bulk-clearance role. type SweeperSource interface { Sweeper() (publicops.Sweeper, error) } @@ -41,18 +39,15 @@ var _ publicops.Sweeper = (*sweeper)(nil) // Sweep clears the request's tier inside ONE unit of work. // // This is the genuinely separate body: the two store backends share -// issueops.SweepInTx, and this one reaches the same four questions through the -// domain use cases. What it must NOT do differently is which rows go — the -// selection, the pattern, the pinned and closed_at rechecks and the citation -// rule all run through the same internal/workapi functions the shared body -// runs, so the two implementations differ in their plumbing rather than in -// their answer. +// issueops.SweepInTx, and this one reaches the same questions through the domain +// use cases. What it must NOT do differently is WHICH ROWS GO — the selection, +// the pattern, the pinned and closed_at rechecks and the citation rule all run +// through the same internal/workapi functions the shared body runs. // // ONE UNIT OF WORK matters more here than it does for a read. The candidate // query and the delete are on the same transaction, so a row closed, unpinned // or cited between them cannot change what is deleted — the promise -// issueops.Sweeper.Sweep makes and the property the direct CLI route did not -// have before this role existed. +// issueops.Sweeper.Sweep makes. // // A DRY RUN TAKES A READ-ONLY UNIT OF WORK: it writes nothing, so it must not // take the committing path and leave a history entry describing a preview. @@ -123,11 +118,8 @@ func sweepInUOW(ctx context.Context, uw UnitOfWork, req publicops.SweepRequest) // sweepReferencedInUOW returns which of the candidates a not-done row cites, // reading the not-done set and its comments on the same unit of work the -// candidates came off. -// -// It reads the comments of the whole not-done set in ONE batch rather than one -// query per row, which is what makes the protection affordable on the corpora -// `bd prune` runs over. +// candidates came off. Comments are read for the whole not-done set in ONE +// batch rather than one query per row. func sweepReferencedInUOW(ctx context.Context, uw UnitOfWork, candidates []*types.Issue) (map[string]bool, error) { if len(candidates) == 0 { return nil, nil diff --git a/internal/storage/uow/sweeper_contract_test.go b/internal/storage/uow/sweeper_contract_test.go index 3ba29db88..0d5d1992e 100644 --- a/internal/storage/uow/sweeper_contract_test.go +++ b/internal/storage/uow/sweeper_contract_test.go @@ -9,12 +9,11 @@ import ( // TestSweeperContract runs the Sweeper contract against the unit-of-work // provider — the one implementation that does not run -// internal/storage/issueops.SweepInTx, and the one that reaches the same four -// questions through the domain use cases. It is the SECOND of two votes, not -// the third: the two store backends share the other body. +// internal/storage/issueops.SweepInTx. It is the SECOND of two votes, not the +// third: the two store backends share the other body. // -// One provider for the whole suite (each newUOWRoleFixtureProvider boots a -// real Dolt sql-server) and NO t.Parallel: this backend has no per-test +// One provider for the whole suite (each newUOWRoleFixtureProvider boots a real +// Dolt sql-server) and NO t.Parallel: this backend has no per-test // copy-on-write branch, so dolt_log and the issues table are database-global // and a parallel subtest would delete another subtest's rows — which on this // role is not a flake but the operation working as documented. @@ -58,8 +57,7 @@ func newUOWSweeperFixture(t *testing.T, ctx context.Context, prefix string) conf t.Helper() provider := newUOWRoleFixtureProvider(t, ctx, prefix) // Through the capability accessor, not NewSweeper: a provider that stopped - // offering the role is the regression, and a constructor call would hide - // it. + // offering the role is the regression a constructor call would hide. source, ok := provider.(SweeperSource) if !ok { t.Fatalf("provider %T does not offer the Sweeper accessor", provider) diff --git a/internal/storage/uow/tree_walker.go b/internal/storage/uow/tree_walker.go index 35f20de6e..48f56e4a1 100644 --- a/internal/storage/uow/tree_walker.go +++ b/internal/storage/uow/tree_walker.go @@ -38,14 +38,10 @@ var _ publicops.TreeWalker = (*treeWalker)(nil) // // One unit of work is load-bearing here rather than tidy. The walk is a root // probe, a recursion of adjacency reads and a hydration per node, and a `both` -// request runs the whole thing twice; on this backend all of it shares one -// transaction, so the answer describes a graph that existed rather than a -// stitching of several that did. The two store-backed bodies get the same -// property from their own read transaction. -// -// It is also the change this role makes to the PROXIED front door, which -// previously called the use case twice for a `both` walk with no transaction -// spanning the pair. +// request runs the whole thing twice; sharing one transaction is what makes the +// answer describe a graph that existed rather than a stitching of several that +// did. The proxied front door previously called the use case twice for a `both` +// walk with no transaction spanning the pair. func (t *treeWalker) WalkTree(ctx context.Context, req publicops.WalkTreeRequest) (publicops.TreeResult, error) { return RunTxRead(ctx, t.provider, func(ctx context.Context, uw UnitOfWork) (publicops.TreeResult, error) { return uw.DependencyUseCase().WalkDependencyTree(ctx, req) diff --git a/internal/storage/uow/tree_walker_contract_test.go b/internal/storage/uow/tree_walker_contract_test.go index 5435acf7d..8743a1011 100644 --- a/internal/storage/uow/tree_walker_contract_test.go +++ b/internal/storage/uow/tree_walker_contract_test.go @@ -14,10 +14,9 @@ import ( // For most roles this is the wiring where a genuine seam divergence shows up, // because the unit of work is a second body. NOT FOR THIS ROLE: it reaches the // same issueops.WalkDependencyTreeInTx through the domain repository, so what -// this leg checks is the WRAPPER — that the request survives the trip through -// the repository and the use case, that the walk runs inside one unit of work, -// and that the typed refusals still match errors.Is/errors.As after crossing two -// layers whose siblings all wrap their errors. +// this leg checks is the WRAPPER — that the request survives the trip and that +// the typed refusals still match errors.Is/errors.As after crossing two layers +// whose siblings wrap their errors. // // One provider for the whole suite and NO t.Parallel: this backend has no // per-test copy-on-write branch, so the tables are database-global. Every case @@ -101,8 +100,7 @@ func newUOWTreeWalkerFixture(t *testing.T, ctx context.Context, prefix string) c AddDependency: kit.AddDependency, // The frozen kit exposes reads only. This is the write half of the same // unfiltered raw-SQL pass-through its QueryScalar reads through, inside - // ONE committing unit of work — which is also what gives the whole script - // one session. + // ONE committing unit of work, which gives the whole script one session. Exec: func(ctx context.Context, statements []conformance.SQLStatement) error { return RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) { for _, stmt := range statements { diff --git a/internal/storage/uow/version_reconcile_integration_test.go b/internal/storage/uow/version_reconcile_integration_test.go index 6f1e14d9b..7fb4ebda0 100644 --- a/internal/storage/uow/version_reconcile_integration_test.go +++ b/internal/storage/uow/version_reconcile_integration_test.go @@ -67,10 +67,8 @@ func newTestUOWProvider(t *testing.T) UnitOfWorkProvider { // // The role cannot express that — every write through it commits — so the // rolled-back leg drives the metadata seam directly, the same seam the role's -// body writes through. Everything else the old version of this test covered -// (fresh install, no-op, upgrade, persistence into a NEW unit of work) is now -// TestVersionReconcilerContract, which runs it here and on the two store -// backends instead of only here. +// body writes through. Everything else about version reconciliation is +// TestVersionReconcilerContract, which runs here and on the two store backends. func TestReconcileVersionPersistsAcrossUOW(t *testing.T) { provider := newTestUOWProvider(t) ctx := context.Background() diff --git a/internal/storage/uow/version_reconciler.go b/internal/storage/uow/version_reconciler.go index e628092d3..faa36022b 100644 --- a/internal/storage/uow/version_reconciler.go +++ b/internal/storage/uow/version_reconciler.go @@ -55,14 +55,12 @@ func (r *versionReconciler) RecordedVersion(ctx context.Context, _ publicops.Rec // could be written after another process had already moved the marker past it, // which is the one way this role could ever lower the high-water mark. // -// VALIDATION HAPPENS BEFORE THE UNIT OF WORK IS OPENED, for the reason -// workspaceConfig.SetSetting gives — a refused reconciliation should cost no -// connection and no transaction, and this one runs before every command. +// VALIDATION HAPPENS BEFORE THE UNIT OF WORK IS OPENED, so a refused +// reconciliation costs no connection and no transaction. // // A NO-OP AND A REFUSAL STILL OPEN THE TRANSACTION and commit nothing, which is // how this backend answers "reconciliation records no history": the commit -// message is only spent when something was written, and RunTxResult treats a -// unit of work with nothing in it as the no-op it is. +// message is only spent when something was written. func (r *versionReconciler) ReconcileVersion(ctx context.Context, req publicops.VersionReconcileRequest) (publicops.VersionReconcileResult, error) { if _, err := workapi.ValidateReconcileVersion(req.CLIVersion); err != nil { return publicops.VersionReconcileResult{}, err diff --git a/internal/storage/uow/version_reconciler_contract_test.go b/internal/storage/uow/version_reconciler_contract_test.go index 7fc2aee8b..380cf4531 100644 --- a/internal/storage/uow/version_reconciler_contract_test.go +++ b/internal/storage/uow/version_reconciler_contract_test.go @@ -21,9 +21,7 @@ import ( // // One provider for the whole suite (each newUOWRoleFixtureProvider boots a real // Dolt sql-server) and NO t.Parallel: this backend has no per-test -// copy-on-write branch, so the metadata plane and dolt_log are database-global -// and a parallel subtest would corrupt another subtest's seeded markers and -// history delta. +// copy-on-write branch, so the metadata plane and dolt_log are database-global. func TestVersionReconcilerContract(t *testing.T) { ctx := context.Background() fixture := newUOWVersionReconcilerFixture(t, ctx, "vrec") diff --git a/internal/storage/uow/workspace_config.go b/internal/storage/uow/workspace_config.go index 2b0587c4c..ab0efaf46 100644 --- a/internal/storage/uow/workspace_config.go +++ b/internal/storage/uow/workspace_config.go @@ -69,17 +69,13 @@ func (c *workspaceConfig) ListSettings(ctx context.Context, _ publicops.ListSett // The projection of status.custom and types.custom into their normalized // tables happens in the config repository this use case sits on // (internal/storage/domain/db/config.go), so the row and its table land in -// THIS transaction and commit together. That is the same guarantee the store -// backends get from their own SetConfig, reached a different way — and it is -// the half of this plane that was missing on this backend until this role -// existed: a proxied `bd config set types.custom` wrote the string, left -// custom_types holding the previous set, and the table-first read kept -// answering with the previous set forever. +// THIS transaction and commit together. Before this role existed a proxied +// `bd config set types.custom` wrote the string, left custom_types holding the +// previous set, and the table-first read kept answering with it forever. // -// VALIDATION HAPPENS BEFORE THE UNIT OF WORK IS OPENED. A refused write should -// cost no connection and no transaction, and — more to the point — a validation -// failure raised inside RunTx would be indistinguishable at the call site from -// a write that rolled back. +// VALIDATION HAPPENS BEFORE THE UNIT OF WORK IS OPENED: a validation failure +// raised inside RunTx would be indistinguishable at the call site from a write +// that rolled back. func (c *workspaceConfig) SetSetting(ctx context.Context, req publicops.SetSettingRequest) (publicops.SetSettingResult, error) { value, err := workapi.ValidateSettingWrite(req.Key, req.Value) if err != nil { diff --git a/internal/storage/uow/workspace_config_contract_test.go b/internal/storage/uow/workspace_config_contract_test.go index a1384766a..c95a562c5 100644 --- a/internal/storage/uow/workspace_config_contract_test.go +++ b/internal/storage/uow/workspace_config_contract_test.go @@ -8,21 +8,18 @@ import ( ) // TestWorkspaceConfigContract runs the WorkspaceConfig contract against the -// unit-of-work provider — the one WorkspaceConfig implementation that does not -// hand back internal/workapi/storeworkspaceconfig, so this is the wiring where -// a genuine body divergence shows up. The two store backends share that body -// between them, which makes this the SECOND of two votes rather than the third. +// unit-of-work provider — the one implementation that does not hand back +// internal/workapi/storeworkspaceconfig. The two store backends share that +// body, which makes this the SECOND of two votes rather than the third. // -// It is also the wiring the projection cases were written for. This backend +// It is also the wiring the projection cases were written for: this backend // stored status.custom and types.custom without rewriting the tables that reads // consult first, so a proxied `bd config set types.custom` reported success and -// never took effect; ProjectsCustomTypes is the case that failed here and -// passed on the other two. +// never took effect. // // One provider for the whole suite (each newUOWRoleFixtureProvider boots a real // Dolt sql-server) and NO t.Parallel: this backend has no per-test -// copy-on-write branch, so the config plane and dolt_log are database-global -// and a parallel subtest would corrupt another subtest's history delta. +// copy-on-write branch, so the config plane and dolt_log are database-global. func TestWorkspaceConfigContract(t *testing.T) { ctx := context.Background() fixture := newUOWWorkspaceConfigFixture(t, ctx, "wcfg") @@ -77,8 +74,7 @@ func newUOWWorkspaceConfigFixture(t *testing.T, ctx context.Context, prefix stri // is what the protected-key cases need to remove and restore. provider := newUOWRoleFixtureProvider(t, ctx, prefix) // Through the capability accessor, not NewWorkspaceConfig: a provider that - // stopped offering the role is the regression, and a constructor call would - // hide it. + // stopped offering the role is the regression a constructor call would hide. source, ok := provider.(WorkspaceConfigSource) if !ok { t.Fatalf("provider %T does not offer the WorkspaceConfig accessor", provider) diff --git a/internal/workapi/bootstrap.go b/internal/workapi/bootstrap.go index ae4c45fe2..69e73467b 100644 --- a/internal/workapi/bootstrap.go +++ b/internal/workapi/bootstrap.go @@ -10,24 +10,17 @@ import ( // This file holds the shared, database-free half of issueops.Bootstrapper and // issueops.InitVerifier: the keys the identity lives under, the request // validation, and the normalization that makes the prefix a bootstrap stores -// the same string on every backend. It is a pure file for the reason -// PlanVersionReconcile is one — three implementations decide through it, so the -// answer cannot differ by backend, and the refusals are pinned in milliseconds -// without a database. +// the same string on every backend. It is pure so that three implementations +// decide through one body and the refusals pin without a database. // The two keys a workspace's IDENTITY lives under. // -// They are named here rather than spelled at each call site because three -// implementations, two front doors and three conformance wirings read and write -// them, and a key spelled differently in one of those places is an identity -// nothing else can find — which looks exactly like a database nobody ever -// initialized. +// They are named here rather than spelled at each call site because a key +// spelled differently in one of the places that read them is an identity nothing +// else can find — which looks exactly like a database nobody ever initialized. // // These two and no others decide whether a substrate is bootstrapped at all, // and either one of them present is what Bootstrapper.Bootstrap refuses over. -// The per-clone bookkeeping `bd init` also seeds — the fingerprints, the -// synced-at marker, the recorded binary version — is not identity and is not -// named here; see issueops.Bootstrapper for why it is not on the role either. const ( // ConfigKeyIssuePrefix lives on the durable settings plane, which is where // every other reader of the prefix already looks for it. @@ -40,12 +33,10 @@ const ( // NormalizeBootstrapPrefix returns the prefix as a bootstrap STORES it. // -// The settings plane strips a trailing hyphen from this key and has since long -// before these roles existed. Doing it here instead of relying on that means -// BootstrapResult.Prefix, the value a later VerifyIdentity answers with and the -// string the front door goes on to print are one value on every backend, -// including the unit-of-work one whose write does not pass through that plane's -// normalizer at all. +// The settings plane strips a trailing hyphen from this key. Doing it here +// instead of relying on that means BootstrapResult.Prefix and the value a later +// VerifyIdentity answers with are one value on every backend, including the +// unit-of-work one whose write does not pass through that plane's normalizer. func NormalizeBootstrapPrefix(prefix string) string { return strings.TrimRight(prefix, "-") } @@ -53,15 +44,9 @@ func NormalizeBootstrapPrefix(prefix string) string { // ValidateBootstrapRequest refuses a bootstrap that cannot produce a usable // workspace and returns the request as it will be WRITTEN. // -// Every implementation validates through it BEFORE opening a transaction, so a -// refused bootstrap costs no database work — which is what makes -// issueops.Bootstrapper's "a refusal writes nothing" true of the connection as -// well as of the keys. -// -// Both fields are required, and for the same underlying reason stated two ways -// on the request: a substrate carrying one of them and not the other is exactly -// the half-identified state the refusal below cannot tell from a deliberately -// half-provisioned database. +// Every implementation validates through it BEFORE opening a transaction, which +// is what makes issueops.Bootstrapper's "a refusal writes nothing" true of the +// connection as well as of the keys. func ValidateBootstrapRequest(req issueops.BootstrapRequest) (issueops.BootstrapRequest, error) { req.Prefix = NormalizeBootstrapPrefix(req.Prefix) if req.Prefix == "" { diff --git a/internal/workapi/bootstrap_test.go b/internal/workapi/bootstrap_test.go index 245124641..1f88bae93 100644 --- a/internal/workapi/bootstrap_test.go +++ b/internal/workapi/bootstrap_test.go @@ -11,9 +11,7 @@ import ( // because they are the same on every backend by construction: all three // implementations validate through ValidateBootstrapRequest and decide the // refusal through RefuseIdentifiedSubstrate. The conformance contract is left -// to assert what only a real backend can show — that a refusal wrote nothing, -// that the identity is there for the next caller, that the two reads are one -// snapshot. +// to assert what only a real backend can show. func validBootstrapRequest() issueops.BootstrapRequest { return issueops.BootstrapRequest{ @@ -50,8 +48,8 @@ func TestValidateBootstrapRequestNormalizesOnlyTheTrailingHyphen(t *testing.T) { if err != nil { t.Fatalf("ValidateBootstrapRequest(): %v", err) } - // Interior hyphens survive; only the trailing run goes, which is exactly - // what the settings plane has always done to this key. + // Interior hyphens survive; only the trailing run goes, which is what the + // settings plane has always done to this key. if got.Prefix != "my-proj" { t.Fatalf("normalized prefix = %q, want %q", got.Prefix, "my-proj") } diff --git a/internal/workapi/count.go b/internal/workapi/count.go index 4f07a9061..0d2453b15 100644 --- a/internal/workapi/count.go +++ b/internal/workapi/count.go @@ -10,12 +10,9 @@ import ( ) // countGroupColumns is the closed set issueops.CountByGroupRequest.GroupBy -// promises, mapped to what the storage seam calls each dimension. It is the -// one place the two vocabularies meet: the role publishes "type" because that -// is what the flag is called, storage groups by issue_type, and the seam's own -// switch already knows the mapping — this table exists so an unknown value is -// refused HERE, as ErrValidation, rather than reaching storage and coming back -// as an unclassifiable "unsupported groupBy" string. +// promises, mapped to what the storage seam calls each dimension. It exists so +// an unknown value is refused HERE, as ErrValidation, rather than reaching +// storage and coming back as an unclassifiable "unsupported groupBy" string. var countGroupColumns = map[issueops.CountGroup]string{ issueops.CountGroupStatus: "status", issueops.CountGroupPriority: "priority", @@ -35,18 +32,16 @@ func ValidateCountGroup(group issueops.CountGroup) (string, error) { return column, nil } -// BuildCountFilter turns a count request into the storage-level filter. It is -// the single definition of what `bd count` means, the way BuildListFilter is -// for `bd list`, and every implementation of issueops.Counter builds through -// it. +// BuildCountFilter turns a count request into the storage-level filter: the +// single definition of what `bd count` means, which every implementation of +// issueops.Counter builds through. // // It is a SEPARATE builder rather than a call into BuildListFilter with the // paging fields blanked out, because the two commands disagree about the -// default answer: a listing hides closed, pinned, template and gate rows, and -// a count hides none of them. The one place they must agree is -// --include-infra, and that agreement is pinned by a golden-style test -// comparing this builder's output against BuildListFilter's for the same -// request (count_test.go, GH#4387). +// default answer: a listing hides closed, pinned, template and gate rows, and a +// count hides none of them. The one place they must agree is --include-infra, +// pinned by a golden-style test comparing this builder's output against +// BuildListFilter's for the same request (count_test.go, GH#4387). // // cfg supplies the workspace's infra vocabulary and is only read under // IncludeInfra; a zero ListConfig falls back to the default infra set. @@ -72,8 +67,7 @@ func BuildCountFilter(in issueops.CountRequest, cfg ListConfig) (types.IssueFilt // Status and IssueType are taken as written. Neither is validated against // the workspace vocabulary: issueops.CountRequest promises an unrecognized - // name matches nothing rather than failing, which is what both front doors - // have always done. + // name matches nothing rather than failing. if in.Status != "" && in.Status != "all" { status := types.Status(in.Status) filter.Status = &status @@ -89,8 +83,7 @@ func BuildCountFilter(in issueops.CountRequest, cfg ListConfig) (types.IssueFilt // NormalizeLabels allocates its own slice, so the caller's Labels and // LabelsAny are read and never written — the snapshot promise on - // issueops.Counter, which matters here because these are the role's only - // reference-typed request fields. + // issueops.Counter. if labels := utils.NormalizeLabels(in.Labels); len(labels) > 0 { filter.Labels = labels } @@ -115,18 +108,15 @@ func BuildCountFilter(in issueops.CountRequest, cfg ListConfig) (types.IssueFilt // `bd count --include-infra ` returns exactly the number of rows // `bd list --include-infra --all` materializes: // -// - the wisps table is merged into the count (SkipWisps=false), picking up -// no_history beads (durable work stored in the wisps tier) and ephemeral -// wisps, exactly like list's merge path; -// - template molecules are excluded (list's default without -// --include-templates); -// - gate beads are excluded unless gates are explicitly requested via -// --type gate (list's default without --include-gates); -// - counting an infra type (agent/role/message, or the store-configured -// set) routes to the ephemeral wisps tier, like list's infra-type listing. +// - the wisps table is merged in (SkipWisps=false), picking up no_history +// beads and ephemeral wisps, like list's merge path; +// - template molecules are excluded (list's default); +// - gate beads are excluded unless requested via --type gate; +// - counting an infra type (agent/role/message, or the store-configured set) +// routes to the ephemeral wisps tier, like list's infra-type listing. // -// The non-flag path never calls this function: a count without IncludeInfra -// keeps its historical durable-only semantics. +// A count without IncludeInfra never calls this and keeps its historical +// durable-only semantics. func applyCountIncludeInfra(filter *types.IssueFilter, issueType string, cfg ListConfig) { filter.SkipWisps = false diff --git a/internal/workapi/count_test.go b/internal/workapi/count_test.go index 1daa56f14..0a85996cc 100644 --- a/internal/workapi/count_test.go +++ b/internal/workapi/count_test.go @@ -53,8 +53,7 @@ func TestBuildCountFilterIncludeInfraMirrorsListFilter(t *testing.T) { t.Errorf("IssueType = %v, list --include-infra --all uses %v", got.IssueType, want.IssueType) } // A count defaults to all statuses and all pinned states, which is - // exactly what list's --all flag selects: none of these dimensions - // may carry a filter on either side. + // exactly what list's --all flag selects. if !reflect.DeepEqual(got.Status, want.Status) { t.Errorf("Status = %v, list --include-infra --all uses %v", got.Status, want.Status) } @@ -121,7 +120,7 @@ func TestBuildCountFilterDefaultsToTheDurablePlane(t *testing.T) { countPtrStr(got.Status), got.ExcludeStatus, countPtrStr(got.Pinned)) } // Limit and Offset are the two fields the count seam ignores, and - // issueops.CountRequest has no knob for either. Pinning them at zero says + // issueops.CountRequest has no knob for either: pinning them at zero says // the builder does not invent one. if got.Limit != 0 || got.Offset != 0 { t.Errorf("Limit=%d Offset=%d, want a count filter to bound nothing", got.Limit, got.Offset) @@ -161,8 +160,8 @@ func TestBuildCountFilterNormalizesLabelsAndIDs(t *testing.T) { // TestBuildCountFilterTakesStatusAndTypeAsWritten pins the deliberate absence // of validation: an unrecognized status or type reaches the filter as written -// and matches nothing, rather than failing. Both front doors have always -// behaved this way and a scripted caller counting a retired status reads 0. +// and matches nothing, rather than failing. A scripted caller counting a +// retired status reads 0. func TestBuildCountFilterTakesStatusAndTypeAsWritten(t *testing.T) { got, err := BuildCountFilter(issueops.CountRequest{Status: "no-such-status", IssueType: "no-such-type"}, ListConfig{}) if err != nil { @@ -189,9 +188,9 @@ func TestBuildCountFilterTakesStatusAndTypeAsWritten(t *testing.T) { // TestValidateCountGroupClosesTheDimensionSet pins the five published // dimensions and the typed refusal for everything else. The refusal has to be -// ErrValidation rather than a bare string because both front doors classify -// it, and because an empty GroupBy reaching storage would come back as an -// "unsupported groupBy" that no caller can match on. +// ErrValidation rather than a bare string because both front doors classify it, +// and because an empty GroupBy reaching storage comes back as an "unsupported +// groupBy" that no caller can match on. func TestValidateCountGroupClosesTheDimensionSet(t *testing.T) { for group, want := range map[issueops.CountGroup]string{ issueops.CountGroupStatus: "status", diff --git a/internal/workapi/delete.go b/internal/workapi/delete.go index 4ad629068..1e2011a68 100644 --- a/internal/workapi/delete.go +++ b/internal/workapi/delete.go @@ -13,21 +13,18 @@ import ( // the orphan list and the dependents refusal — are ordered. // // Every implementation runs these, so `bd delete` has one definition of a -// malformed request rather than one per backend, and the parts that decide -// what the answer MEANS are pinned in delete_test.go without a database. +// malformed request rather than one per backend. // // What is NOT here is the deletion. The existence probe, the guard and the -// erasure need one transaction (issueops.Deleter.Delete), which no interface -// above a store publishes; the bodies live in +// erasure need one transaction (issueops.Deleter.Delete); the bodies live in // internal/storage/issueops/delete.go and in the unit-of-work provider. // ValidateDeleteRequest applies the request rules every Deleter implementation // shares, before anything is read. // -// There is deliberately no require-a-filter analog of the sweep gate here. -// A delete request carries no predicate at all: a caller cannot spell -// "everything" without typing every id, so the shape that gate protects -// against does not exist on this role. The guard that does matter — dependents +// There is deliberately no require-a-filter analog of the sweep gate here: a +// delete request carries no predicate at all, so a caller cannot spell +// "everything" without typing every id. The guard that does matter — dependents // outside the request — needs the graph and therefore lives in the bodies. func ValidateDeleteRequest(in issueops.DeleteRequest) error { if len(in.IDs) == 0 { @@ -46,8 +43,7 @@ func ValidateDeleteRequest(in issueops.DeleteRequest) error { // // First-mention order rather than sorted, because it is the order the front // doors echo back in their "issues not found" line and in the confirmation -// hint they print, and a caller re-reading its own `--from-file` list against -// that output should not have to re-sort it. +// hint they print. // // It assumes a request already accepted by ValidateDeleteRequest, so no entry // trims to empty. diff --git a/internal/workapi/delete_test.go b/internal/workapi/delete_test.go index da63bd7d8..dfddb6a94 100644 --- a/internal/workapi/delete_test.go +++ b/internal/workapi/delete_test.go @@ -10,8 +10,7 @@ import ( // The database-free half of issueops.Deleter, pinned in milliseconds. Every // backend runs these functions, so a disagreement about what a malformed -// request means, or about what order the ids come back in, is caught here -// rather than three times over in the conformance suite. +// request means is caught here rather than three times over in conformance. func TestValidateDeleteRequest(t *testing.T) { for _, test := range []struct { diff --git a/internal/workapi/query.go b/internal/workapi/query.go index 19c3314ae..2da2f674b 100644 --- a/internal/workapi/query.go +++ b/internal/workapi/query.go @@ -18,13 +18,11 @@ const DefaultQueryLimit = 50 // QueryPlan is an evaluated query request: what to ask the database, what to // decide in Go afterwards, and how to cut the page. // -// It exists because the two executions of one query are NOT the same shape. -// A filter-expressible expression is a filter the database answers whole; an -// expression with an OR or a general NOT is a base filter plus a predicate, -// and the predicate is a Go function that no seam can push down. Both -// implementations of issueops.Querier build one of these, so the decision -// about which shape an expression takes — and, crucially, what row limit each -// shape may carry — is made once here rather than once per backend. +// The two executions of one query are NOT the same shape. A filter-expressible +// expression is a filter the database answers whole; an expression with an OR +// or a general NOT is a base filter plus a Go predicate no seam can push down. +// Both implementations of issueops.Querier build one of these, so which shape +// an expression takes — and what row limit it may carry — is decided once here. type QueryPlan struct { // Filter is what the database is asked. For a predicate query it carries // the expression's base filters and NO row limit; see BuildQueryPlan. @@ -35,11 +33,10 @@ type QueryPlan struct { // Limit is the number of rows the CALLER receives, which is not always // what Filter carries. 0 means unlimited. Limit int - // Offset is the number of matching rows to skip. It is reported here - // rather than written onto Filter because only one of the two seams can - // render OFFSET, and only the filter-expressible shape may push it down at - // all — skipping candidate rows before a predicate runs would drop rows - // the predicate never accepted (issueops/querier.go:70-86). + // Offset is the number of matching rows to skip. It is reported here rather + // than written onto Filter because only the filter-expressible shape may + // push it down: skipping candidate rows before a predicate runs would drop + // rows the predicate never accepted (issueops/querier.go:70-86). Offset int // SortBy and Reverse are the display order, applied by the page epilogue. SortBy string @@ -49,22 +46,18 @@ type QueryPlan struct { // RequiresPredicate reports whether this plan is answered in two steps. func (p QueryPlan) RequiresPredicate() bool { return p.Predicate != nil } -// BuildQueryPlan turns a query request into its executable plan. It is the -// single definition of what `bd query` MEANS: the parse, the evaluation, the -// default closed exclusion, the limit defaulting, and the row bound each shape -// of query may carry. +// BuildQueryPlan turns a query request into its executable plan: the parse, the +// evaluation, the default closed exclusion, the limit defaulting, and the row +// bound each shape of query may carry. // // THE ROW BOUND IS THE WHOLE REASON THIS IS ONE FUNCTION. A predicate query's // Filter gets NO limit — the predicate must see every candidate row, or the // page it produces is an arbitrary prefix of the answer reported as the whole -// of it (issueops/querier.go:118-133). Both front doors used to bound that -// query at max(3*Limit, 100) and filter what came back, in two places, with -// the arithmetic written out twice. The bound is gone and the decision has one -// home. +// of it (issueops/querier.go:118-133). The front doors used to bound that query +// at max(3*Limit, 100) and filter what came back; that bound is gone. // -// It reads no configuration and touches no store: the query vocabulary is -// closed and the evaluator resolves it entirely, which is why both -// implementations can share this without either supplying a config source. +// It reads no configuration and touches no store, so both implementations share +// it without supplying a config source. func BuildQueryPlan(in issueops.QueryRequest) (QueryPlan, error) { expression := strings.TrimSpace(in.Expression) if expression == "" { @@ -143,13 +136,11 @@ func mentionsStatus(node query.Node) bool { // ApplyQueryPredicate keeps the rows the predicate accepts, in the order they // arrived. Both implementations of issueops.Querier call it, so "what the -// predicate is applied to" cannot come to mean two things: it is applied to -// every row the database returned, and the database was not asked for a -// bounded set. +// predicate is applied to" cannot come to mean two things: every row the +// database returned, and the database was not asked for a bounded set. // // A nil row, or a row carrying no issue, is dropped rather than offered to the -// predicate — a predicate reads issue fields and would be handed nothing to -// read. +// predicate. func ApplyQueryPredicate(rows []*types.IssueWithCounts, predicate func(*types.Issue) bool) []*types.IssueWithCounts { if predicate == nil { return rows diff --git a/internal/workapi/query_test.go b/internal/workapi/query_test.go index e9143a411..afad6a4a9 100644 --- a/internal/workapi/query_test.go +++ b/internal/workapi/query_test.go @@ -14,16 +14,15 @@ func queryRequest(expression string, limit int) issueops.QueryRequest { } // TestBuildQueryPlanLeavesAPredicateQueryUNBOUNDED is the unit-level pin on the -// defect this role shipped to fix, and it is here rather than only in the -// conformance contract because it is the ARITHMETIC that was wrong, not the -// backend: both front doors set the row limit to max(3*Limit, 100) and filtered -// what came back, so an OR query over a workspace with more than a hundred -// candidate rows returned a prefix of its answer and reported it as whole. +// defect this role shipped to fix. Both front doors set the row limit to +// max(3*Limit, 100) and filtered what came back, so an OR query over a workspace +// with more than a hundred candidate rows returned a prefix of its answer and +// reported it as whole. // -// A predicate query's filter must carry NO row limit. There is no value it -// could carry that is safe: the predicate rejects an unknown fraction of the -// rows the database returns, so any bound on the fetch is a bound on the -// matches with no relationship to the page the caller asked for. +// A predicate query's filter must carry NO row limit. The predicate rejects an +// unknown fraction of the rows the database returns, so any bound on the fetch +// is a bound on the matches with no relationship to the page the caller asked +// for. func TestBuildQueryPlanLeavesAPredicateQueryUNBOUNDED(t *testing.T) { for _, expression := range []string{ "type=bug OR type=feature", @@ -132,8 +131,8 @@ func TestBuildQueryPlanExcludesClosedUnlessTheExpressionSaysOtherwise(t *testing } // TestBuildQueryPlanRefusals pins every deterministic refusal, each of which a -// front door would otherwise have to make for itself — which is how the two -// routes came to disagree about what an offset means. +// front door would otherwise make for itself — which is how the two routes came +// to disagree about what an offset means. func TestBuildQueryPlanRefusals(t *testing.T) { for _, test := range []struct { name string @@ -156,9 +155,8 @@ func TestBuildQueryPlanRefusals(t *testing.T) { // TestAQueryExpressionRefusalNamesItselfForTheWire pins the message prefix // internal/httpapi matches to turn an unparseable expression into a 400 on `q` -// rather than a 500. It is the same bounded prose dependency the filter -// builders already carry, written down here so a reword fails beside the -// sentence it rewords. +// rather than a 500, written down here so a reword fails beside the sentence it +// rewords. func TestAQueryExpressionRefusalNamesItselfForTheWire(t *testing.T) { _, err := BuildQueryPlan(issueops.QueryRequest{Expression: "===invalid==="}) if err == nil { diff --git a/internal/workapi/ready.go b/internal/workapi/ready.go index c0956c862..0da6df20d 100644 --- a/internal/workapi/ready.go +++ b/internal/workapi/ready.go @@ -98,19 +98,15 @@ func BuildReadyFilter(in issueops.ReadyRequest) (types.WorkFilter, error) { // BuildReadyCountFilter turns a ready request into the storage-level filter a // COUNT of the ready set runs against: BuildReadyFilter's filter with the page -// removed, and the single definition of what `bd ready`'s published total -// means. +// removed, and the single definition of what `bd ready`'s published total means. // // It refuses a request carrying a page. issueops.ReadyCounter.CountReady // promises its answer equals len(Reader.Ready(r with Limit=0).Items), and a // Limit would make that "how many of the first N" while an Offset would -// subtract the rows it skipped from the size of a set that still holds them — -// so both are ErrValidation here rather than accepted and dropped, which is -// the same call ValidateClaimNextRequest makes for the same reason. +// subtract the rows it skipped from the size of a set that still holds them. // // The zeroed limit is set on a LOCAL copy: a nil Limit means the shared ready -// default at BuildReadyFilter, so an unlimited count has to say so explicitly, -// and the caller's request is not the place to say it. +// default at BuildReadyFilter, so an unlimited count has to say so explicitly. func BuildReadyCountFilter(in issueops.ReadyRequest) (types.WorkFilter, error) { if in.Limit != nil { return types.WorkFilter{}, fmt.Errorf("%w: a ready count does not take a limit", issueops.ErrValidation) diff --git a/internal/workapi/ready_count_test.go b/internal/workapi/ready_count_test.go index 32e64a6ce..94352b9da 100644 --- a/internal/workapi/ready_count_test.go +++ b/internal/workapi/ready_count_test.go @@ -10,10 +10,9 @@ import ( // TestBuildReadyCountFilterIsTheUnboundedReadyFilter is the filter-level half // of the identity issueops.ReadyCounter promises: the predicate a count runs is -// the predicate the listing runs, with the page taken off. Asserting it against -// BuildReadyFilter rather than field by field is what makes it survive a new -// ReadyRequest field — one the count builder forgot to carry would show up here -// as a difference, where a field-by-field check would simply not mention it. +// the predicate the listing runs, with the page taken off. It is asserted +// against BuildReadyFilter rather than field by field so a new ReadyRequest +// field the count builder forgot to carry shows up as a difference. func TestBuildReadyCountFilterIsTheUnboundedReadyFilter(t *testing.T) { priority := 1 request := issueops.ReadyRequest{ @@ -59,10 +58,8 @@ func TestBuildReadyCountFilterIsTheUnboundedReadyFilter(t *testing.T) { // TestBuildReadyCountFilterRefusesAPage pins the two deterministic refusals the // role states (issueops/readycounter.go:74-86). The explicitly-unlimited limit -// is refused with the rest: an unlimited count is the only kind there is, so -// asking for one is asking for the default, and accepting the pointer here -// would make "unset" and "explicitly unlimited" mean different things to a -// count than they mean to a page. +// is refused with the rest: accepting the pointer here would make "unset" and +// "explicitly unlimited" mean different things to a count than to a page. func TestBuildReadyCountFilterRefusesAPage(t *testing.T) { limit := 10 unlimited := 0 @@ -99,10 +96,8 @@ func TestBuildReadyCountFilterLeavesTheRequestAlone(t *testing.T) { } // TestBuildReadyCountFilterRefusesAnInvalidSort keeps the count's refusals a -// SUPERSET of the listing's rather than a replacement: a sort policy the -// listing rejects is not quietly accepted here because a count has no order. -// The request has to stay the listing's request for the identity to hold, and -// that includes the ways it can be wrong. +// SUPERSET of the listing's: a sort policy the listing rejects is not quietly +// accepted here because a count has no order. func TestBuildReadyCountFilterRefusesAnInvalidSort(t *testing.T) { if _, err := BuildReadyCountFilter(issueops.ReadyRequest{Sort: "bogus"}); !errors.Is(err, issueops.ErrValidation) { t.Fatalf("BuildReadyCountFilter(sort=bogus) error = %v, want ErrValidation", err) diff --git a/internal/workapi/stats.go b/internal/workapi/stats.go index f5075de2c..5ba37e558 100644 --- a/internal/workapi/stats.go +++ b/internal/workapi/stats.go @@ -12,21 +12,17 @@ import ( // which every implementation answers by asking storage two questions and // folding the answers, rather than by running one aggregate. // -// The workspace-wide question needs nothing here. It is a single seam call on -// every backend (GetStatistics / GetStatisticsNoBlocked on a store, the use -// case's GetStatistics through a unit of work), so there is no request to -// translate and a builder for it would be a function that returns nothing. -// This file exists because the assignee-scoped answer is ASSEMBLED, and -// assembling it twice is how the two front doors would come to disagree about -// what "your work" means. +// The workspace-wide question needs nothing here — it is a single seam call on +// every backend. This file exists because the assignee-scoped answer is +// ASSEMBLED, and assembling it twice is how the two front doors would come to +// disagree about what "your work" means. // ValidateStatsAssignee resolves the actor an assignee-scoped summary answers // for, refusing an empty or whitespace-only one with ErrValidation. // -// It returns the value UNCHANGED when it accepts, and the return exists to make -// that explicit at every call site: an assignee is an opaque identifier this -// layer has no vocabulary for, so trimming it would silently answer for a -// different actor than the caller named. +// It returns the value UNCHANGED when it accepts: an assignee is an opaque +// identifier this layer has no vocabulary for, so trimming it would silently +// answer for a different actor than the caller named. func ValidateStatsAssignee(assignee string) (string, error) { if strings.TrimSpace(assignee) == "" { return "", fmt.Errorf("assignee must not be empty for an assignee-scoped summary%.0w", issueops.ErrValidation) @@ -41,17 +37,15 @@ func ValidateStatsAssignee(assignee string) (string, error) { // omission: no status restriction (the fold tallies every status, including // closed), no limit (a capped scan would silently under-report a busy actor's // total), and no wisp suppression — the search seam merges the ephemeral tier -// unless told not to, and issueops.StatsReporter.AssigneeStats documents the -// wider set that produces. +// unless told not to. func BuildStatsAssigneeIssueFilter(assignee string) types.IssueFilter { return types.IssueFilter{Assignee: &assignee} } // BuildStatsAssigneeWorkFilter is the ready-work predicate for the same actor. -// It is a second filter type rather than the one above because ready work is a -// different question with its own exclusions, which is exactly why -// AssigneeStats can report a ready count the workspace-wide answer's -// subtraction would not produce. +// It is a second filter type because ready work is a different question with +// its own exclusions — which is why AssigneeStats can report a ready count the +// workspace-wide answer's subtraction would not produce. func BuildStatsAssigneeWorkFilter(assignee string) types.WorkFilter { return types.WorkFilter{Assignee: &assignee} } @@ -59,20 +53,19 @@ func BuildStatsAssigneeWorkFilter(assignee string) types.WorkFilter { // FoldStatsAssigneeSummary turns one actor's rows and their ready-work count // into the summary both front doors print. // -// It is the single definition of what `bd status --assigned` means. Everything -// it does NOT set is as much a part of that definition as what it does: -// PinnedIssues, EpicsEligibleForClosure and AverageLeadTime stay zero, which -// AssigneeStats states and this function is the reason for. +// It is the single definition of what `bd status --assigned` means. What it +// does NOT set is part of that definition: PinnedIssues, +// EpicsEligibleForClosure and AverageLeadTime stay zero. // // BlockedIssues and ReadyIssues are always non-nil here, including for an actor // with no rows at all. The nil pointers are the workspace-wide answer's // skipped-scan signal (issueops.StatsRequest.SkipBlocked) and mean "not // computed"; this path always computes both, so leaving them nil would render // as "(skipped)" on a summary that skipped nothing. -// A nil element is skipped and counted nowhere, TotalIssues included: it is a -// row the seam failed to hydrate rather than a row of work, and counting it in -// the total while it lands in no status bucket would publish an inconsistency -// as data. +// +// A nil element is skipped and counted nowhere, TotalIssues included: counting +// a row the seam failed to hydrate while it lands in no status bucket would +// publish an inconsistency as data. func FoldStatsAssigneeSummary(issues []*types.Issue, readyCount int) types.Statistics { stats := types.Statistics{} diff --git a/internal/workapi/stats_test.go b/internal/workapi/stats_test.go index 68eedc758..1cfd73a10 100644 --- a/internal/workapi/stats_test.go +++ b/internal/workapi/stats_test.go @@ -11,9 +11,8 @@ import ( // TestValidateStatsAssignee pins the one refusal on the summary role, and pins // it here because it needs no database: an assignee-scoped summary of nobody is // ErrValidation, and an accepted assignee comes back BYTE-IDENTICAL. The second -// half is the load-bearing one — trimming would answer for a different actor -// than the caller named, and it is exactly the kind of helpfulness a validator -// grows by accident. +// half is the load-bearing one: trimming would answer for a different actor +// than the caller named. func TestValidateStatsAssignee(t *testing.T) { for _, blank := range []string{"", " ", "\t\n"} { got, err := ValidateStatsAssignee(blank) @@ -61,9 +60,8 @@ func TestBuildStatsAssigneeFiltersCarryOnlyTheAssignee(t *testing.T) { } // TestFoldStatsAssigneeSummary is the definition of what `bd status --assigned` -// means, checked without a database. It moved here from cmd/bd/status_test.go -// with the fold itself: both routes read it from this one function now, so a -// change to any number below is a change to both surfaces at once. +// means, checked without a database. Both routes read it from this one function, +// so a change to any number below is a change to both surfaces at once. func TestFoldStatsAssigneeSummary(t *testing.T) { tests := []struct { name string diff --git a/internal/workapi/storecounter/counter.go b/internal/workapi/storecounter/counter.go index 7cb0050ac..f873d5900 100644 --- a/internal/workapi/storecounter/counter.go +++ b/internal/workapi/storecounter/counter.go @@ -3,14 +3,9 @@ // accessor hands back. // // It is a package of its own for the reason internal/workapi/storereader is — -// see that package's doc. A constructor sitting in internal/workapi would be a -// one-line drop-in for store.Counter() from any front door, and one that -// silently skips the decorators, because a decorator adds its layer in its own -// accessor. Down here the only importers are the two Dolt store packages and -// the cmd-bd-role-constructors depguard rule in .golangci.yml makes a front -// door importing it a lint failure rather than a review comment. -// -// The accessor is the door. This is the thing behind it. +// see that package's doc. Down here the only importers are the two Dolt store +// packages, and the cmd-bd-role-constructors depguard rule in .golangci.yml +// makes a front door importing it a lint failure rather than a review comment. package storecounter import ( @@ -82,11 +77,10 @@ func (c *storeCounter) CountByGroup(ctx context.Context, req issueops.CountByGro // // TWO THINGS ARE DELIBERATE. The load is SKIPPED unless IncludeInfra is set, // because that flag is the only thing in a count request the configuration -// reaches — paying three config queries on every plain count would make the -// cheapest command in the tree the one that talks to storage most. And when it -// does run it runs PER CALL rather than once at construction: the infra -// vocabulary is workspace state a caller can change between two counts, and a -// counter that cached it would answer for the older workspace. +// reaches. And when it does run it runs PER CALL rather than once at +// construction: the infra vocabulary is workspace state a caller can change +// between two counts, and a counter that cached it would answer for the older +// workspace. func (c *storeCounter) filter(ctx context.Context, req issueops.CountRequest) (types.IssueFilter, error) { var cfg workapi.ListConfig if req.IncludeInfra { diff --git a/internal/workapi/storequerier/querier.go b/internal/workapi/storequerier/querier.go index d7b1d666b..f0c91f42c 100644 --- a/internal/workapi/storequerier/querier.go +++ b/internal/workapi/storequerier/querier.go @@ -3,14 +3,9 @@ // accessor hands back. // // It is a package of its own for the reason internal/workapi/storereader is — -// see that package's doc. A constructor sitting in internal/workapi would be a -// one-line drop-in for store.Querier() from any front door, and one that -// silently skips the decorators, because a decorator adds its layer in its own -// accessor. Down here the only importers are the two Dolt store packages and -// the cmd-bd-role-constructors depguard rule in .golangci.yml makes a front -// door importing it a lint failure rather than a review comment. -// -// The accessor is the door. This is the thing behind it. +// see that package's doc. Down here the only importers are the two Dolt store +// packages, and the cmd-bd-role-constructors depguard rule in .golangci.yml +// makes a front door importing it a lint failure rather than a review comment. package storequerier import ( @@ -35,9 +30,9 @@ type storeQuerier struct{ store storage.DoltStorage } var _ issueops.Querier = (*storeQuerier)(nil) -// offsetBackend names the backend an Offset refusal comes from, spelled as -// storereader spells it: one name for both engines, because it is the BODY — -// not the engine underneath it — that cannot page by offset. +// offsetBackend names the backend an Offset refusal comes from: one name for +// both engines, because it is the BODY — not the engine underneath it — that +// cannot page by offset. const offsetBackend = "dolt-store" func (q *storeQuerier) Query(ctx context.Context, req issueops.QueryRequest) (issueops.IssuePage, error) { @@ -46,20 +41,18 @@ func (q *storeQuerier) Query(ctx context.Context, req issueops.QueryRequest) (is return issueops.IssuePage{}, err } // UNIFORM, not per-expression. This body could skip rows for a predicate - // query, where the skip happens in Go — but which shape an expression - // takes is the evaluator's decision, not the caller's, so an Offset that - // worked for one expression and refused another would be unpredictable - // from the outside (issueops/querier.go:70-86). + // query, but which shape an expression takes is the evaluator's decision, + // so an Offset that worked for one expression and refused another would be + // unpredictable from the outside (issueops/querier.go:70-86). if plan.Offset != 0 { return issueops.IssuePage{}, &issueops.ErrUnsupported{Op: "Querier.Query(Offset)", Backend: offsetBackend} } filter := plan.Filter if !plan.RequiresPredicate() { - // The store seam has no HasMore of its own, so ask for one row past - // the page and let its presence be the answer. A predicate query - // carries no row limit at all, so there is nothing here to extend: - // its verdict comes from the count of MATCHES below. + // The store seam has no HasMore of its own, so ask for one row past the + // page and let its presence be the answer. A predicate query carries no + // row limit to extend: its verdict comes from the count of MATCHES. filter = workapi.WithFetchOneExtra(filter) } @@ -69,9 +62,9 @@ func (q *storeQuerier) Query(ctx context.Context, req issueops.QueryRequest) (is } rows = workapi.ApplyQueryPredicate(rows, plan.Predicate) - // The shared epilogue, for the reason every other page read runs it: the - // sort, the cut and the verdict written out longhand is how two routes of - // one command came to disagree about `--sort id --limit 5`. + // The shared epilogue: the sort, the cut and the verdict written out + // longhand is how two routes of one command came to disagree about + // `--sort id --limit 5`. items, hasMore := workapi.FinishPage(rows, plan.SortBy, plan.Reverse, plan.Limit, false) return issueops.IssuePage{Items: items, HasMore: hasMore}, nil } diff --git a/internal/workapi/storereadycounter/counter.go b/internal/workapi/storereadycounter/counter.go index c7f69dcc8..87a30bffc 100644 --- a/internal/workapi/storereadycounter/counter.go +++ b/internal/workapi/storereadycounter/counter.go @@ -3,15 +3,11 @@ // ReadyCounter accessor hands back. // // It is a package of its own for the reason internal/workapi/storereader and -// internal/workapi/storecounter are — see either package's doc. A constructor -// sitting in internal/workapi would be a one-line drop-in for -// store.ReadyCounter() from any front door, and one that silently skips the -// decorators, because a decorator adds its layer in its own accessor. Down -// here the only importers are the two Dolt store packages, and the -// cmd-bd-role-constructors depguard rule in .golangci.yml makes a front door -// importing it a lint failure rather than a review comment. -// -// The accessor is the door. This is the thing behind it. +// internal/workapi/storecounter are: a constructor sitting in internal/workapi +// would be a one-line drop-in for store.ReadyCounter() that silently skips the +// decorators. Down here the only importers are the two Dolt store packages, and +// the cmd-bd-role-constructors depguard rule in .golangci.yml makes a front +// door importing it a lint failure rather than a review comment. package storereadycounter import ( @@ -26,15 +22,13 @@ import ( // *EmbeddedDoltStore answer identically because the difference between them is // below storage.DoltStorage, not above it. // -// THE PARAMETER IS THE CHEAP SEAM ITSELF, not storage.DoltStorage, and that is -// the one thing this body does differently from its siblings. `bd ready --json` +// THE PARAMETER IS THE CHEAP SEAM ITSELF, not storage.DoltStorage, which is the +// one thing this body does differently from its siblings. `bd ready --json` // used to ask for that seam at RUNTIME — unwrap the decorators, type-assert to // storage.ReadyWorkCounter, and fall back to an unbounded ready query when the -// assertion missed — because the value it held was a decorated interface that -// could not answer for its own inner store. Reached through an accessor the -// question is settled at COMPILE time: a store that cannot size the ready set -// cannot construct this body, so there is no silent fallback to a mega-query -// and no branch nothing exercises. +// assertion missed. Reached through an accessor the question is settled at +// COMPILE time: a store that cannot size the ready set cannot construct this +// body, so there is no silent fallback to a mega-query. func New(store storage.ReadyWorkCounter) (issueops.ReadyCounter, error) { if store == nil { return nil, &issueops.ErrUnsupported{Op: "storereadycounter.New", Backend: "nil"} @@ -49,11 +43,9 @@ var _ issueops.ReadyCounter = (*storeReadyCounter)(nil) // CountReady sizes the ready set with the store's indexed COUNT(*) path. // // The filter comes from the shared builder, so the predicate counted here and -// the predicate Reader.Ready lists are one predicate, and the identity -// CountReady promises is a property of the query rather than of this file: -// storage.ReadyWorkCounter is documented as identical to -// len(GetReadyWorkWithCounts(filter with Limit=0)), which is the same filter -// this builder produces for the same request. +// the predicate Reader.Ready lists are one predicate. storage.ReadyWorkCounter +// is documented as identical to len(GetReadyWorkWithCounts(filter with +// Limit=0)), which is the same filter this builder produces. func (c *storeReadyCounter) CountReady(ctx context.Context, req issueops.ReadyRequest) (issueops.ReadyCountResult, error) { filter, err := workapi.BuildReadyCountFilter(req) if err != nil { diff --git a/internal/workapi/storestats/reporter.go b/internal/workapi/storestats/reporter.go index 6f980427a..7bc04905f 100644 --- a/internal/workapi/storestats/reporter.go +++ b/internal/workapi/storestats/reporter.go @@ -3,14 +3,9 @@ // StatsReporter accessor hands back. // // It is a package of its own for the reason internal/workapi/storecounter is — -// see that package's doc. A constructor sitting in internal/workapi would be a -// one-line drop-in for store.StatsReporter() from any front door, and one that -// silently skips the decorators, because a decorator adds its layer in its own -// accessor. Down here the only importers are the two Dolt store packages and -// the cmd-bd-role-constructors depguard rule in .golangci.yml makes a front -// door importing it a lint failure rather than a review comment. -// -// The accessor is the door. This is the thing behind it. +// see that package's doc. Down here the only importers are the two Dolt store +// packages, and the cmd-bd-role-constructors depguard rule in .golangci.yml +// makes a front door importing it a lint failure rather than a review comment. package storestats import ( @@ -69,10 +64,9 @@ func (r *storeStatsReporter) Stats(ctx context.Context, req issueops.StatsReques // // The ready-work failure is reported as zero ready work rather than as an // error, which AssigneeStats documents as this role's one number that may not -// be an answer. It is the shipped behavior of both `bd status --assigned` -// routes and is kept rather than tightened here: the alternative turns a -// summary that is right about five numbers into no summary at all, on the one -// query in this role slow enough to time out on a large graph. +// be an answer. The alternative turns a summary that is right about five +// numbers into no summary at all, on the one query in this role slow enough to +// time out on a large graph. func (r *storeStatsReporter) AssigneeStats(ctx context.Context, req issueops.AssigneeStatsRequest) (issueops.StatsResult, error) { assignee, err := workapi.ValidateStatsAssignee(req.Assignee) if err != nil { diff --git a/internal/workapi/storeversionreconciler/versionreconciler.go b/internal/workapi/storeversionreconciler/versionreconciler.go index bd580634b..375271b01 100644 --- a/internal/workapi/storeversionreconciler/versionreconciler.go +++ b/internal/workapi/storeversionreconciler/versionreconciler.go @@ -3,15 +3,10 @@ // VersionReconciler accessor hands back. // // It is a package of its own for the reason internal/workapi/storereader and -// internal/workapi/storeworkspaceconfig are — see those packages' docs. A -// constructor sitting in internal/workapi would be a one-line drop-in for -// store.VersionReconciler() from any front door, and one that silently skips -// the decorators, because a decorator adds its layer in its own accessor. Down +// internal/workapi/storeworkspaceconfig are — see those packages' docs. Down // here the only importers are the two Dolt store packages, and the // cmd-bd-role-constructors depguard rule in .golangci.yml makes a front door -// importing it a lint failure rather than a review comment. -// -// The accessor is the door. This is the thing behind it. +// importing it a lint failure. package storeversionreconciler import ( @@ -23,8 +18,8 @@ import ( ) // New returns the version-marker surface backed by a store handle. *DoltStore -// and *EmbeddedDoltStore answer identically because the difference between them -// is below storage.DoltStorage, not above it. +// and *EmbeddedDoltStore answer identically: the difference between them is +// below storage.DoltStorage. func New(store storage.DoltStorage) (issueops.VersionReconciler, error) { if store == nil { return nil, &issueops.ErrUnsupported{Op: "storeversionreconciler.New", Backend: "nil"} @@ -47,16 +42,13 @@ func (r *storeVersionReconciler) RecordedVersion(ctx context.Context, _ issueops // ReconcileVersion reads the markers, decides through the shared planner and // writes only what the plan asks for. // -// THE TWO WRITES ARE NOT ONE TRANSACTION on this backend, and that is stated -// rather than hidden: storage.DoltStorage publishes methods, not transactions, -// so a failure between them leaves the marker moved and the mark behind. The -// consequence is bounded and benign — a mark below the marker only ever means -// the next older binary is refused by the marker instead of by the mark, which -// is the same refusal — and buying atomicity would mean a transaction-scoped -// body for two writes to a dolt-ignored plane that no other reader shares. +// THE TWO WRITES ARE NOT ONE TRANSACTION on this backend: storage.DoltStorage +// publishes methods, not transactions, so a failure between them leaves the +// marker moved and the mark behind. The consequence is bounded — a mark below +// the marker only ever means the next older binary is refused by the marker +// instead of by the mark, which is the same refusal. func (r *storeVersionReconciler) ReconcileVersion(ctx context.Context, req issueops.VersionReconcileRequest) (issueops.VersionReconcileResult, error) { - // Validate before reading anything: a refused reconciliation should cost no - // round trip, and this one runs on every startup. + // Validate before reading anything: this runs on every startup. if _, err := workapi.ValidateReconcileVersion(req.CLIVersion); err != nil { return issueops.VersionReconcileResult{}, err } @@ -85,9 +77,7 @@ func (r *storeVersionReconciler) ReconcileVersion(ctx context.Context, req issue // readMarkers reads both markers, which is the whole cost of the path that // changes nothing: two point reads of a dolt-ignored table, no configuration -// load, no second connection and no lock. Both are read even when the first one -// already decides the outcome, because RecordedVersion publishes the pair and a -// second shape of this helper would be a second thing to keep true. +// load, no second connection and no lock. func (r *storeVersionReconciler) readMarkers(ctx context.Context) (recorded, mark string, err error) { recorded, err = r.store.GetLocalMetadata(ctx, workapi.MetadataKeyVersion) if err != nil { diff --git a/internal/workapi/storeworkspaceconfig/workspaceconfig.go b/internal/workapi/storeworkspaceconfig/workspaceconfig.go index 7da742166..7dc8e647b 100644 --- a/internal/workapi/storeworkspaceconfig/workspaceconfig.go +++ b/internal/workapi/storeworkspaceconfig/workspaceconfig.go @@ -3,15 +3,10 @@ // WorkspaceConfig accessor hands back. // // It is a package of its own for the reason internal/workapi/storereader and -// internal/workapi/storecounter are — see those packages' docs. A constructor -// sitting in internal/workapi would be a one-line drop-in for -// store.WorkspaceConfig() from any front door, and one that silently skips the -// decorators, because a decorator adds its layer in its own accessor. Down here -// the only importers are the two Dolt store packages and the +// internal/workapi/storecounter are — see those packages' docs. Down here the +// only importers are the two Dolt store packages, and the // cmd-bd-role-constructors depguard rule in .golangci.yml makes a front door // importing it a lint failure rather than a review comment. -// -// The accessor is the door. This is the thing behind it. package storeworkspaceconfig import ( @@ -64,14 +59,12 @@ func (c *storeWorkspaceConfig) ListSettings(ctx context.Context, _ issueops.List // Set writes one setting through the store's own config verb. // -// THE PROJECTION IS THE STORE'S, not this body's, and that is deliberate: both -// store backends' SetConfig already rewrite custom_statuses / custom_types -// inside the same retryable transaction as the row, and they additionally drop -// the process-local caches those tables feed. Re-implementing either here would -// put the projection outside that transaction — a row that landed and a table -// that did not is precisely the state the projection exists to prevent — and -// would leave the caches stale. What this body owns is the REFUSALS, which the -// store seam does not make. +// THE PROJECTION IS THE STORE'S, not this body's: both store backends' +// SetConfig already rewrite custom_statuses / custom_types inside the same +// retryable transaction as the row, and drop the process-local caches those +// tables feed. Re-implementing either here would put the projection outside that +// transaction — a row that landed and a table that did not is precisely the +// state the projection exists to prevent. What this body owns is the REFUSALS. func (c *storeWorkspaceConfig) SetSetting(ctx context.Context, req issueops.SetSettingRequest) (issueops.SetSettingResult, error) { value, err := workapi.ValidateSettingWrite(req.Key, req.Value) if err != nil { diff --git a/internal/workapi/sweep.go b/internal/workapi/sweep.go index 61d40f8d4..500fd9096 100644 --- a/internal/workapi/sweep.go +++ b/internal/workapi/sweep.go @@ -14,8 +14,7 @@ import ( // The shared, DATABASE-FREE half of issueops.Sweeper: what a sweep request // means, which candidates survive the recheck, and what counts as a citation. // Every implementation of the role runs these, so `bd purge` and `bd prune` -// have one definition rather than one per backend, and the parts that decide -// what the answer MEANS are pinned in sweep_test.go in milliseconds. +// have one definition rather than one per backend. // // What is NOT here is the sweep itself. Selecting rows and deleting them needs // one transaction (issueops.Sweeper.Sweep), which no interface above a store @@ -25,10 +24,9 @@ import ( // ValidateSweepRequest applies the request rules every Sweeper implementation // shares, before anything is read. // -// The require-a-filter refusal for the durable tier is the one that matters, -// and it is HERE rather than in a CLI handler on purpose: it is a safety -// invariant, so a second front door inherits it by calling the role rather -// than by remembering to re-implement it. See issueops.SweepRequest. +// The require-a-filter refusal for the durable tier is a safety invariant, so +// it lives HERE rather than in a CLI handler: a second front door inherits it +// by calling the role. See issueops.SweepRequest. func ValidateSweepRequest(in issueops.SweepRequest) error { switch in.Tier { case issueops.SweepEphemeral, issueops.SweepDurable: @@ -62,10 +60,9 @@ func ValidateSweepRequest(in issueops.SweepRequest) error { // the cutoff. // // The pattern is deliberately NOT in the filter. Globs are matched in Go -// (MatchesSweepPattern) because the storage seam has no glob predicate and a -// LIKE translation would silently disagree with filepath.Match on `[...]` and -// on the escape rules — a disagreement that, on this operation, decides which -// rows are deleted. +// (MatchesSweepPattern) because a LIKE translation would silently disagree with +// filepath.Match on `[...]` and on the escape rules — a disagreement that, on +// this operation, decides which rows are deleted. // // Call ValidateSweepRequest first; this builder assumes a validated request // and does not re-refuse one. @@ -86,8 +83,7 @@ func BuildSweepCandidateFilter(in issueops.SweepRequest) types.IssueFilter { // MatchesSweepPattern reports whether an id is admitted by a request's // IDPattern. An empty pattern admits everything. // -// A malformed pattern reports false here; ValidateSweepRequest is what refuses -// it, so this function is never the place a bad glob is discovered. +// A malformed pattern reports false here; ValidateSweepRequest is what refuses it. func MatchesSweepPattern(pattern, id string) bool { if pattern == "" { return true @@ -103,9 +99,9 @@ func MatchesSweepPattern(pattern, id string) bool { // THE ORDER IS PART OF THE ANSWER, and issueops.Sweeper.Sweep states it: the // pattern narrows first, so a pinned row the pattern excluded is not counted // as protected — it was never a candidate. The three closed_at buckets are -// defenses against the tier query returning a row it was not asked for, and -// they are counted rather than dropped so a disagreement between the query and -// the recheck is visible instead of silent. +// defenses against the tier query returning a row it was not asked for, counted +// rather than dropped so a disagreement between the query and the recheck is +// visible instead of silent. // // cutoff is the request's ClosedBefore; a nil cutoff performs the presence // checks and skips the comparison. @@ -138,10 +134,10 @@ func FilterSweepCandidates(issues []*types.Issue, pattern string, cutoff *time.T } // SweepDefenseSkips is how many candidates the recheck rejected as -// self-inconsistent — the three closed_at buckets plus the unreadable row. -// It is separate from the two PROTECTIONS (pinned, referenced) because a -// non-zero value here is a defense firing rather than a normal outcome, and -// the front doors warn on exactly that. +// self-inconsistent — the three closed_at buckets plus the unreadable row. It +// is separate from the two PROTECTIONS (pinned, referenced) because a non-zero +// value here is a defense firing rather than a normal outcome, and the front +// doors warn on exactly that. func SweepDefenseSkips(s issueops.SweepSkips) int { return s.Unreadable + s.NotClosed + s.UnknownClosedAt + s.ClosedAtOrAfterCutoff } @@ -154,8 +150,7 @@ func SweepDefenseSkips(s issueops.SweepSkips) int { // what the storage seam takes reliably on both planes (a Statuses set, not an // ExcludeStatus). Reading the workspace's custom statuses is required, not // best-effort: a scan that missed a custom active status would under-protect -// and delete a bead a live bead still cites — see -// issueops.SweepRequest.ProtectReferenced. +// and delete a bead a live bead still cites. func NotDoneStatusesForSweep(custom []types.CustomStatus) []types.Status { statuses := []types.Status{ types.StatusOpen, @@ -183,12 +178,11 @@ func BuildSweepReferenceScanFilter(custom []types.CustomStatus) types.IssueFilte // set in arbitrary text. It is the whole of what "cited" means for // issueops.SweepRequest.ProtectReferenced. // -// It is bucketed by FIRST BYTE and each bucket sorted longest-first, because -// the scan is run over every not-done bead's description, notes and comments: -// a naive strings.Contains per candidate is O(candidates x text) and the -// reference protection exists on the command that runs over the largest -// corpora. Longest-first inside a bucket is what makes `be-1.1` win over -// `be-1` where both are candidates and both start at the same offset. +// It is bucketed by FIRST BYTE and each bucket sorted longest-first: the scan +// runs over every not-done bead's description, notes and comments, where a +// naive strings.Contains per candidate is O(candidates x text). Longest-first +// inside a bucket is what makes `be-1.1` win over `be-1` where both are +// candidates and both start at the same offset. type CandidateIDMatcher struct { byFirstByte map[byte][]string } @@ -254,10 +248,9 @@ func isASCIIWordByte(b byte) bool { // PartitionSweepReferenced splits candidates into the ones no not-done row // cites and the ones some row does, and returns the bounded sample -// issueops.SweepResult.ReferencedIDs carries. -// -// The kept slice preserves the candidate order, and so does the sample, so two -// runs over one snapshot report the same ids. +// issueops.SweepResult.ReferencedIDs carries. Both the kept slice and the +// sample preserve the candidate order, so two runs over one snapshot report the +// same ids. func PartitionSweepReferenced(candidates []*types.Issue, referenced map[string]bool) (kept []*types.Issue, referencedCount int, sample []string) { kept = make([]*types.Issue, 0, len(candidates)) for _, issue := range candidates { diff --git a/internal/workapi/sweep_test.go b/internal/workapi/sweep_test.go index ed7c0d934..3d9a8dfb2 100644 --- a/internal/workapi/sweep_test.go +++ b/internal/workapi/sweep_test.go @@ -11,10 +11,9 @@ import ( "github.com/steveyegge/beads/issueops" ) -// The DATABASE-FREE half of issueops.Sweeper, pinned in milliseconds: what a -// request means, which candidates survive the recheck, and what counts as a -// citation. The conformance contract is left to assert what only a real -// backend can show. +// The DATABASE-FREE half of issueops.Sweeper: what a request means, which +// candidates survive the recheck, and what counts as a citation. The +// conformance contract asserts what only a real backend can show. func TestValidateSweepRequestRequiresATier(t *testing.T) { for _, test := range []struct { @@ -272,10 +271,8 @@ func TestPartitionSweepReferencedBoundsTheSample(t *testing.T) { // TestCandidateIDMatcherLargeFixture is the NFR-02 budget from be-5sn, moved // here with the scan itself: 10K bodies of ~5KB each, matched against 100 -// candidates, in under five seconds. It is the matcher that made the old -// per-candidate substring scan unaffordable, so the matcher is what the budget -// is written against — the store round trips it used to include measured the -// fixture, not the algorithm. +// candidates, in under five seconds. It is written against the MATCHER, +// because the store round trips it used to include measured the fixture. func TestCandidateIDMatcherLargeFixture(t *testing.T) { if testing.Short() { t.Skip("skipping large fixture bench") @@ -327,8 +324,7 @@ func TestCandidateIDMatcherLargeFixture(t *testing.T) { // The race detector adds multi-x overhead that invalidates a wall-clock // budget, so only enforce the bound in non-race builds. The correctness - // assertions below still run under -race, which is where the large-fixture - // pass earns its keep as a data-race check. + // assertions below still run under -race. if !raceEnabled && elapsed > maxDurationSeconds*time.Second { t.Errorf("scan took %v; must complete in <%ds on a %d-body fixture", elapsed, maxDurationSeconds, bodyCount) } diff --git a/internal/workapi/versionreconcile.go b/internal/workapi/versionreconcile.go index 253a7ad30..c449dbdec 100644 --- a/internal/workapi/versionreconcile.go +++ b/internal/workapi/versionreconcile.go @@ -14,58 +14,42 @@ import ( // answer cannot differ by backend, and the cases that matter (a downgrade below // the marker, a downgrade below the mark, a catch-up to the mark) are pinned in // milliseconds without a database. -// -// It is ALSO where the duplication went. Before this role, the direct route -// compared versions in cmd/bd/version_tracking.go and the proxied route -// compared them again in a use case, each with its own copy of the dotted -// comparison; the two agreed, but nothing made them agree and no test compared -// them. The conformance contract is left to assert what only a real backend can -// show: that the markers persist, that a refusal writes nothing, and that -// neither the read nor the write touches history. // MetadataKeyVersion and MetadataKeyVersionMax are the two clone-local, -// dolt-ignored keys the version markers live under. -// -// They are named here rather than spelled at each call site because three -// implementations and three conformance wirings write them, and a key spelled -// differently in one of those places is a marker nothing else can find — which -// looks exactly like a workspace that was never reconciled. +// dolt-ignored keys the version markers live under. Three implementations and +// three conformance wirings write them, and a key spelled differently in one of +// those places is a marker nothing else can find — which looks exactly like a +// workspace that was never reconciled. const ( MetadataKeyVersion = "bd_version" MetadataKeyVersionMax = "bd_version_max" ) // VersionReconcilePlan is what a reconciliation decided, plus which of the two -// markers that decision has to write. -// -// The writes are reported as flags rather than performed here because the three -// backends reach the metadata plane differently — two through a store handle, -// one through a unit of work — and the decision is the same on all of them. +// markers that decision has to write. The writes are reported as flags rather +// than performed here because the three backends reach the metadata plane +// differently — two through a store handle, one through a unit of work. type VersionReconcilePlan struct { // Result is what the caller returns, unchanged, once the writes below - // succeed. It is complete before any write happens, which is what makes - // "a failed reconciliation reports an error rather than a wrong outcome" - // checkable: there is no field a partial write could still be filling in. + // succeed. It is complete before any write happens, so there is no field a + // partial write could still be filling in. Result issueops.VersionReconcileResult // RecordVersion asks for MetadataKeyVersion to be set to Result.Current. // It is set only for a migration; a no-op and a refusal both write nothing. RecordVersion bool // RecordHighWaterMark asks for MetadataKeyVersionMax to be set to - // Result.Current, and is a SEPARATE flag because the mark and the marker do - // not always move together: a workspace catching up to a mark a newer - // binary already left moves the marker to the mark and leaves the mark - // where it is. + // Result.Current. It is a SEPARATE flag because the two do not always move + // together: a workspace catching up to a mark a newer binary already left + // moves the marker to the mark and leaves the mark where it is. RecordHighWaterMark bool } // ValidateReconcileVersion checks the version a caller wants to record, and // returns it unchanged. // -// It is separate from the planner so a body can refuse BEFORE it reads -// anything or opens a unit of work — the same reason -// issueops.WorkspaceConfig's bodies validate ahead of RunTx. This runs on -// every startup, so a refusal that costs a round trip is a refusal that costs -// every command. +// It is separate from the planner so a body can refuse BEFORE it reads anything +// or opens a unit of work. This runs on every startup, so a refusal that costs +// a round trip is a refusal that costs every command. // // The only rule at this end is that a version has to name something. Recording // "" over a real marker would silently take the downgrade guard down with it, @@ -101,7 +85,7 @@ func PlanVersionReconcile(cliVersion, recorded, highWaterMark string) (VersionRe // it means an older binary is opening a workspace a newer one has already // prepared, and relabelling it would make the next upgrade re-run work that // is already done. The mark catches the same thing after someone has since - // moved the marker back down; it is the only reason the second key exists. + // moved the marker back down — the only reason the second key exists. refuse := (recorded != "" && compareDottedVersions(cliVersion, recorded) < 0) || (highWaterMark != "" && compareDottedVersions(cliVersion, highWaterMark) < 0) if refuse { @@ -123,9 +107,8 @@ func PlanVersionReconcile(cliVersion, recorded, highWaterMark string) (VersionRe // It is deliberately NOT a semver comparison, and issueops.VersionReconcileRequest // says so where callers will read it: "1.2.0" and "1.2.0-rc1" compare EQUAL // here, so a pre-release binary reconciles a workspace its release counterpart -// already recorded without either refusing the other. Both front doors have -// compared versions this way since the markers existed, and tightening it would -// start refusing binaries that work today. +// already recorded without either refusing the other. Tightening it would start +// refusing binaries that work today. func compareDottedVersions(v1, v2 string) int { parts1 := strings.Split(v1, ".") parts2 := strings.Split(v2, ".") diff --git a/internal/workapi/versionreconcile_test.go b/internal/workapi/versionreconcile_test.go index acceff0cf..690750e19 100644 --- a/internal/workapi/versionreconcile_test.go +++ b/internal/workapi/versionreconcile_test.go @@ -13,9 +13,8 @@ import ( // // The two marker states a workspace reaches ONLY through something outside the // role — a recorded version below the high-water mark — are here rather than -// there for the same reason: they are decisions, and reproducing them on three -// backends costs a seeded write per case to test arithmetic that never touches -// storage. +// there: reproducing them on three backends costs a seeded write per case to +// test arithmetic that never touches storage. func TestPlanVersionReconcile(t *testing.T) { for _, test := range []struct { name string diff --git a/internal/workapi/workspaceconfig.go b/internal/workapi/workspaceconfig.go index a1cd39ff0..6ac8e1556 100644 --- a/internal/workapi/workspaceconfig.go +++ b/internal/workapi/workspaceconfig.go @@ -13,22 +13,19 @@ import ( // // It lives here for the reason those do: three implementations of // issueops.WorkspaceConfig have to agree about it, and it is checkable without -// a database, so the rules are unit-tested in workspaceconfig_test.go and the -// conformance contract is left to pin what only a real backend can show — that -// the row and its projection land together. +// a database. The conformance contract is left to pin what only a real backend +// can show — that the row and its projection land together. // // It is deliberately NOT the whole of `bd config set`. Which SOURCE a key // belongs to (config.yaml, git config, this plane) is resolved by the front -// door, because two of the three sources are files on the client's filesystem; -// see issueops/workspaceconfig.go. What is here is what remains once the key is -// known to belong to the database. +// door; see issueops/workspaceconfig.go. // ValidateSettingKey checks a key a caller wants to READ or REMOVE, and // returns it unchanged. // -// The only rule at this end is that a key has to name something. An empty key -// selects no row, so answering it with the empty value that an unset key -// returns would report "not set" for a question nobody asked. +// The only rule at this end is that a key has to name something: an empty key +// answered with the empty value an unset key returns would report "not set" +// for a question nobody asked. func ValidateSettingKey(key string) (string, error) { if strings.TrimSpace(key) == "" { return "", fmt.Errorf("%w: config key must not be empty", issueops.ErrValidation) @@ -37,33 +34,26 @@ func ValidateSettingKey(key string) (string, error) { } // ValidateSettingWrite checks a key and value a caller wants to STORE, and -// returns the value as it will be stored. -// -// It returns the value rather than nothing so that a body cannot store a -// different string from the one that was checked. Nothing transforms it today -// — issueops.SetSettingResult.Value promises exactly that — and the signature -// is what keeps the promise checkable if a normalization is ever added. +// returns the value as it will be stored, so that a body cannot store a +// different string from the one that was checked. func ValidateSettingWrite(key, value string) (string, error) { if _, err := ValidateSettingKey(key); err != nil { return "", err } - // The prefix is owned by bd init --prefix, bd bootstrap and - // bd rename-prefix. Refused HERE rather than at the front door because - // `bd config set` is not the only door that reaches this plane: `bd config - // set-many` partitions its pairs by source and writes the database ones - // straight through, so before this role existed `bd config set-many - // issue_prefix=x` walked past the guard `bd config set` enforces and - // re-prefixed the workspace. + // The prefix is owned by bd init --prefix, bd bootstrap and bd + // rename-prefix. Refused HERE rather than at the front door because `bd + // config set` is not the only door that reaches this plane: before this + // role existed `bd config set-many issue_prefix=x` walked past the guard + // and re-prefixed the workspace. if key == issueops.SettingKeyIssuePrefix || key == "issue-prefix" { return "", fmt.Errorf("%w: %q is set by bd init --prefix, bd bootstrap or bd rename-prefix, not by a config write: "+ "storing it here would leave existing ids under the old prefix with nothing to reconcile them", issueops.ErrValidation, key) } // status.custom is PROJECTED into custom_statuses, which reads consult - // first, so a value that cannot be projected must not become a row. The - // projection would refuse it a moment later anyway (SyncCustomStatusesTable - // parses too); checking first is what makes the refusal a validation error - // with the caller's own value in it rather than a storage failure. + // first, so a value that cannot be projected must not become a row. + // Checking here rather than leaving it to SyncCustomStatusesTable is what + // makes the refusal a validation error rather than a storage failure. if key == issueops.SettingKeyStatusCustom && value != "" { if _, err := types.ParseCustomStatusConfig(value); err != nil { return "", fmt.Errorf("%w: invalid %s value: %v", issueops.ErrValidation, key, err) diff --git a/internal/workapi/workspaceconfig_test.go b/internal/workapi/workspaceconfig_test.go index abe5785ba..e82a4c5b5 100644 --- a/internal/workapi/workspaceconfig_test.go +++ b/internal/workapi/workspaceconfig_test.go @@ -13,8 +13,7 @@ import ( // The conformance contract pins what only a real backend can show — that a row // and its projection land together, and that a refusal leaves both alone. What // is here is the part all three implementations share, so a rule broken here -// would otherwise fail three suites at once and be diagnosed from a Dolt server -// boot. +// would otherwise fail three suites at once. func TestValidateSettingKeyRefusesOnlyTheEmptyKey(t *testing.T) { for _, key := range []string{"", " ", "\t\n"} { @@ -23,8 +22,7 @@ func TestValidateSettingKeyRefusesOnlyTheEmptyKey(t *testing.T) { } } // Everything else is a key, including the shapes a front door routes - // elsewhere: which SOURCE owns a key is not this validator's question, and - // a rule here that guessed at it would refuse writes the CLI performs. + // elsewhere: which SOURCE owns a key is not this validator's question. for _, key := range []string{ "custom.anything", "status.custom", @@ -49,9 +47,8 @@ func TestValidateSettingWriteRefusesTheProtectedKeyInBothSpellings(t *testing.T) if !errors.Is(err, issueops.ErrValidation) { t.Fatalf("ValidateSettingWrite(%q) error = %v, want ErrValidation", key, err) } - // The message names the commands that DO own the prefix. A refusal that - // only said "no" would send a caller looking for a flag on the verb - // that just refused them. + // The message names the commands that DO own the prefix, so a caller is + // not left hunting for a flag on the verb that just refused them. for _, want := range []string{"bd init --prefix", "bd bootstrap", "bd rename-prefix"} { if !strings.Contains(err.Error(), want) { t.Errorf("ValidateSettingWrite(%q) message %q does not name %q", key, err, want) @@ -64,9 +61,8 @@ func TestValidateSettingWriteParsesTheCustomStatusValue(t *testing.T) { for _, value := range []string{ "awaiting_review", "awaiting_review:active,awaiting_docs:wip", - // Empty CLEARS the set, and clearing is not a value to parse. The - // projection reads it the same way, so refusing it here would make the - // key impossible to unset by writing. + // Empty CLEARS the set, and clearing is not a value to parse. Refusing + // it here would make the key impossible to unset by writing. "", } { if _, err := ValidateSettingWrite("status.custom", value); err != nil { @@ -88,7 +84,7 @@ func TestValidateSettingWriteParsesTheCustomStatusValue(t *testing.T) { // TestValidateSettingWriteReturnsTheValueUnchanged is the machine half of // issueops.SetSettingResult.Value's promise: a successful write stores what the // caller sent. Nothing normalizes today, and this is what would fail if -// something started to without the result type saying so. +// something started to. func TestValidateSettingWriteReturnsTheValueUnchanged(t *testing.T) { for _, test := range []struct{ key, value string }{ {"custom.thing", " spaced "}, diff --git a/issue_roles_external_test.go b/issue_roles_external_test.go index 7763b6503..63711327e 100644 --- a/issue_roles_external_test.go +++ b/issue_roles_external_test.go @@ -195,12 +195,9 @@ func TestIssueRelationsExposesTypedUnsupportedError(t *testing.T) { } } -// TestCounterKeepsTelemetryOutermost is the count role's version of -// TestIssueRelationsKeepsTelemetryOutermost, and it is the READ answer for the -// same reason: counting fires no completion hooks, so the hook decorator adds -// no layer and the outermost surface a caller gets is the instrumented one. A -// hook wrapper appearing here would mean a layer landed on a path with nothing -// to fire. +// TestCounterKeepsTelemetryOutermost is the READ answer for the reason +// TestIssueRelationsKeepsTelemetryOutermost gives: counting fires no completion +// hooks, so the hook decorator adds no layer. func TestCounterKeepsTelemetryOutermost(t *testing.T) { t.Setenv("BD_OTEL_STDOUT", "true") instrumented, ok := telemetry.WrapStorage(&dolt.DoltStore{}).(*telemetry.InstrumentedStorage) @@ -217,16 +214,13 @@ func TestCounterKeepsTelemetryOutermost(t *testing.T) { } } -// TestWorkspaceConfigKeepsTelemetryOutermost is the settings role's version of -// the pin, and it is the only place in this file where the read answer is given -// for a role that WRITES. +// TestWorkspaceConfigKeepsTelemetryOutermost is the first place in this file +// where the read answer is given for a role that WRITES. // // The hook decorator's vocabulary is on_create / on_update / on_close and every // one of them hands a hook script an ISSUE. A settings write changes the // workspace rather than a bead, so there is nothing to hand one — and the -// legacy config verbs this decorator inherits fire nothing either. A hook -// wrapper appearing here would therefore mean a layer landed on a path with -// nothing to fire, which is exactly what the read-role pins above catch. +// legacy config verbs this decorator inherits fire nothing either. func TestWorkspaceConfigKeepsTelemetryOutermost(t *testing.T) { t.Setenv("BD_OTEL_STDOUT", "true") instrumented, ok := telemetry.WrapStorage(&dolt.DoltStore{}).(*telemetry.InstrumentedStorage) @@ -243,14 +237,11 @@ func TestWorkspaceConfigKeepsTelemetryOutermost(t *testing.T) { } } -// TestVersionReconcilerKeepsTelemetryOutermost is the version-marker role's -// version of the pin, and the second place in this file where the read answer -// is given for a role that WRITES. -// -// The reason is the settings role's, plus one this role has on its own: it runs -// from PersistentPreRun on every startup, so a hook wrapper here would run a -// user's script before every command — including the ones that go on to fail on -// their own arguments — with no bead to hand it. +// TestVersionReconcilerKeepsTelemetryOutermost is the settings role's reason +// plus one this role has on its own: it runs from PersistentPreRun on every +// startup, so a hook wrapper here would run a user's script before every +// command — including the ones that go on to fail on their own arguments — +// with no bead to hand it. func TestVersionReconcilerKeepsTelemetryOutermost(t *testing.T) { t.Setenv("BD_OTEL_STDOUT", "true") instrumented, ok := telemetry.WrapStorage(&dolt.DoltStore{}).(*telemetry.InstrumentedStorage) @@ -267,16 +258,13 @@ func TestVersionReconcilerKeepsTelemetryOutermost(t *testing.T) { } } -// TestBootstrapperKeepsTelemetryOutermost is the identity-seeding role's -// version of the pin, and the third place in this file where the READ answer is -// given for a role that WRITES. -// -// The reason is neither the settings role's nor the version marker's. A -// bootstrap writes, and loudly — it is what turns a database into a workspace — -// but this decorator's hook vocabulary is issue-shaped and a bootstrap names no -// issue; and on a workspace this new, `bd init` has not installed .beads/hooks/ -// yet, so a hook fired here would run whatever the previous project in that -// directory left behind. See internal/storage/hook_bootstrapper.go. +// TestBootstrapperKeepsTelemetryOutermost has a reason that is neither the +// settings role's nor the version marker's. A bootstrap writes, and loudly — +// it is what turns a database into a workspace — but this decorator's hook +// vocabulary is issue-shaped and a bootstrap names no issue; and on a workspace +// this new, `bd init` has not installed .beads/hooks/ yet, so a hook fired here +// would run whatever the previous project in that directory left behind. See +// internal/storage/hook_bootstrapper.go. func TestBootstrapperKeepsTelemetryOutermost(t *testing.T) { t.Setenv("BD_OTEL_STDOUT", "true") instrumented, ok := telemetry.WrapStorage(&dolt.DoltStore{}).(*telemetry.InstrumentedStorage) @@ -356,10 +344,8 @@ func TestWorkspaceConfigExposesTypedUnsupportedError(t *testing.T) { } } -// TestStatsReporterKeepsTelemetryOutermost is the summary role's version of -// the same pin, and the READ answer again: reporting fires no completion hooks, -// so the hook decorator recurses and the outermost surface is the instrumented -// one. +// TestStatsReporterKeepsTelemetryOutermost is the READ answer again: reporting +// fires no completion hooks, so the hook decorator recurses. func TestStatsReporterKeepsTelemetryOutermost(t *testing.T) { t.Setenv("BD_OTEL_STDOUT", "true") instrumented, ok := telemetry.WrapStorage(&dolt.DoltStore{}).(*telemetry.InstrumentedStorage) @@ -387,9 +373,8 @@ func TestStatsReporterExposesTypedUnsupportedError(t *testing.T) { } } -// TestCycleDetectorKeepsTelemetryOutermost is the cycle role's version of -// TestCounterKeepsTelemetryOutermost, and the READ answer for the same reason: -// a cycle sweep fires no completion hooks, so the hook decorator adds no layer. +// TestCycleDetectorKeepsTelemetryOutermost is the READ answer again: a cycle +// sweep fires no completion hooks, so the hook decorator adds no layer. func TestCycleDetectorKeepsTelemetryOutermost(t *testing.T) { t.Setenv("BD_OTEL_STDOUT", "true") instrumented, ok := telemetry.WrapStorage(&dolt.DoltStore{}).(*telemetry.InstrumentedStorage) @@ -417,11 +402,8 @@ func TestCycleDetectorExposesTypedUnsupportedError(t *testing.T) { } } -// TestEdgeReaderKeepsTelemetryOutermost is the stored-edge role's version of -// TestIssueRelationsKeepsTelemetryOutermost, and it is the READ answer for the -// same reason: reading edges fires no completion hooks, so the hook decorator -// adds no layer and the outermost surface a caller gets is the instrumented -// one. +// TestEdgeReaderKeepsTelemetryOutermost is the READ answer again: reading edges +// fires no completion hooks, so the hook decorator adds no layer. func TestEdgeReaderKeepsTelemetryOutermost(t *testing.T) { t.Setenv("BD_OTEL_STDOUT", "true") instrumented, ok := telemetry.WrapStorage(&dolt.DoltStore{}).(*telemetry.InstrumentedStorage) @@ -449,10 +431,9 @@ func TestEdgeReaderExposesTypedUnsupportedError(t *testing.T) { } } -// TestBlockingAnnotatorKeepsTelemetryOutermost is the blocking-decoration -// role's version of the same pin, and the READ answer for the same reason: +// TestBlockingAnnotatorKeepsTelemetryOutermost is the READ answer again: // annotating a page fires no completion hooks, so the hook decorator adds no -// layer and the outermost surface a caller gets is the instrumented one. +// layer. func TestBlockingAnnotatorKeepsTelemetryOutermost(t *testing.T) { t.Setenv("BD_OTEL_STDOUT", "true") instrumented, ok := telemetry.WrapStorage(&dolt.DoltStore{}).(*telemetry.InstrumentedStorage) @@ -480,10 +461,8 @@ func TestBlockingAnnotatorExposesTypedUnsupportedError(t *testing.T) { } } -// TestTreeWalkerKeepsTelemetryOutermost is the dependency-tree role's version of -// TestEdgeReaderKeepsTelemetryOutermost, and the READ answer for the same -// reason: a tree walk fires no completion hooks, so the hook decorator adds no -// layer and the outermost surface a caller gets is the instrumented one. +// TestTreeWalkerKeepsTelemetryOutermost is the READ answer again: a tree walk +// fires no completion hooks, so the hook decorator adds no layer. func TestTreeWalkerKeepsTelemetryOutermost(t *testing.T) { t.Setenv("BD_OTEL_STDOUT", "true") instrumented, ok := telemetry.WrapStorage(&dolt.DoltStore{}).(*telemetry.InstrumentedStorage) @@ -522,10 +501,8 @@ func TestCounterExposesTypedUnsupportedError(t *testing.T) { } } -// TestReadyCounterKeepsTelemetryOutermost is the ready-count role's version of -// the same pin, and it is the READ answer again: sizing the ready set fires no -// completion hooks, so the hook decorator adds no layer and the outermost -// surface a caller gets is the instrumented one. +// TestReadyCounterKeepsTelemetryOutermost is the READ answer again: sizing the +// ready set fires no completion hooks, so the hook decorator adds no layer. func TestReadyCounterKeepsTelemetryOutermost(t *testing.T) { t.Setenv("BD_OTEL_STDOUT", "true") instrumented, ok := telemetry.WrapStorage(&dolt.DoltStore{}).(*telemetry.InstrumentedStorage) @@ -553,10 +530,8 @@ func TestReadyCounterExposesTypedUnsupportedError(t *testing.T) { } } -// TestQuerierKeepsTelemetryOutermost is the boolean-query role's version of the -// same pin, and it is the READ answer again: a query fires no completion hooks, -// so the hook decorator adds no layer and the outermost surface a caller gets -// is the instrumented one. +// TestQuerierKeepsTelemetryOutermost is the READ answer again: a query fires no +// completion hooks, so the hook decorator adds no layer. func TestQuerierKeepsTelemetryOutermost(t *testing.T) { t.Setenv("BD_OTEL_STDOUT", "true") instrumented, ok := telemetry.WrapStorage(&dolt.DoltStore{}).(*telemetry.InstrumentedStorage) @@ -584,12 +559,11 @@ func TestQuerierExposesTypedUnsupportedError(t *testing.T) { } } -// TestSweeperKeepsTelemetryOutermost is the bulk-clearance role's version of -// the same pin, and it is the ONE WRITE role that answers the way the reads -// do: there is no on_delete hook to fire (internal/storage/hook_sweeper.go), so -// the hook decorator adds no layer and the outermost surface a caller gets is -// the instrumented one. Pinning it here is what keeps that a decision rather -// than a wrapper someone forgot to write. +// TestSweeperKeepsTelemetryOutermost is a WRITE role that answers the way the +// reads do: there is no on_delete hook to fire +// (internal/storage/hook_sweeper.go), so the hook decorator adds no layer. +// Pinning it here is what keeps that a decision rather than a wrapper someone +// forgot to write. func TestSweeperKeepsTelemetryOutermost(t *testing.T) { t.Setenv("BD_OTEL_STDOUT", "true") instrumented, ok := telemetry.WrapStorage(&dolt.DoltStore{}).(*telemetry.InstrumentedStorage) @@ -617,11 +591,9 @@ func TestSweeperExposesTypedUnsupportedError(t *testing.T) { } } -// TestDeleterKeepsTelemetryOutermost is the named-row erasure role's version of -// the same pin, and the SECOND write role to answer the way the reads do: there -// is no on_delete hook to fire (internal/storage/hook_deleter.go), so the hook -// decorator adds no layer and the outermost surface a caller gets is the -// instrumented one. +// TestDeleterKeepsTelemetryOutermost is the second write role to answer the way +// the reads do: there is no on_delete hook to fire +// (internal/storage/hook_deleter.go), so the hook decorator adds no layer. func TestDeleterKeepsTelemetryOutermost(t *testing.T) { t.Setenv("BD_OTEL_STDOUT", "true") instrumented, ok := telemetry.WrapStorage(&dolt.DoltStore{}).(*telemetry.InstrumentedStorage)