diff --git a/CHANGELOG.md b/CHANGELOG.md index 241e92c95..abb76e98b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- `GET /v0/beads/dependencies/blocking` accepts `is_blocked`, behind the new + `dependencies.blocking.isBlocked` capability token (additive; no + wire_revision bump), and answers each item's stored, transitive + `is_blocked` flag, the column `bd ready` filters on; an item whose id names + no row carries none. `issueops.BlockingRequest` gains `IncludeIsBlocked` on + every BlockingAnnotator implementation, and `issueops.BlockedFlags` is the + batched read over it. The HTTP backend's `IsBlockedBatch` now serves + through it; against a server that does not advertise the token it still + refuses before dialing, now with a typed capability error naming the + token. An unsatisfied `external:` blocker sets the flag on every route, + just as it keeps the issue out of `bd ready`. - `bd promote` works over a connected HTTP workspace (S21b). Its one library entry, `issueops.Promote(ctx, PromoteRoles{Reader, Lifecycle, Commenter}, PromoteRequest)`, reads the row, refuses one that is not a wisp diff --git a/backend/conformance/blocking_annotator_contract.go b/backend/conformance/blocking_annotator_contract.go index 523b05037..e17b49fb9 100644 --- a/backend/conformance/blocking_annotator_contract.go +++ b/backend/conformance/blocking_annotator_contract.go @@ -546,3 +546,65 @@ func assertParent(t *testing.T, result publicops.BlockingResult, id, want string t.Errorf("entry %s parent = %q, want %q", id, got, want) } } + +// RunBlockingAnnotatorReportsTheTransitiveBlockedFlag pins +// BlockingRequest.IncludeIsBlocked and IssueBlocking.IsBlocked: asked, each id +// with a row carries its STORED TRANSITIVE is_blocked flag — a child of a +// blocked parent is blocked with no blocking edge of its own, which BlockedBy +// alone would read as free — and an id naming no row carries none. Unasked, +// no item carries a flag. This is the read issueops.BlockedFlags (storage's +// IsBlockedBatch on a role-served backend) is built on. +func RunBlockingAnnotatorReportsTheTransitiveBlockedFlag(t *testing.T, ctx context.Context, fixture BlockingAnnotatorFixture) { + t.Helper() + blocker := fixture.IssuePrefix + "-flag-blocker" + blocked := fixture.IssuePrefix + "-flag-blocked" + child := fixture.IssuePrefix + "-flag-child" + free := fixture.IssuePrefix + "-flag-free" + ghost := fixture.IssuePrefix + "-flag-ghost" + seedBlockingIssues(t, ctx, fixture, blocker, blocked, child, free) + seedBlockingEdge(t, ctx, fixture, child, blocked, types.DepParentChild) + seedBlockingEdge(t, ctx, fixture, blocked, blocker, types.DepBlocks) + + ids := []string{blocked, child, free, ghost} + unasked := annotateBlocking(t, ctx, fixture, publicops.BlockingRequest{IDs: ids}) + for _, item := range unasked.Items { + if item.IsBlocked != nil { + t.Errorf("unasked: %s carries IsBlocked=%v, want no flag", item.ID, *item.IsBlocked) + } + } + + asked := annotateBlocking(t, ctx, fixture, publicops.BlockingRequest{IDs: ids, IncludeIsBlocked: true}) + want := map[string]*bool{blocked: new(true), child: new(true), free: new(false), ghost: nil} + if len(asked.Items) != len(ids) { + t.Fatalf("asked: %d items, want %d", len(asked.Items), len(ids)) + } + for _, item := range asked.Items { + w, ok := want[item.ID] + if !ok { + t.Errorf("asked: unexpected item %s", item.ID) + continue + } + switch { + case w == nil && item.IsBlocked != nil: + t.Errorf("asked: %s (no row) IsBlocked=%v, want no flag", item.ID, *item.IsBlocked) + case w != nil && item.IsBlocked == nil: + t.Errorf("asked: %s IsBlocked absent, want %v", item.ID, *w) + case w != nil && *item.IsBlocked != *w: + t.Errorf("asked: %s IsBlocked=%v, want %v", item.ID, *item.IsBlocked, *w) + } + } + + flags, err := publicops.BlockedFlags(ctx, fixture.Annotator, append(ids, blocked, "")) + if err != nil { + t.Fatalf("BlockedFlags: %v", err) + } + wantFlags := map[string]bool{blocked: true, child: true, free: false} + if len(flags) != len(wantFlags) { + t.Errorf("BlockedFlags = %v, want %v (no entry for the ghost or the blank id)", flags, wantFlags) + } + for id, w := range wantFlags { + if got, ok := flags[id]; !ok || got != w { + t.Errorf("BlockedFlags[%s] = %v (present %v), want %v", id, got, ok, w) + } + } +} diff --git a/backend/conformance/role_bundle_cases.go b/backend/conformance/role_bundle_cases.go index caaa5dc7a..ff52c67e4 100644 --- a/backend/conformance/role_bundle_cases.go +++ b/backend/conformance/role_bundle_cases.go @@ -127,6 +127,7 @@ var roleContractCases = []roleContract{ RunBlockingAnnotatorRefusesAnEmptyID, RunBlockingAnnotatorLeavesTheRequestAlone, RunBlockingAnnotatorWritesNothing, + RunBlockingAnnotatorReportsTheTransitiveBlockedFlag, ), // One contract file covers both halves of workspace identity: the eight diff --git a/internal/httpapi/apigen/types.gen.go b/internal/httpapi/apigen/types.gen.go index f0f16b608..8cdf6e633 100644 --- a/internal/httpapi/apigen/types.gen.go +++ b/internal/httpapi/apigen/types.gen.go @@ -1101,7 +1101,7 @@ type ContextResponse struct { // OPTIONAL, and absent means only that this server does not disclose its filesystem layout — never that it has no workspace. A client MUST NOT require it, MUST NOT treat absence as an error, and has no use for the value beyond display: it is a path on the SERVER's filesystem, which the client cannot open. Identify the workspace by `project_id` and `database`, which are required. BeadsDir *string `json:"beads_dir,omitempty"` - // Capabilities The tokens this server advertises: the OPERATIONS it implements, derived from its route table, and the server-wide BEHAVIORS it enforces. v0's operation vocabulary is `ready.list`, `ready.count`, `issues.list`, `issues.query`, `issues.count`, `issues.get`, `issues.related`, `issues.create`, `issues.addComment`, `issues.batchClose`, `issues.claim`, `issues.claimNext`, `issues.release`, `issues.close`, `issues.reopen`, `issues.update`, `issues.sweep`, `issues.delete`, `issues.batchGet`, `issues.reclaim`, `issues.batchCreate`, `issues.batchApply`, `stats.get`, `config.list`, `config.get`, `config.set`, `config.unset`, `dependencies.cycles`, `dependencies.list`, `dependencies.count`, `dependencies.blocking`, `dependencies.tree`, `dependencies.add`, `dependencies.remove`, `memories.list`, `memories.get`, `memories.remember`, `memories.forget`, `events.list`, `events.watch`, `issues.casMetadata`, `issues.advanceMolecule`; the behavior tokens are `project.enforce`, which announces that a `Bd-Project-Id` stamp for the wrong workspace is refused here rather than silently ignored, `issues.batchApplyLarge`, which announces that `POST /v0/beads/issues:batchApply` accepts the RAISED envelope — up to 1000 items (`ApplyBatchRequest.items.maxItems`), a 16 MiB body, and (for a request over 100 items) a run budget that EXTENDS to an operator-configured ceiling (`bd serve --large-apply-ceiling`, 5 minutes by default) — rather than the original 100-item, 4 MiB bound. The ceiling is a flat whole-run budget, not a value scaled by item count: a 101-item request and a 1000-item request both get the same extended budget. A request at or under 100 items is unaffected either way and keeps the server's ordinary deadline exactly as before. A client that checks for this token before sending a plan over 100 items learns whether THIS server accepts it without paying for a round trip an older server would refuse anyway, and `issues.list.sort`, which announces that `GET /v0/beads/issues` accepts the `sort` query parameter (two closed, pageable total orders — see that parameter) rather than silently answering `unknown_parameter`, and `issues.count.scope`, which announces that `GET /v0/beads/issues:count` accepts `parent`, `no_parent`, `exclude_type`, and `exclude_status` (see those parameters) rather than silently answering `unknown_parameter` for all four, `issues.sweep.wispsPlane`, which announces that `POST /v0/beads/issues:sweep` accepts the `wisps-plane` value of `tier` rather than silently answering `invalid_value`, `issues.sweep.liveDependents`, which announces that the same operation accepts `protect_live_dependents` and answers `skipped.live_dependent` rather than silently answering `unknown_parameter`, `issues.sweep.limit`, which announces that it accepts `limit` and answers `remaining` rather than silently answering `unknown_parameter`, `issues.batchApply.depAddLineage`, which announces that a `dep_add` item on `POST /v0/beads/issues:batchApply` accepts `has_spawner` and `thread_id` (see `ApplyDepAddItem`) rather than a `400` naming the member unknown, and `issues.update.allowTemplate`, which announces that `PATCH /v0/beads/issues/{id}` accepts `allow_template` (see `UpdateIssueRequest`) rather than a `400` naming the member unknown, and `issues.update.persistence`, which announces that `PATCH /v0/beads/issues/{id}` accepts a `persistence` member in its `patch` (see `IssuePatchBody`), the plane move behind `bd promote`, rather than a `400` naming the member unknown, and `issues.create.defaultPriority`, which announces that a create (`POST /v0/beads/issues`, `issues:batchCreate` and `issues:batchApply` create items) with no `priority` member stores the default P2 rather than P0, and `issues.close.autoCloseMolecule`, which announces that `POST /v0/beads/issues/{id}:close` and `POST /v0/beads/issues:batchClose` accept `auto_close_molecule` and answer `auto_closed_molecule` and `molecule_auto_close_refusal` rather than a `400` naming the member unknown, `issues.list.search`, which announces that `GET /v0/beads/issues` accepts `q`, `bd search`'s free text (see that parameter), rather than silently answering `unknown_parameter`, and `issues.list.noAssignee`, `issues.list.title` and `issues.list.ids`, which announce that `GET /v0/beads/issues` accepts `no_assignee`, `title` and the repeatable `id` respectively (`bd list --no-assignee`, `--title` and `--id`; see those parameters) rather than answering `unknown_parameter`. One behavior token is CONDITIONAL rather than build-level: `policy.external_dependencies` announces that this server's ready, claim, claim-next, close, blocking and dependency-tree operations already apply bd's external-dependency policy (an issue blocked by an unsatisfied `external::` dependency is neither ready, claimable nor closable without force). A server advertises it only when it enforces that policy; a client that sees it must not apply the policy again, and a client that does not see it applies the policy itself. The list grows additively, and an operation never appears here unless it is fully implemented. This is how a client checks for an operation or a behavior — never the version string. + // Capabilities The tokens this server advertises: the OPERATIONS it implements, derived from its route table, and the server-wide BEHAVIORS it enforces. v0's operation vocabulary is `ready.list`, `ready.count`, `issues.list`, `issues.query`, `issues.count`, `issues.get`, `issues.related`, `issues.create`, `issues.addComment`, `issues.batchClose`, `issues.claim`, `issues.claimNext`, `issues.release`, `issues.close`, `issues.reopen`, `issues.update`, `issues.sweep`, `issues.delete`, `issues.batchGet`, `issues.reclaim`, `issues.batchCreate`, `issues.batchApply`, `stats.get`, `config.list`, `config.get`, `config.set`, `config.unset`, `dependencies.cycles`, `dependencies.list`, `dependencies.count`, `dependencies.blocking`, `dependencies.tree`, `dependencies.add`, `dependencies.remove`, `memories.list`, `memories.get`, `memories.remember`, `memories.forget`, `events.list`, `events.watch`, `issues.casMetadata`, `issues.advanceMolecule`; the behavior tokens are `project.enforce`, which announces that a `Bd-Project-Id` stamp for the wrong workspace is refused here rather than silently ignored, `issues.batchApplyLarge`, which announces that `POST /v0/beads/issues:batchApply` accepts the RAISED envelope — up to 1000 items (`ApplyBatchRequest.items.maxItems`), a 16 MiB body, and (for a request over 100 items) a run budget that EXTENDS to an operator-configured ceiling (`bd serve --large-apply-ceiling`, 5 minutes by default) — rather than the original 100-item, 4 MiB bound. The ceiling is a flat whole-run budget, not a value scaled by item count: a 101-item request and a 1000-item request both get the same extended budget. A request at or under 100 items is unaffected either way and keeps the server's ordinary deadline exactly as before. A client that checks for this token before sending a plan over 100 items learns whether THIS server accepts it without paying for a round trip an older server would refuse anyway, and `issues.list.sort`, which announces that `GET /v0/beads/issues` accepts the `sort` query parameter (two closed, pageable total orders — see that parameter) rather than silently answering `unknown_parameter`, and `issues.count.scope`, which announces that `GET /v0/beads/issues:count` accepts `parent`, `no_parent`, `exclude_type`, and `exclude_status` (see those parameters) rather than silently answering `unknown_parameter` for all four, `issues.sweep.wispsPlane`, which announces that `POST /v0/beads/issues:sweep` accepts the `wisps-plane` value of `tier` rather than silently answering `invalid_value`, `issues.sweep.liveDependents`, which announces that the same operation accepts `protect_live_dependents` and answers `skipped.live_dependent` rather than silently answering `unknown_parameter`, `issues.sweep.limit`, which announces that it accepts `limit` and answers `remaining` rather than silently answering `unknown_parameter`, `issues.batchApply.depAddLineage`, which announces that a `dep_add` item on `POST /v0/beads/issues:batchApply` accepts `has_spawner` and `thread_id` (see `ApplyDepAddItem`) rather than a `400` naming the member unknown, and `issues.update.allowTemplate`, which announces that `PATCH /v0/beads/issues/{id}` accepts `allow_template` (see `UpdateIssueRequest`) rather than a `400` naming the member unknown, and `issues.update.persistence`, which announces that `PATCH /v0/beads/issues/{id}` accepts a `persistence` member in its `patch` (see `IssuePatchBody`), the plane move behind `bd promote`, rather than a `400` naming the member unknown, and `issues.create.defaultPriority`, which announces that a create (`POST /v0/beads/issues`, `issues:batchCreate` and `issues:batchApply` create items) with no `priority` member stores the default P2 rather than P0, and `issues.close.autoCloseMolecule`, which announces that `POST /v0/beads/issues/{id}:close` and `POST /v0/beads/issues:batchClose` accept `auto_close_molecule` and answer `auto_closed_molecule` and `molecule_auto_close_refusal` rather than a `400` naming the member unknown, `issues.list.search`, which announces that `GET /v0/beads/issues` accepts `q`, `bd search`'s free text (see that parameter), rather than silently answering `unknown_parameter`, `issues.list.noAssignee`, `issues.list.title` and `issues.list.ids`, which announce that `GET /v0/beads/issues` accepts `no_assignee`, `title` and the repeatable `id` respectively (`bd list --no-assignee`, `--title` and `--id`; see those parameters) rather than answering `unknown_parameter`, and `dependencies.blocking.isBlocked`, which announces that `GET /v0/beads/dependencies/blocking` accepts `is_blocked` and answers each item's stored, transitive `is_blocked` flag (see that parameter) rather than silently answering `unknown_parameter`. One behavior token is CONDITIONAL rather than build-level: `policy.external_dependencies` announces that this server's ready, claim, claim-next, close, blocking and dependency-tree operations already apply bd's external-dependency policy (an issue blocked by an unsatisfied `external::` dependency is neither ready, claimable nor closable without force). A server advertises it only when it enforces that policy; a client that sees it must not apply the policy again, and a client that does not see it applies the policy itself. The list grows additively, and an operation never appears here unless it is fully implemented. This is how a client checks for an operation or a behavior — never the version string. // // THIS LIST IS BUILD-LEVEL, NOT WORKSPACE-LEVEL, apart from the conditional `policy.external_dependencies` above, which depends on how this server composed its roles rather than on the build. It says which operations this binary serves, and for every entry but two that is the whole answer. `events.list` and `events.watch` are the exceptions: the durable events journal is a per-workspace setting that is OFF by default, so a server that advertises them may still refuse every request to both with 409 `events_journal_disabled` — correctly, because the operations exist and the workspace has no journal. A consumer of either MUST treat the capability as "this server speaks it" and the 409 as "not on this workspace", and must not read the capability as a promise that records will arrive. Capabilities []string `json:"capabilities"` @@ -2261,6 +2261,9 @@ type ListBlockingAnnotationsParams struct { // // Repeats collapse: an id named twice is one entry, at the position of its first mention. IssueId []string `form:"issue_id" json:"issue_id"` + + // IsBlocked `true` adds each item's `is_blocked`: the issue's stored, TRANSITIVE readiness flag — the column the ready set filters on, which a child inherits from a blocked parent and which `waits-for` and `conditional-blocks` gates set — rather than the two-edge-type, direct `blocked_by` summary. It is the batched readiness projection a client cache needs to answer readiness with the server's own predicate. An id that names no row in either plane gets no `is_blocked` member. Absent or `false` answers exactly as before. Behind the `dependencies.blocking.isBlocked` capability token; a server that predates it answers `400` with `param: "is_blocked"` and `reason: "unknown_parameter"`. + IsBlocked *bool `form:"is_blocked,omitempty" json:"is_blocked,omitempty"` } // GetDependencyTreeParams defines parameters for GetDependencyTree. diff --git a/internal/httpapi/blocking.go b/internal/httpapi/blocking.go index 62ceb0c03..03608f528 100644 --- a/internal/httpapi/blocking.go +++ b/internal/httpapi/blocking.go @@ -27,6 +27,9 @@ func (s *Server) handleBlockingAnnotations(w http.ResponseWriter, r *http.Reques q := newQuery(r.URL.Query()) ids := q.list("issue_id") + // is_blocked rides CapDependenciesBlockingIsBlocked: the role's + // IncludeIsBlocked, each item's stored transitive flag. + includeIsBlocked := q.boolean("is_blocked") if !s.acceptQuery(w, r, q) { return } @@ -51,7 +54,7 @@ func (s *Server) handleBlockingAnnotations(w http.ResponseWriter, r *http.Reques s.failErr(w, r, err) return } - result, err := annotator.AnnotateBlocking(r.Context(), issueops.BlockingRequest{IDs: ids}) + result, err := annotator.AnnotateBlocking(r.Context(), issueops.BlockingRequest{IDs: ids, IncludeIsBlocked: includeIsBlocked}) if err != nil { s.failBlockingErr(w, r, err) return diff --git a/internal/httpapi/blocking_test.go b/internal/httpapi/blocking_test.go index 2dfd38822..a576d41d7 100644 --- a/internal/httpapi/blocking_test.go +++ b/internal/httpapi/blocking_test.go @@ -175,3 +175,47 @@ func TestABlockingRoleRefusalIsTheDocumentedBadRequest(t *testing.T) { t.Errorf("status = %d for an opaque role failure, want 500: %s", resp.StatusCode, readAll(t, resp)) } } + +// TestBlockingAnnotationsCarryTheTransitiveFlagWhenAsked pins the +// dependencies.blocking.isBlocked parameter: `is_blocked=true` reaches the +// role as IncludeIsBlocked, the role's flag is shipped as `is_blocked`, an +// item without one omits the member, and a request without the parameter +// asks for nothing. +func TestBlockingAnnotationsCarryTheTransitiveFlagWhenAsked(t *testing.T) { + blocked := true + annotator := &roleBlockingAnnotator{result: issueops.BlockingResult{Items: []issueops.IssueBlocking{ + {ID: "bd-1", BlockedBy: []string{}, Blocks: []string{}, IsBlocked: &blocked}, + {ID: "bd-ghost", BlockedBy: []string{}, Blocks: []string{}}, + }}} + ts := newBlockingServer(t, annotator) + + body := decodeBody(t, ts.get(t, "/v0/beads/dependencies/blocking?issue_id=bd-1&issue_id=bd-ghost&is_blocked=true")) + reads := annotator.blockingRequests() + if len(reads) != 1 || !reads[0].IncludeIsBlocked { + t.Fatalf("role saw %+v, want one request with IncludeIsBlocked", reads) + } + items, _ := body["items"].([]any) + if len(items) != 2 { + t.Fatalf("items = %v", body["items"]) + } + if first, _ := items[0].(map[string]any); first["is_blocked"] != true { + t.Errorf("items[0].is_blocked = %v, want true", first["is_blocked"]) + } + if second, _ := items[1].(map[string]any); second["is_blocked"] != nil { + t.Errorf("items[1] carries is_blocked %v; an item with no flag omits it", second["is_blocked"]) + } + + ts.get(t, "/v0/beads/dependencies/blocking?issue_id=bd-1") + if reads := annotator.blockingRequests(); len(reads) != 2 || reads[1].IncludeIsBlocked { + t.Errorf("a request without is_blocked asked for the flag: %+v", reads) + } +} + +// TestBlockedFlagsChunkIsTheServedAnchorBound holds issueops.BlockedFlagsChunk +// to this operation's issue_id bound, so the library entry never asks a +// question the served operation refuses. +func TestBlockedFlagsChunkIsTheServedAnchorBound(t *testing.T) { + if issueops.BlockedFlagsChunk != maxDependencyAnchors { + t.Errorf("issueops.BlockedFlagsChunk = %d, maxDependencyAnchors = %d; they must be equal", issueops.BlockedFlagsChunk, maxDependencyAnchors) + } +} diff --git a/internal/httpapi/routes.go b/internal/httpapi/routes.go index a724540e1..b70f2e6f1 100644 --- a/internal/httpapi/routes.go +++ b/internal/httpapi/routes.go @@ -166,6 +166,15 @@ const ( // (E9-S2), adopted unchanged so the two servers publish one `id`. const CapListIDs = "issues.list.ids" +// CapDependenciesBlockingIsBlocked is the behavior capability that advertises +// GET /v0/beads/dependencies/blocking's `is_blocked` parameter (blocking.go): +// issueops.BlockingRequest.IncludeIsBlocked, which adds each item's stored, +// transitive is_blocked flag to the decoration. It is the batched readiness +// projection behind storage's IsBlockedBatch on a role-served backend +// (issueops.BlockedFlags). The client refuses the read locally, naming this +// token, against a server that does not advertise it. +const CapDependenciesBlockingIsBlocked = "dependencies.blocking.isBlocked" + // CapIssuesSweepWispsPlane is the behavior capability that advertises the // `wisps-plane` value of SweepRequest.tier (sweep.go, spec SweepRequest.tier): // a third, wider tier that clears the whole wisps table plus any durable bead @@ -1044,7 +1053,7 @@ var behaviorCapabilities = []string{ CapIssuesSweepWispsPlane, CapIssuesSweepLiveDependents, CapIssuesSweepLimit, CapBatchApplyDepAddLineage, CapIssuesUpdateAllowTemplate, CapIssuesCreateDefaultPriority, CapIssuesCloseAutoCloseMolecule, CapIssuesListSearch, - CapIssuesListNoAssignee, CapIssuesListTitle, CapListIDs, CapIssuesUpdatePersistence, + CapIssuesListNoAssignee, CapIssuesListTitle, CapListIDs, CapIssuesUpdatePersistence, CapDependenciesBlockingIsBlocked, } // Capabilities lists what this build advertises in ContextResponse.capabilities: diff --git a/internal/httpapi/server_test.go b/internal/httpapi/server_test.go index 43e983b2e..97899d2d1 100644 --- a/internal/httpapi/server_test.go +++ b/internal/httpapi/server_test.go @@ -639,7 +639,7 @@ func TestCapabilitiesAdvertiseEveryImplementedOperation(t *testing.T) { "issues.sweep.wispsPlane", "issues.sweep.liveDependents", "issues.sweep.limit", "issues.batchApply.depAddLineage", "issues.update.allowTemplate", "issues.create.defaultPriority", "issues.close.autoCloseMolecule", "issues.list.search", - "issues.list.noAssignee", "issues.list.title", "issues.list.ids", "issues.update.persistence") + "issues.list.noAssignee", "issues.list.title", "issues.list.ids", "issues.update.persistence", "dependencies.blocking.isBlocked") slices.Sort(want) if !slices.Equal(got, want) { t.Errorf("capabilities = %v, want %v", got, want) diff --git a/internal/httpapi/spec/openapi.v0.yaml b/internal/httpapi/spec/openapi.v0.yaml index 3556c5e99..e937cf752 100644 --- a/internal/httpapi/spec/openapi.v0.yaml +++ b/internal/httpapi/spec/openapi.v0.yaml @@ -5645,6 +5645,25 @@ paths: maxItems: 100 items: type: string + - name: is_blocked + in: query + description: >- + `true` adds each item's `is_blocked`: the issue's stored, + TRANSITIVE readiness flag — the column the ready set filters on, + which a child inherits from a blocked parent and which + `waits-for` and `conditional-blocks` gates set — rather than the + two-edge-type, direct `blocked_by` summary. It is the batched + readiness projection a client cache needs to answer readiness + with the server's own predicate. An id that names no row in + either plane gets no `is_blocked` member. Absent or `false` + answers exactly as before. Behind the + `dependencies.blocking.isBlocked` capability token; a server + that predates it answers `400` with `param: "is_blocked"` and + `reason: "unknown_parameter"`. + required: false + schema: + type: boolean + default: false security: - bearerToken: [] responses: @@ -8119,6 +8138,13 @@ components: carries several `parent-child` edges, which one appears here is not specified. A client that needs every structural edge reads them from `GET /v0/beads/dependencies`. + is_blocked: + type: boolean + description: >- + The issue's stored, transitive is_blocked flag — present only when + the request carried `is_blocked=true` (capability + `dependencies.blocking.isBlocked`) and the id names a row. Its + absence never means "not blocked". # --------------------------------------------------------------------- # Envelope schemas. Almost all of these have no canonical Go type behind @@ -8299,13 +8325,16 @@ components: member unknown, `issues.list.search`, which announces that `GET /v0/beads/issues` accepts `q`, `bd search`'s free text (see that parameter), rather than silently answering - `unknown_parameter`, and `issues.list.noAssignee`, + `unknown_parameter`, `issues.list.noAssignee`, `issues.list.title` and `issues.list.ids`, which announce that `GET /v0/beads/issues` accepts `no_assignee`, `title` and the repeatable `id` respectively (`bd list --no-assignee`, `--title` and `--id`; see those parameters) rather than answering - `unknown_parameter`. One - behavior token is + `unknown_parameter`, and `dependencies.blocking.isBlocked`, which + announces that `GET /v0/beads/dependencies/blocking` accepts + `is_blocked` and answers each item's stored, transitive + `is_blocked` flag (see that parameter) rather than silently + answering `unknown_parameter`. One behavior token is CONDITIONAL rather than build-level: `policy.external_dependencies` announces that this server's ready, claim, claim-next, close, blocking and dependency-tree operations already apply bd's diff --git a/internal/httpapi/wireshape/testdata/golden.json b/internal/httpapi/wireshape/testdata/golden.json index b136b13af..c2d2882d3 100644 --- a/internal/httpapi/wireshape/testdata/golden.json +++ b/internal/httpapi/wireshape/testdata/golden.json @@ -2345,6 +2345,12 @@ "type": "string", "required": true }, + { + "schema": "IssueBlocking", + "member": "is_blocked", + "type": "boolean", + "required": false + }, { "schema": "IssueBlocking", "member": "parent", @@ -5667,6 +5673,15 @@ "explode": true, "default": "false" }, + { + "schema": "param:listBlockingAnnotations", + "member": "query:is_blocked", + "type": "boolean", + "required": false, + "style": "form", + "explode": true, + "default": "false" + }, { "schema": "param:listBlockingAnnotations", "member": "query:issue_id", diff --git a/internal/httpclient/BUILD.bazel b/internal/httpclient/BUILD.bazel index 68803269c..95ee71185 100644 --- a/internal/httpclient/BUILD.bazel +++ b/internal/httpclient/BUILD.bazel @@ -10,6 +10,7 @@ go_library( "batchcloser.go", "batchcreator.go", "batchgetter.go", + "blocked_querier.go", "blocked_recomputer.go", "bridge.go", "ca.go", @@ -96,6 +97,7 @@ go_test( srcs = [ "backend_credential_test.go", "batchapplier_test.go", + "blocked_querier_test.go", "brief_test.go", "bulk_roles_test.go", "ca_permissions_unix_test.go", @@ -194,6 +196,7 @@ go_test( embed = [":httpclient"], shard_count = 2, deps = [ + "//:beads", "//backend/conformance", "//internal/eventsjournal", "//internal/hooks", diff --git a/internal/httpclient/blocked_querier.go b/internal/httpclient/blocked_querier.go new file mode 100644 index 000000000..dea6fecda --- /dev/null +++ b/internal/httpclient/blocked_querier.go @@ -0,0 +1,22 @@ +package httpclient + +import ( + "context" + + "github.com/steveyegge/beads/issueops" +) + +// IsBlockedBatch serves beads.BlockedQuerier's batched read — the stored, +// transitive is_blocked flag per id, an id naming no row absent — through the +// one library entry, issueops.BlockedFlags, over this store's +// BlockingAnnotator (listBlockingAnnotations with `is_blocked`, at most +// issueops.BlockedFlagsChunk ids per request). +// +// Against a server that does not advertise dependencies.blocking.isBlocked +// the annotator refuses before dialing with *ErrUnsupported naming the token, +// so a caller's errors.As on the typed refusal (gc's ready projection latches +// its degrade on it) sees the same sentinel the generated stub answered with +// before, now with the capability that would lift it. +func (s *Store) IsBlockedBatch(ctx context.Context, ids []string) (map[string]bool, error) { + return issueops.BlockedFlags(ctx, httpBlockingAnnotator{store: s}, ids) +} diff --git a/internal/httpclient/blocked_querier_test.go b/internal/httpclient/blocked_querier_test.go new file mode 100644 index 000000000..b37391375 --- /dev/null +++ b/internal/httpclient/blocked_querier_test.go @@ -0,0 +1,115 @@ +package httpclient + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "slices" + "testing" + + beads "github.com/steveyegge/beads" + "github.com/steveyegge/beads/internal/httpapi/apigen" + "github.com/steveyegge/beads/internal/httpclient/wire" + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/issueops" +) + +// TestIsBlockedBatchRidesTheBlockingAnnotatorBehindItsCapability pins the +// client half of the http IsBlockedBatch: beads.AsBlockedQuerier finds it, it +// asks listBlockingAnnotations with is_blocked=true, chunked at +// issueops.BlockedFlagsChunk ids, and answers id -> flag with an id the server +// gave no flag (no row) absent. +func TestIsBlockedBatchRidesTheBlockingAnnotatorBehindItsCapability(t *testing.T) { + served := &apigen.ContextResponse{Capabilities: []string{"dependencies.blocking", wire.CapBlockingIsBlocked}} + w := &countingWire{} + w.preflight = func(context.Context, string) error { return nil } + w.do = func(_ context.Context, req wire.Request, out any) error { + w.dialed = append(w.dialed, req) + items := make([]map[string]any, 0) + for _, id := range req.Query["issue_id"] { + item := map[string]any{"id": id, "blocked_by": []string{}, "blocks": []string{}} + switch id { + case "x-ghost": + case "x-7", "x-150": + item["is_blocked"] = true + default: + item["is_blocked"] = false + } + items = append(items, item) + } + raw, _ := json.Marshal(map[string]any{"items": items}) + return json.Unmarshal(raw, out) + } + var store beads.Storage = New(testTarget(t), w, served) + querier, ok := beads.AsBlockedQuerier(store) + if !ok { + t.Fatal("AsBlockedQuerier(http store) = false") + } + ids := []string{"x-ghost"} + for i := range 160 { + ids = append(ids, fmt.Sprintf("x-%d", i)) + } + ids = append(ids, "x-7") // a repeat is asked once + flags, err := querier.IsBlockedBatch(t.Context(), ids) + if err != nil { + t.Fatalf("IsBlockedBatch: %v", err) + } + if len(w.dialed) != 2 { + t.Fatalf("dialed %d requests, want 2 (161 distinct ids at %d per request)", len(w.dialed), issueops.BlockedFlagsChunk) + } + for _, req := range w.dialed { + if req.Op != wire.OpListBlockingAnnotations || req.Path != wire.PathDependenciesBlocking { + t.Errorf("dialed %s %s, want listBlockingAnnotations", req.Op, req.Path) + } + if got := req.Query["is_blocked"]; !slices.Equal(got, []string{"true"}) { + t.Errorf("query[is_blocked] = %v, want [true]", got) + } + if n := len(req.Query["issue_id"]); n > issueops.BlockedFlagsChunk { + t.Errorf("a request named %d ids, over the %d bound", n, issueops.BlockedFlagsChunk) + } + } + if len(flags) != 160 { + t.Errorf("len(flags) = %d, want 160 (the ghost absent)", len(flags)) + } + if _, ok := flags["x-ghost"]; ok { + t.Error("an id the server gave no flag is present; absent means no row") + } + if !flags["x-7"] || !flags["x-150"] || flags["x-8"] { + t.Errorf("flags x-7=%v x-150=%v x-8=%v, want true true false", flags["x-7"], flags["x-150"], flags["x-8"]) + } +} + +// TestIsBlockedBatchRefusesBeforeDialingWithoutTheCapability is the skew side: +// against a server that does not advertise dependencies.blocking.isBlocked (the +// deployed 1.3.0 serve, for one), the read refuses before the dial with the +// typed refusal gc's ready projection latches its degrade on, now naming the +// capability that would lift it. Sending it would cost a 400 +// unknown_parameter; dropping is_blocked would pass "no flag" off as "free". +func TestIsBlockedBatchRefusesBeforeDialingWithoutTheCapability(t *testing.T) { + masked := &apigen.ContextResponse{Capabilities: []string{"dependencies.blocking"}} + w := newCountingWire(`{"items":[]}`) + _, err := New(testTarget(t), w, masked).IsBlockedBatch(t.Context(), []string{"x-1"}) + var unsup *storage.ErrUnsupported + if !errors.As(err, &unsup) { + t.Fatalf("IsBlockedBatch error = %v, want *storage.ErrUnsupported", err) + } + if unsup.Capability != wire.CapBlockingIsBlocked { + t.Errorf("refusal capability = %q, want %s", unsup.Capability, wire.CapBlockingIsBlocked) + } + if len(w.dialed) != 0 { + t.Errorf("dialed %d times, want 0", len(w.dialed)) + } + + // The plain decoration is unaffected by the missing token. + annotator, err := New(testTarget(t), w, masked).BlockingAnnotator() + if err != nil { + t.Fatal(err) + } + if _, err := annotator.AnnotateBlocking(t.Context(), issueops.BlockingRequest{IDs: []string{"x-1"}}); err != nil { + t.Fatalf("AnnotateBlocking without the flag: %v", err) + } + if w.query(t).Has("is_blocked") { + t.Error("a request without IncludeIsBlocked sent is_blocked") + } +} diff --git a/internal/httpclient/completeness_test.go b/internal/httpclient/completeness_test.go index a0c18d544..d8b06ba89 100644 --- a/internal/httpclient/completeness_test.go +++ b/internal/httpclient/completeness_test.go @@ -260,7 +260,6 @@ var legitimatelyUnsupported = map[string]string{ "GetDependentRecordsForIssues": "raw read: no multi-id dependents operation", "GetDependents": "raw read: no dependents operation off getIssue", "IsBlocked": "raw read: role BlockingAnnotator serves this shape", - "IsBlockedBatch": "raw read: role BlockingAnnotator serves this shape", "IterAllDependencyRecords": "raw read: streaming has no wire shape", "IterDependenciesWithMetadata": "raw read: streaming has no wire shape", "IterDependentsWithMetadata": "raw read: streaming has no wire shape", diff --git a/internal/httpclient/roles_graph.go b/internal/httpclient/roles_graph.go index 3a0dda6a5..487930a26 100644 --- a/internal/httpclient/roles_graph.go +++ b/internal/httpclient/roles_graph.go @@ -540,6 +540,19 @@ func (a httpBlockingAnnotator) AnnotateBlocking(ctx context.Context, req issueop for _, id := range ids { q.Add("issue_id", id) } + if req.IncludeIsBlocked { + // Refused before the dial against a server that does not advertise + // the parameter: it would answer unknown_parameter, and an answer + // without the flag must never pass for "nothing is blocked". + served, err := a.store.servesCapability(ctx, wire.CapBlockingIsBlocked) + if err != nil { + return issueops.BlockingResult{}, err + } + if !served { + return issueops.BlockingResult{}, a.store.unsupportedCapability("BlockingAnnotator.AnnotateBlocking", wire.CapBlockingIsBlocked) + } + q.Set("is_blocked", "true") + } var body apigen.BlockingAnnotations if err := a.store.dispatch(ctx, wire.Request{ diff --git a/internal/httpclient/served_external_dependency_policy_test.go b/internal/httpclient/served_external_dependency_policy_test.go index 3b11a08bd..896173cd6 100644 --- a/internal/httpclient/served_external_dependency_policy_test.go +++ b/internal/httpclient/served_external_dependency_policy_test.go @@ -5,7 +5,9 @@ package httpclient import ( "errors" "fmt" + "maps" "slices" + "strconv" "testing" "github.com/steveyegge/beads/internal/storage" @@ -284,6 +286,32 @@ func TestServedRolesKeepTheExternalDependencyPolicy(t *testing.T) { t.Errorf("AnnotateBlocking over http: %s blocked by %v", item.ID, item.BlockedBy) } } + // The stored is_blocked column has no external term, so the server calls + // the blocked issue unblocked; the flag and the batch read over it must + // still say blocked, as Ready does. + flagged, err := annotator.AnnotateBlocking(ctx, issueops.BlockingRequest{IDs: []string{blockedID, freeID}, IncludeIsBlocked: true}) + if err != nil { + t.Fatalf("AnnotateBlocking(IncludeIsBlocked) over http: %v", err) + } + if len(flagged.Items) != 2 { + t.Fatalf("AnnotateBlocking(IncludeIsBlocked) over http answered %d items, want 2", len(flagged.Items)) + } + for _, item := range flagged.Items { + got := "absent" + if item.IsBlocked != nil { + got = strconv.FormatBool(*item.IsBlocked) + } + if want := strconv.FormatBool(item.ID == blockedID); got != want { + t.Errorf("AnnotateBlocking(IncludeIsBlocked) over http: %s is_blocked = %s, want %s", item.ID, got, want) + } + } + flags, err := decorated.IsBlockedBatch(ctx, []string{blockedID, freeID}) + if err != nil { + t.Fatalf("IsBlockedBatch over http: %v", err) + } + if want := map[string]bool{blockedID: true, freeID: false}; !maps.Equal(flags, want) { + t.Errorf("IsBlockedBatch over http = %v, want %v", flags, want) + } walker, err := decorated.TreeWalker() if err != nil { diff --git a/internal/httpclient/served_graph_aux_test.go b/internal/httpclient/served_graph_aux_test.go index ce8ac1954..ce4d1506f 100644 --- a/internal/httpclient/served_graph_aux_test.go +++ b/internal/httpclient/served_graph_aux_test.go @@ -177,6 +177,7 @@ func TestServedBlockingAnnotatorContract(t *testing.T) { {"RefusesAnEmptyID", conformance.RunBlockingAnnotatorRefusesAnEmptyID}, {"LeavesTheRequestAlone", conformance.RunBlockingAnnotatorLeavesTheRequestAlone}, {"WritesNothing", conformance.RunBlockingAnnotatorWritesNothing}, + {"ReportsTheTransitiveBlockedFlag", conformance.RunBlockingAnnotatorReportsTheTransitiveBlockedFlag}, } { t.Run(tc.name, func(t *testing.T) { tc.run(t, t.Context(), fixture) }) } diff --git a/internal/httpclient/unsupported_gen.go b/internal/httpclient/unsupported_gen.go index 3c72a4a97..7c900ccb7 100644 --- a/internal/httpclient/unsupported_gen.go +++ b/internal/httpclient/unsupported_gen.go @@ -427,11 +427,6 @@ func (unsupportedDoltStorage) IsBlocked(_ context.Context, _ string) (_ bool, _ return } -func (unsupportedDoltStorage) IsBlockedBatch(_ context.Context, _ []string) (_ map[string]bool, err error) { - err = errUnsupported("IsBlockedBatch") - return -} - func (unsupportedDoltStorage) IterAllDependencyRecords(_ context.Context) (_ storage.Iter[types.Dependency], err error) { err = errUnsupported("IterAllDependencyRecords") return @@ -732,4 +727,4 @@ func (unsupportedDoltStorage) VersionReconciler() (_ issueops.VersionReconciler, return } -// NOTE: partial shell (143 of 201 methods generated; 58 left to this package's hand-written set). +// NOTE: partial shell (142 of 201 methods generated; 59 left to this package's hand-written set). diff --git a/internal/httpclient/wire/handshake.go b/internal/httpclient/wire/handshake.go index bc395596c..c555d2e25 100644 --- a/internal/httpclient/wire/handshake.go +++ b/internal/httpclient/wire/handshake.go @@ -179,6 +179,15 @@ const ( CapListIDs = "issues.list.ids" ) +// CapBlockingIsBlocked is the behavior capability announcing that +// listBlockingAnnotations honors `is_blocked` (issueops.BlockingRequest. +// IncludeIsBlocked), spelled exactly as httpapi's +// CapDependenciesBlockingIsBlocked. The annotator refuses a request asking +// for the flag LOCALLY, with a typed capability error naming this token, when +// the server does not advertise it, so the IsBlockedBatch read never dials a +// server that would answer `unknown_parameter`. +const CapBlockingIsBlocked = "dependencies.blocking.isBlocked" + // CapBatchApplyLarge is the behavior capability announcing that issues.batchApply // accepts a batch larger than the compiled-in floor (100 items), up to the // raised ceiling (1000), spelled exactly as httpapi's constant of the same name @@ -416,7 +425,7 @@ var behaviorCapabilities = []string{ CapSweepWispsPlane, CapSweepLiveDependents, CapSweepLimit, CapBatchApplyDepAddLineage, CapIssuesUpdateAllowTemplate, CapIssuesCreateDefaultPriority, CapCloseAutoCloseMolecule, CapListSearch, - CapListNoAssignee, CapListTitle, CapListIDs, CapIssuesUpdatePersistence, + CapListNoAssignee, CapListTitle, CapListIDs, CapIssuesUpdatePersistence, CapBlockingIsBlocked, } // CapabilityFor reports the capability token gating op, and whether op is on diff --git a/internal/httpclient/wire/vocabulary_test.go b/internal/httpclient/wire/vocabulary_test.go index 7dcbd2134..5059fd660 100644 --- a/internal/httpclient/wire/vocabulary_test.go +++ b/internal/httpclient/wire/vocabulary_test.go @@ -160,6 +160,9 @@ func TestTheProjectIdentityVocabularyMatchesTheServer(t *testing.T) { if CapListIDs != httpapi.CapListIDs { t.Errorf("CapListIDs = %q, server says %q", CapListIDs, httpapi.CapListIDs) } + if CapBlockingIsBlocked != httpapi.CapDependenciesBlockingIsBlocked { + t.Errorf("CapBlockingIsBlocked = %q, server says %q", CapBlockingIsBlocked, httpapi.CapDependenciesBlockingIsBlocked) + } if CapCountScope != httpapi.CapIssuesCountScope { t.Errorf("CapCountScope = %q, server says %q", CapCountScope, httpapi.CapIssuesCountScope) } @@ -214,12 +217,12 @@ func TestTheProjectIdentityVocabularyMatchesTheServer(t *testing.T) { httpapi.CapIssuesSweepWispsPlane, httpapi.CapIssuesSweepLiveDependents, httpapi.CapIssuesSweepLimit, httpapi.CapBatchApplyDepAddLineage, httpapi.CapIssuesUpdateAllowTemplate, httpapi.CapIssuesCreateDefaultPriority, httpapi.CapIssuesCloseAutoCloseMolecule, httpapi.CapIssuesListSearch, - httpapi.CapIssuesListNoAssignee, httpapi.CapIssuesListTitle, httpapi.CapListIDs, httpapi.CapIssuesUpdatePersistence, + httpapi.CapIssuesListNoAssignee, httpapi.CapIssuesListTitle, httpapi.CapListIDs, httpapi.CapIssuesUpdatePersistence, httpapi.CapDependenciesBlockingIsBlocked, }) { t.Errorf("behaviorCapabilities = %v, want the server's project.enforce, issues.batchApplyLarge, issues.list.sort, "+ "issues.count.scope, issues.sweep.wispsPlane, issues.sweep.liveDependents, issues.sweep.limit, "+ "issues.batchApply.depAddLineage, issues.update.allowTemplate, issues.create.defaultPriority, issues.close.autoCloseMolecule, issues.list.search, "+ - "issues.list.noAssignee, issues.list.title, issues.list.ids and issues.update.persistence tokens", behaviorCapabilities) + "issues.list.noAssignee, issues.list.title, issues.list.ids, issues.update.persistence and dependencies.blocking.isBlocked tokens", behaviorCapabilities) } } diff --git a/internal/storage/dolt/blocking_annotator_contract_test.go b/internal/storage/dolt/blocking_annotator_contract_test.go index d63631065..9e137e26f 100644 --- a/internal/storage/dolt/blocking_annotator_contract_test.go +++ b/internal/storage/dolt/blocking_annotator_contract_test.go @@ -71,6 +71,9 @@ func TestBlockingAnnotatorContract(t *testing.T) { t.Run("WritesNothing", func(t *testing.T) { conformance.RunBlockingAnnotatorWritesNothing(t, ctx, fixture) }) + t.Run("ReportsTheTransitiveBlockedFlag", func(t *testing.T) { + conformance.RunBlockingAnnotatorReportsTheTransitiveBlockedFlag(t, ctx, fixture) + }) } func newDoltBlockingAnnotatorFixture(t *testing.T, prefix string) (conformance.BlockingAnnotatorFixture, context.Context, func()) { diff --git a/internal/storage/domain/db/dependency.go b/internal/storage/domain/db/dependency.go index dc4332bb1..18056084b 100644 --- a/internal/storage/domain/db/dependency.go +++ b/internal/storage/domain/db/dependency.go @@ -608,6 +608,17 @@ func (r *dependencySQLRepositoryImpl) GetBlockingInfo(ctx context.Context, issue return info, nil } +// IsBlockedBatch reads the stored transitive is_blocked flag for ids from both +// planes through the shared body (issueops.IsBlockedBatchInTx) every store +// uses, so the unit-of-work answer cannot drift from the store's. +func (r *dependencySQLRepositoryImpl) IsBlockedBatch(ctx context.Context, ids []string) (map[string]bool, error) { + out, err := issueops.IsBlockedBatchInTx(ctx, r.runner, ids) + if err != nil { + return nil, fmt.Errorf("db: DependencySQLRepository.IsBlockedBatch: %w", err) + } + return out, nil +} + func (r *dependencySQLRepositoryImpl) GetBlockingInfoAcrossIssuesAndWisps(ctx context.Context, issueIDs []string) (domain.BlockingInfo, error) { perm, err := r.GetBlockingInfo(ctx, issueIDs, domain.DepListOpts{UseWispsTable: false}) if err != nil { diff --git a/internal/storage/domain/dependency.go b/internal/storage/domain/dependency.go index 0110c1c37..d4208560e 100644 --- a/internal/storage/domain/dependency.go +++ b/internal/storage/domain/dependency.go @@ -151,6 +151,10 @@ type DependencySQLRepository interface { GetBlockingInfo(ctx context.Context, issueIDs []string, opts DepListOpts) (BlockingInfo, error) GetBlockingInfoAcrossIssuesAndWisps(ctx context.Context, issueIDs []string) (BlockingInfo, error) IsBlocked(ctx context.Context, issueID string, opts DepListOpts) (bool, []string, error) + // IsBlockedBatch reads the stored transitive is_blocked flag for ids across + // both planes (issues win a cross-table collision); an id naming no row is + // absent from the map. + IsBlockedBatch(ctx context.Context, ids []string) (map[string]bool, error) // DeleteAllForIDs takes actor for the same reason Delete above does: the // edges it drops are journaled as dep_remove rows, and a cascade removal @@ -203,6 +207,9 @@ type DependencyUseCase interface { CountsByIssueIDs(ctx context.Context, issueIDs []string) (map[string]*types.DependencyCounts, error) GetBlockingInfo(ctx context.Context, issueIDs []string) (BlockingInfo, error) IsBlocked(ctx context.Context, issueID string) (bool, []string, error) + // IsBlockedBatch is the repository read of the same name: the stored + // transitive is_blocked flag per id, both planes, absent = no row. + IsBlockedBatch(ctx context.Context, ids []string) (map[string]bool, error) GetForIssueIDs(ctx context.Context, ids []string) (map[string][]*types.Dependency, error) DetectCycles(ctx context.Context) ([][]*types.Issue, error) // DetectCycleReport is the shape issueops.CycleDetector publishes; see the @@ -617,6 +624,17 @@ func (u *dependencyUseCaseImpl) GetBlockingInfo(ctx context.Context, issueIDs [] return out, nil } +func (u *dependencyUseCaseImpl) IsBlockedBatch(ctx context.Context, ids []string) (map[string]bool, error) { + if len(ids) == 0 { + return map[string]bool{}, nil + } + out, err := u.depRepo.IsBlockedBatch(ctx, ids) + if err != nil { + return nil, fmt.Errorf("IsBlockedBatch: %w", err) + } + return out, nil +} + func (u *dependencyUseCaseImpl) IsBlocked(ctx context.Context, issueID string) (bool, []string, error) { return u.isBlocked(ctx, issueID, false) } diff --git a/internal/storage/embeddeddolt/blocking_annotator_contract_test.go b/internal/storage/embeddeddolt/blocking_annotator_contract_test.go index 604e44436..f5ae720e6 100644 --- a/internal/storage/embeddeddolt/blocking_annotator_contract_test.go +++ b/internal/storage/embeddeddolt/blocking_annotator_contract_test.go @@ -75,6 +75,9 @@ func TestBlockingAnnotatorContract(t *testing.T) { t.Run("WritesNothing", func(t *testing.T) { conformance.RunBlockingAnnotatorWritesNothing(t, ctx, fixture) }) + t.Run("ReportsTheTransitiveBlockedFlag", func(t *testing.T) { + conformance.RunBlockingAnnotatorReportsTheTransitiveBlockedFlag(t, ctx, fixture) + }) } func newEmbeddedBlockingAnnotatorFixture(t *testing.T, te *testEnv, prefix string) conformance.BlockingAnnotatorFixture { diff --git a/internal/storage/externaldeps/decorator.go b/internal/storage/externaldeps/decorator.go index 5c24bb39f..32432b7dc 100644 --- a/internal/storage/externaldeps/decorator.go +++ b/internal/storage/externaldeps/decorator.go @@ -720,13 +720,22 @@ func (s *Store) IsBlocked(ctx context.Context, issueID string) (bool, []string, // IsBlockedBatch preserves the external blocker invariant for batch callers. // The embedded Dolt implementation promotes this method from the wrapped // store, so it must be declared explicitly here rather than relying on -// IsBlocked alone. Like IsBlocked, it refuses over a store that serves its -// roles. +// IsBlocked alone. Over a store that serves its roles the flag comes from the +// server's annotator (dependencies.blocking.isBlocked), and +// remoteExternalBlocked adds the invariant unless the server already applies +// the policy; only IsBlocked still refuses there. func (s *Store) IsBlockedBatch(ctx context.Context, issueIDs []string) (map[string]bool, error) { blocked, err := s.inner.IsBlockedBatch(ctx, issueIDs) if err != nil { return nil, err } + if s.rolesAreRemote() { + // Over a store that serves its roles the raw edge read below is + // refused; the flag came from the server's annotator, and the + // external invariant is added from the edges of these rows only — + // unless the server already applies the policy itself. + return s.remoteExternalBlocked(ctx, issueIDs, blocked) + } deps, err := s.inner.GetDependencyRecordsForIssues(ctx, issueIDs) if err != nil { return nil, err diff --git a/internal/storage/externaldeps/decorator_test.go b/internal/storage/externaldeps/decorator_test.go index c5eaf52c9..6d0b09a71 100644 --- a/internal/storage/externaldeps/decorator_test.go +++ b/internal/storage/externaldeps/decorator_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "maps" "slices" "testing" "time" @@ -157,6 +158,27 @@ func (f *fakeStore) IsBlockedBatch(_ context.Context, ids []string) (map[string] return result, nil } +// BlockingAnnotator serves the decoration a local backend derives for these +// rows: no local blockers, and when asked, isBlocked as each row's stored +// flag. +func (f *fakeStore) BlockingAnnotator() (publicops.BlockingAnnotator, error) { + return localAnnotator{f}, nil +} + +type localAnnotator struct{ f *fakeStore } + +func (a localAnnotator) AnnotateBlocking(ctx context.Context, req publicops.BlockingRequest) (publicops.BlockingResult, error) { + items := make([]publicops.IssueBlocking, 0, len(req.IDs)) + for _, id := range req.IDs { + item := publicops.IssueBlocking{ID: id} + if issue, _ := a.f.GetIssue(ctx, id); issue != nil && req.IncludeIsBlocked { + item.IsBlocked = boolPtr(a.f.isBlocked) + } + items = append(items, item) + } + return publicops.BlockingResult{Items: items}, nil +} + func (f *fakeStore) CloseIssueChecked(ctx context.Context, id, _ string, _ storage.CloseIssueOptions) (storage.CloseIssueResult, error) { issue, err := f.GetIssue(ctx, id) if err != nil { @@ -1008,6 +1030,29 @@ func TestIsBlockedBatchIncludesUnsatisfiedExternalRef(t *testing.T) { } } +// TestBlockingAnnotatorFlagsUnsatisfiedExternalRef: the annotation's +// is_blocked flag keeps IsBlockedBatch's invariant, so a row the stored column +// calls unblocked reads blocked while an external ref still blocks it. +func TestBlockingAnnotatorFlagsUnsatisfiedExternalRef(t *testing.T) { + a, b := issue("be-a"), issue("be-b") + ref := "external:remote:payments" + raw := &fakeStore{ready: []*types.Issue{a, b}, deps: map[string][]*types.Dependency{ + a.ID: {externalDep(a.ID, ref, types.DepBlocks)}, + }} + annotator, err := testStore(raw, &fakeStore{}, true).BlockingAnnotator() + if err != nil { + t.Fatalf("BlockingAnnotator: %v", err) + } + + result, err := annotator.AnnotateBlocking(t.Context(), publicops.BlockingRequest{IDs: []string{a.ID, b.ID}, IncludeIsBlocked: true}) + if err != nil { + t.Fatalf("AnnotateBlocking: %v", err) + } + if got, want := blockedFlags(result), map[string]string{a.ID: "true", b.ID: "false"}; !maps.Equal(got, want) { + t.Fatalf("AnnotateBlocking is_blocked = %v, want %v", got, want) + } +} + func TestCloseIssueCheckedRefusesUnsatisfiedExternalRef(t *testing.T) { a := issue("be-a") ref := "external:remote:payments" @@ -1119,3 +1164,69 @@ func assertExternalCloseBlockers(t *testing.T, err error, issueID, ref string) { t.Errorf("refusal = %q, want %q", err.Error(), wantText) } } + +// TestIsBlockedBatchHonorsShippedExternalRef (bd-yewju3 store half): as +// GetReadyWork does, the flag leaves a row unblocked when its external ref's +// project has shipped it. +func TestIsBlockedBatchHonorsShippedExternalRef(t *testing.T) { + a := issue("be-a") + raw := &fakeStore{ready: []*types.Issue{a}, deps: map[string][]*types.Dependency{ + a.ID: {externalDep(a.ID, "external:remote:payments", types.DepBlocks)}, + }} + foreign := &fakeStore{labels: map[string][]*types.Issue{ + "provides:payments": {{ID: "remote-done", Status: types.StatusClosed}}, + }} + + got, err := testStore(raw, foreign, true).IsBlockedBatch(t.Context(), []string{a.ID}) + if err != nil { + t.Fatalf("IsBlockedBatch: %v", err) + } + if want := map[string]bool{a.ID: false}; !maps.Equal(got, want) { + t.Fatalf("IsBlockedBatch = %v, want %v", got, want) + } +} + +// TestBlockingAnnotatorLeavesShippedExternalRefUnblocked: the store arm's +// served flag reads IsBlocked, so a shipped ref leaves the row unblocked. +func TestBlockingAnnotatorLeavesShippedExternalRefUnblocked(t *testing.T) { + a := issue("be-a") + raw := &fakeStore{ready: []*types.Issue{a}, deps: map[string][]*types.Dependency{ + a.ID: {externalDep(a.ID, "external:remote:payments", types.DepBlocks)}, + }} + foreign := &fakeStore{labels: map[string][]*types.Issue{ + "provides:payments": {{ID: "remote-done", Status: types.StatusClosed}}, + }} + annotator, err := testStore(raw, foreign, true).BlockingAnnotator() + if err != nil { + t.Fatalf("BlockingAnnotator: %v", err) + } + + result, err := annotator.AnnotateBlocking(t.Context(), publicops.BlockingRequest{IDs: []string{a.ID}, IncludeIsBlocked: true}) + if err != nil { + t.Fatalf("AnnotateBlocking: %v", err) + } + if got, want := blockedFlags(result), map[string]string{a.ID: "false"}; !maps.Equal(got, want) { + t.Fatalf("AnnotateBlocking is_blocked = %v, want %v", got, want) + } +} + +// TestBlockingAnnotatorAddsNoFlagUnasked: a request that did not ask for +// is_blocked answers exactly as before, even for an externally blocked row. +func TestBlockingAnnotatorAddsNoFlagUnasked(t *testing.T) { + a := issue("be-a") + raw := &fakeStore{ready: []*types.Issue{a}, deps: map[string][]*types.Dependency{ + a.ID: {externalDep(a.ID, "external:remote:payments", types.DepBlocks)}, + }} + annotator, err := testStore(raw, &fakeStore{}, true).BlockingAnnotator() + if err != nil { + t.Fatalf("BlockingAnnotator: %v", err) + } + + result, err := annotator.AnnotateBlocking(t.Context(), publicops.BlockingRequest{IDs: []string{a.ID}}) + if err != nil { + t.Fatalf("AnnotateBlocking: %v", err) + } + if got, want := blockedFlags(result), map[string]string{a.ID: "absent"}; !maps.Equal(got, want) { + t.Fatalf("AnnotateBlocking is_blocked = %v, want %v", got, want) + } +} diff --git a/internal/storage/externaldeps/remote_roles.go b/internal/storage/externaldeps/remote_roles.go index c99a6402f..5f6c5c598 100644 --- a/internal/storage/externaldeps/remote_roles.go +++ b/internal/storage/externaldeps/remote_roles.go @@ -433,10 +433,35 @@ func (a *remoteBlockingAnnotator) AnnotateBlocking(ctx context.Context, req issu for _, ref := range blockers[result.Items[i].ID] { result.Items[i].BlockedBy = appendUnique(result.Items[i].BlockedBy, ref) } + if req.IncludeIsBlocked && len(blockers[result.Items[i].ID]) > 0 { + result.Items[i].IsBlocked = boolPtr(true) + } } return result, nil } +// remoteExternalBlocked adds the external-dependency invariant to a remote +// store's IsBlockedBatch answer: an id with an unsatisfied external blocker +// is blocked. A server that enforces the policy already folded it in. +func (s *Store) remoteExternalBlocked(ctx context.Context, ids []string, blocked map[string]bool) (map[string]bool, error) { + if enforced, err := s.serverEnforcesPolicy(ctx); err != nil || enforced { + if err != nil { + return nil, err + } + return blocked, nil + } + external, err := s.externalBlockersFor(ctx, ids) + if err != nil { + return nil, err + } + for id, refs := range external { + if len(refs) > 0 { + blocked[id] = true + } + } + return blocked, nil +} + // ── TreeWalker ────────────────────────────────────────────────────── type remoteTreeWalker struct { diff --git a/internal/storage/externaldeps/remote_roles_composition_test.go b/internal/storage/externaldeps/remote_roles_composition_test.go index 9069e323d..308124e9b 100644 --- a/internal/storage/externaldeps/remote_roles_composition_test.go +++ b/internal/storage/externaldeps/remote_roles_composition_test.go @@ -599,8 +599,9 @@ func TestRemoteReadyClaimerWalksAContendedFront(t *testing.T) { } // TestRemoteBlockingAnnotatorMergesExternalBlockers: the served annotation's -// own blockers stay, the external ones join them, and the edges behind them -// are read in chunks the wire accepts. +// own blockers stay, the external ones join them without an is_blocked flag +// the request did not ask for, and the edges behind them are read in chunks +// the wire accepts. func TestRemoteBlockingAnnotatorMergesExternalBlockers(t *testing.T) { issues := make([]*types.Issue, 0, 150) ids := make([]string, 0, 150) @@ -623,6 +624,9 @@ func TestRemoteBlockingAnnotatorMergesExternalBlockers(t *testing.T) { blockedBy := make(map[string][]string, len(result.Items)) for _, item := range result.Items { blockedBy[item.ID] = item.BlockedBy + if item.IsBlocked != nil { + t.Errorf("%s is_blocked = %v unasked, want no flag", item.ID, *item.IsBlocked) + } } if want := []string{"be-local", paymentsRef}; !slices.Equal(blockedBy["be-000"], want) { t.Errorf("be-000 blocked by %v, want %v", blockedBy["be-000"], want) diff --git a/internal/storage/externaldeps/role_accessors.go b/internal/storage/externaldeps/role_accessors.go index 065ac9ed5..fe4dd17e4 100644 --- a/internal/storage/externaldeps/role_accessors.go +++ b/internal/storage/externaldeps/role_accessors.go @@ -132,11 +132,18 @@ func (a *blockingAnnotator) AnnotateBlocking(ctx context.Context, req issueops.B } if blocked { result.Items[i].BlockedBy = blockers + // The flag follows IsBlockedBatch's external invariant: an + // unsatisfied external blocker blocks, whatever the column says. + if req.IncludeIsBlocked { + result.Items[i].IsBlocked = boolPtr(true) + } } } return result, nil } +func boolPtr(v bool) *bool { return &v } + // TreeWalker preserves synthetic external leaves for the normal down-tree // request. Reverse walks do not follow a source's dependencies, and the // combined/up variants retain the backend's existing traversal semantics. diff --git a/internal/storage/externaldeps/uow_decorator.go b/internal/storage/externaldeps/uow_decorator.go index 596ca2cc1..4467e13d8 100644 --- a/internal/storage/externaldeps/uow_decorator.go +++ b/internal/storage/externaldeps/uow_decorator.go @@ -451,6 +451,41 @@ type dependencyUseCase struct { policy *Store } +// IsBlockedBatch keeps the external blocker invariant on the stored column, +// as the store decorator's IsBlockedBatch does: an id with an unsatisfied +// external blocker is blocked whatever the column says. The served is_blocked +// flag is this read on bd serve's unit-of-work arm, so it decides by the +// edges and resolver GetReadyWork excludes by, read through the same unit of +// work. Unlike Ready it resolves only the refs of the ids the column +// answered: a client asks in chunks, and no chunk may reopen every foreign +// project the workspace names. An id naming no row stays absent. +func (u *dependencyUseCase) IsBlockedBatch(ctx context.Context, ids []string) (map[string]bool, error) { + blocked, err := u.DependencyUseCase.IsBlockedBatch(ctx, ids) + if err != nil || len(blocked) == 0 { + return blocked, err + } + records, err := u.GetExternalBlockingDependencyRecords(ctx) + if err != nil { + return nil, fmt.Errorf("external dependencies: %w", err) + } + answered := make(map[string][]*types.Dependency, len(blocked)) + for id := range blocked { + if deps, ok := records[id]; ok { + answered[id] = deps + } + } + state, err := u.policy.blockingStateFromRecords(ctx, answered) + if err != nil { + return nil, fmt.Errorf("external dependencies: %w", err) + } + for id := range blocked { + if len(state.refsByIssue[id]) > 0 { + blocked[id] = true + } + } + return blocked, nil +} + func (u *dependencyUseCase) GetDependencyTree(ctx context.Context, rootID string, opts domain.DepTreeOpts) ([]*types.TreeNode, error) { tree, err := u.DependencyUseCase.GetDependencyTree(ctx, rootID, opts) if err != nil || opts.Direction == domain.DepDirectionIn || len(tree) == 0 { diff --git a/internal/storage/externaldeps/uow_decorator_test.go b/internal/storage/externaldeps/uow_decorator_test.go index 3b6c024fb..5f1392486 100644 --- a/internal/storage/externaldeps/uow_decorator_test.go +++ b/internal/storage/externaldeps/uow_decorator_test.go @@ -3,7 +3,9 @@ package externaldeps import ( "context" "errors" + "maps" "slices" + "strconv" "testing" "time" @@ -12,6 +14,7 @@ import ( "github.com/steveyegge/beads/internal/storage/issueops" "github.com/steveyegge/beads/internal/storage/uow" "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" ) type fakeUOWProvider struct { @@ -30,6 +33,10 @@ type fakeUOW struct { func (u *fakeUOW) IssueUseCase() domain.IssueUseCase { return u.issues } func (u *fakeUOW) DependencyUseCase() domain.DependencyUseCase { return u.deps } +// Close lets a role run over the fake: RunTxRead closes each unit of work it +// opens. +func (u *fakeUOW) Close(context.Context) {} + type fakeIssueUseCase struct { domain.IssueUseCase ready []*types.Issue @@ -117,6 +124,23 @@ type fakeDependencyUseCase struct { external map[string][]*types.Dependency records map[string][]*types.Dependency wispDeps map[string][]*types.Dependency + // isBlocked is the stored is_blocked column, per row; an id it does not + // name has no row. + isBlocked map[string]bool +} + +func (u *fakeDependencyUseCase) GetBlockingInfo(context.Context, []string) (domain.BlockingInfo, error) { + return domain.BlockingInfo{}, nil +} + +func (u *fakeDependencyUseCase) IsBlockedBatch(_ context.Context, ids []string) (map[string]bool, error) { + result := make(map[string]bool, len(ids)) + for _, id := range ids { + if blocked, ok := u.isBlocked[id]; ok { + result[id] = blocked + } + } + return result, nil } func (u *fakeDependencyUseCase) GetExternalBlockingDependencyRecords(context.Context) (map[string][]*types.Dependency, error) { @@ -163,6 +187,149 @@ func TestWrapUOWProviderFiltersProxiedReadyWork(t *testing.T) { } } +// TestWrapUOWProviderBlockedFlagAgreesWithReadyWork: the stored is_blocked +// column has no external term, so a row whose only blocker is an unsatisfied +// external ref reads false there. bd serve answers the served flag on this +// arm, so the flag must call that row blocked, as GetReadyWork does, without +// naming a row the column did not answer: neither an orphan edge's source nor +// an unasked row. +func TestWrapUOWProviderBlockedFlagAgreesWithReadyWork(t *testing.T) { + blocked, free, elsewhere := issue("be-blocked"), issue("be-free"), issue("be-elsewhere") + const ghost = "be-ghost" + inner := &fakeUOW{ + issues: &fakeIssueUseCase{ready: []*types.Issue{blocked, free, elsewhere}}, + deps: &fakeDependencyUseCase{ + external: map[string][]*types.Dependency{ + blocked.ID: {externalDep(blocked.ID, "external:remote:payments", types.DepBlocks)}, + elsewhere.ID: {externalDep(elsewhere.ID, "external:remote:payments", types.DepBlocks)}, + ghost: {externalDep(ghost, "external:remote:payments", types.DepBlocks)}, + }, + isBlocked: map[string]bool{blocked.ID: false, free.ID: false, elsewhere.ID: false}, + }, + } + provider := WrapUOWProvider(&fakeUOWProvider{uw: inner}, func(ProjectName) (string, bool) { + return "", false + }, nil) + uw, err := provider.NewUOW(t.Context()) + if err != nil { + t.Fatalf("NewUOW: %v", err) + } + ready, err := uw.IssueUseCase().GetReadyWork(t.Context(), types.WorkFilter{}) + if err != nil { + t.Fatalf("GetReadyWork: %v", err) + } + if ids := issueIDs(ready.Items); !slices.Equal(ids, []string{free.ID}) { + t.Fatalf("proxied ready IDs = %v, want [%s]", ids, free.ID) + } + + asked := []string{blocked.ID, free.ID, ghost} + flags, err := uw.DependencyUseCase().IsBlockedBatch(t.Context(), asked) + if err != nil { + t.Fatalf("IsBlockedBatch: %v", err) + } + if want := map[string]bool{blocked.ID: true, free.ID: false}; !maps.Equal(flags, want) { + t.Errorf("IsBlockedBatch = %v, want %v", flags, want) + } + + annotator, err := provider.(uow.BlockingAnnotatorSource).BlockingAnnotator() + if err != nil { + t.Fatalf("BlockingAnnotator: %v", err) + } + result, err := annotator.AnnotateBlocking(t.Context(), publicops.BlockingRequest{IDs: asked, IncludeIsBlocked: true}) + if err != nil { + t.Fatalf("AnnotateBlocking: %v", err) + } + if got, want := blockedFlags(result), map[string]string{blocked.ID: "true", free.ID: "false", ghost: "absent"}; !maps.Equal(got, want) { + t.Errorf("AnnotateBlocking is_blocked = %v, want %v", got, want) + } +} + +// TestWrapUOWProviderBlockedFlagResolvesOnlyTheAskedRefs: a client asks for +// the served flag in chunks, so unlike Ready, which must resolve every +// external ref in the workspace, IsBlockedBatch opens only the foreign +// projects its asked rows name, neither an unasked row's nor an orphan +// edge's. +func TestWrapUOWProviderBlockedFlagResolvesOnlyTheAskedRefs(t *testing.T) { + blocked, free, elsewhere := issue("be-blocked"), issue("be-free"), issue("be-elsewhere") + // shipped's external blocker is SATISFIED: the foreign project's labelled + // index carries a closed provider of the capability. Its record is answered + // and resolved, and it must still read unblocked — the half of the + // predicate a "raise every answered external record" body would break. + shipped := issue("be-shipped") + const ghost = "be-ghost" + inner := &fakeUOW{deps: &fakeDependencyUseCase{ + external: map[string][]*types.Dependency{ + blocked.ID: {externalDep(blocked.ID, "external:remote:invoices", types.DepBlocks)}, + shipped.ID: {externalDep(shipped.ID, "external:remote:payments", types.DepBlocks)}, + elsewhere.ID: {externalDep(elsewhere.ID, "external:other:billing", types.DepBlocks)}, + ghost: {externalDep(ghost, "external:orphan:audit", types.DepBlocks)}, + }, + isBlocked: map[string]bool{blocked.ID: false, free.ID: false, elsewhere.ID: false, shipped.ID: false}, + }} + opens := make(map[string]int) + provider := WrapUOWProvider(&fakeUOWProvider{uw: inner}, + func(project ProjectName) (string, bool) { return "/projects/" + string(project), true }, + func(_ context.Context, path string) (storage.DoltStorage, error) { + opens[path]++ + return &fakeStore{labels: map[string][]*types.Issue{ + "provides:payments": {{ID: "remote-done", Status: types.StatusClosed}}, + }}, nil + }, + ) + uw, err := provider.NewUOW(t.Context()) + if err != nil { + t.Fatalf("NewUOW: %v", err) + } + + for _, tc := range []struct { + asked []string + want map[string]bool + wantOpens map[string]int + }{ + {asked: []string{free.ID, ghost}, want: map[string]bool{free.ID: false}, wantOpens: map[string]int{}}, + { + asked: []string{blocked.ID, free.ID}, + want: map[string]bool{blocked.ID: true, free.ID: false}, + wantOpens: map[string]int{"/projects/remote": 1}, + }, + { + asked: []string{shipped.ID, free.ID}, + want: map[string]bool{shipped.ID: false, free.ID: false}, + wantOpens: map[string]int{"/projects/remote": 1}, + }, + { + asked: []string{blocked.ID, shipped.ID}, + want: map[string]bool{blocked.ID: true, shipped.ID: false}, + wantOpens: map[string]int{"/projects/remote": 1}, + }, + } { + clear(opens) + flags, err := uw.DependencyUseCase().IsBlockedBatch(t.Context(), tc.asked) + if err != nil { + t.Fatalf("IsBlockedBatch(%v): %v", tc.asked, err) + } + if !maps.Equal(flags, tc.want) { + t.Errorf("IsBlockedBatch(%v) = %v, want %v", tc.asked, flags, tc.want) + } + if !maps.Equal(opens, tc.wantOpens) { + t.Errorf("IsBlockedBatch(%v) opened %v, want %v", tc.asked, opens, tc.wantOpens) + } + } +} + +// blockedFlags renders each annotated row's is_blocked flag, "absent" where +// the row carries none. +func blockedFlags(result publicops.BlockingResult) map[string]string { + flags := make(map[string]string, len(result.Items)) + for _, item := range result.Items { + flags[item.ID] = "absent" + if item.IsBlocked != nil { + flags[item.ID] = strconv.FormatBool(*item.IsBlocked) + } + } + return flags +} + func TestWrapUOWProviderKeepsUnitOfWorkUnwrappable(t *testing.T) { inner := &fakeUOW{} provider := WrapUOWProvider(&fakeUOWProvider{uw: inner}, nil, nil) diff --git a/internal/storage/issueops/blocking_annotation.go b/internal/storage/issueops/blocking_annotation.go index 49ef3a99c..bec8b48c8 100644 --- a/internal/storage/issueops/blocking_annotation.go +++ b/internal/storage/issueops/blocking_annotation.go @@ -85,5 +85,28 @@ func ExecuteBlockingAnnotation(ctx context.Context, tx DBTX, request publicops.B if err != nil { return publicops.BlockingResult{}, err } - return FinishBlockingAnnotation(anchors, blockedBy, blocks, parent), nil + result := FinishBlockingAnnotation(anchors, blockedBy, blocks, parent) + if request.IncludeIsBlocked { + flags, err := IsBlockedBatchInTx(ctx, tx, anchors) + if err != nil { + return publicops.BlockingResult{}, err + } + ApplyBlockedFlags(&result, flags) + } + return result, nil +} + +// ApplyBlockedFlags stamps BlockingRequest.IncludeIsBlocked's answer onto a +// finished annotation: each item whose id has a row in flags gets that row's +// stored transitive is_blocked flag, and an item with none keeps a nil flag. +// It is shared by every body that answers the role, so "absent from flags" +// means "no row" on all of them. +func ApplyBlockedFlags(result *publicops.BlockingResult, flags map[string]bool) { + for i := range result.Items { + blocked, ok := flags[result.Items[i].ID] + if !ok { + continue + } + result.Items[i].IsBlocked = &blocked + } } diff --git a/internal/storage/uow/blocking_annotator_contract_test.go b/internal/storage/uow/blocking_annotator_contract_test.go index a9df7af0c..dcf7bbafe 100644 --- a/internal/storage/uow/blocking_annotator_contract_test.go +++ b/internal/storage/uow/blocking_annotator_contract_test.go @@ -72,6 +72,9 @@ func TestBlockingAnnotatorContract(t *testing.T) { t.Run("WritesNothing", func(t *testing.T) { conformance.RunBlockingAnnotatorWritesNothing(t, ctx, fixture) }) + t.Run("ReportsTheTransitiveBlockedFlag", func(t *testing.T) { + conformance.RunBlockingAnnotatorReportsTheTransitiveBlockedFlag(t, ctx, fixture) + }) } func newUOWBlockingAnnotatorFixture(t *testing.T, ctx context.Context, prefix string) conformance.BlockingAnnotatorFixture { diff --git a/internal/storage/uow/blockingannotator.go b/internal/storage/uow/blockingannotator.go index 6f587a5e4..25f575980 100644 --- a/internal/storage/uow/blockingannotator.go +++ b/internal/storage/uow/blockingannotator.go @@ -59,6 +59,14 @@ func (a *blockingAnnotator) AnnotateBlocking(ctx context.Context, request public if err != nil { return publicops.BlockingResult{}, err } - return storageissueops.FinishBlockingAnnotation(anchors, info.BlockedBy, info.Blocks, info.Parent), nil + result := storageissueops.FinishBlockingAnnotation(anchors, info.BlockedBy, info.Blocks, info.Parent) + if request.IncludeIsBlocked { + flags, err := uw.DependencyUseCase().IsBlockedBatch(ctx, anchors) + if err != nil { + return publicops.BlockingResult{}, err + } + storageissueops.ApplyBlockedFlags(&result, flags) + } + return result, nil }) } diff --git a/internal/storage/uow/notifying_parity_test.go b/internal/storage/uow/notifying_parity_test.go index 8626bf9d9..f1a9a31fd 100644 --- a/internal/storage/uow/notifying_parity_test.go +++ b/internal/storage/uow/notifying_parity_test.go @@ -203,6 +203,7 @@ func TestRecordingDependencyUseCaseCoversItsSurface(t *testing.T) { "GetIssueDependencyRecords": reads, "GetWispDependencyRecords": reads, "IsBlocked": reads, + "IsBlockedBatch": reads, "IsWispBlocked": reads, "IterWispWithIssueMetadata": reads, "IterWithIssueMetadata": reads, diff --git a/issueops/blockingannotator.go b/issueops/blockingannotator.go index e34645ee1..e9f6e58b7 100644 --- a/issueops/blockingannotator.go +++ b/issueops/blockingannotator.go @@ -28,6 +28,18 @@ type BlockingRequest struct { // for EdgeReadRequest: the answer is keyed by id and a second entry for the // same key carries no second fact. IDs []string + + // IncludeIsBlocked asks for each answered id's stored, TRANSITIVE + // is_blocked flag (IssueBlocking.IsBlocked) alongside the decoration. It + // is opt-in because the flag is a separate read and a listing that only + // prints the decoration has no use for it. + // + // It is the batched readiness projection a cache needs to answer Ready + // with the store's own predicate: the column GetReadyWork filters on, + // which propagates DOWN parent-child edges and reads waits-for and + // conditional-blocks gates, so BlockedBy (two edge types, direct only) + // cannot stand in for it. BlockedFlags is the one entry that asks for it. + IncludeIsBlocked bool } // IssueBlocking is one issue's blocking decoration. @@ -62,6 +74,13 @@ type IssueBlocking struct { // caller that needs every structural edge asks EdgeReader, which answers // with the rows. Parent string `json:"parent,omitempty"` + // IsBlocked is the issue's stored, transitive is_blocked flag — the same + // value storage's IsBlockedBatch answers and GetReadyWork filters on. It + // is set only when the request asked (BlockingRequest.IncludeIsBlocked) + // and the id names a row in either plane; it is nil otherwise, and nil + // never means "not blocked". An unsatisfied external blocker sets it, + // exactly as it does for storage's IsBlockedBatch. + IsBlocked *bool `json:"is_blocked,omitempty"` } // BlockingResult is the per-id answer. @@ -158,3 +177,55 @@ type BlockingAnnotator interface { // there is no Missing flag on it. AnnotateBlocking(ctx context.Context, req BlockingRequest) (BlockingResult, error) } + +// BlockedFlagsChunk is how many ids BlockedFlags names per AnnotateBlocking +// call. It equals the served listBlockingAnnotations bound (100 issue_id +// values; httpapi's maxDependencyAnchors, held equal by a test there), so a +// call through any transport stays inside a question the server accepts. +const BlockedFlagsChunk = 100 + +// BlockedFlags answers the batched transitive is_blocked read (storage's +// IsBlockedBatch: id -> flag, an id naming no row absent) through the +// BlockingAnnotator role with IncludeIsBlocked, BlockedFlagsChunk ids per +// call. It is the one library entry for that read on a role-served backend: +// the http client's IsBlockedBatch is this function over its annotator. +// +// Repeats and blank entries are dropped before asking (a blank id names no +// row, so it would be absent either way). An annotator that answers an item +// without a flag for an id it reports is treated as "no row", matching the +// absent-means-not-found contract; a failure of any chunk fails the call. +func BlockedFlags(ctx context.Context, annotator BlockingAnnotator, ids []string) (map[string]bool, error) { + out := make(map[string]bool, len(ids)) + distinct := make([]string, 0, len(ids)) + seen := make(map[string]struct{}, len(ids)) + for _, id := range ids { + if id == "" { + continue + } + if _, dup := seen[id]; dup { + continue + } + seen[id] = struct{}{} + distinct = append(distinct, id) + } + for start := 0; start < len(distinct); start += BlockedFlagsChunk { + end := min(start+BlockedFlagsChunk, len(distinct)) + result, err := annotator.AnnotateBlocking(ctx, BlockingRequest{ + IDs: distinct[start:end], + IncludeIsBlocked: true, + }) + if err != nil { + return nil, err + } + for _, item := range result.Items { + if item.IsBlocked == nil { + continue + } + if _, asked := seen[item.ID]; !asked { + continue + } + out[item.ID] = *item.IsBlocked + } + } + return out, nil +}