fix(externaldeps): guard explicit claims and batch closes (#6738)
* fix(externaldeps): guard explicit claims and batch closes Preserve external capability policy across lifecycle updates and batch close/claim-next operations, including direct, embedded, and proxied paths. Follow up on upstream PR #4753 and issue #4769. Agent-Signature: codex-unknown-model-unknown-reasoning on behalf of Denis Redozubov * test(externaldeps): include embedded regression in CI discovery * test(serve): preserve external close policy when peeling hooks Replace the raw batch-closer identity assertion with a behavioral policy check, retaining the no-hooks assertion. Document full-workspace claim filtering and batch lookup cost. Agent-Signature: codex-unknown-model-unknown-reasoning on behalf of Denis Redozubov * test(externaldeps): align the mixed-batch pin with #6648's partial-failure exit Maintainer fixup applied while adopting PR #6738. `exerciseExternalMutationPolicy`'s `mixed_batch_and_claim_next` subtest asserted that a partially-refused `bd close` batch keeps the CLI's zero exit status. That was true at this PR's original base, but #6740 (Beads #6648) landed on main in the meantime and made a partial batch close exit 1 with an `N of M issues failed to close` summary. The two changes are independently correct and merge without a textual conflict, so the stale expectation only surfaces as a red `cmd/bd` shard after the rebase. The PR's substance is unchanged: the externally blocked issue is still refused with its blocker named, the eligible item still closes, and `--claim-next` still claims. Only the exit-status expectation moves onto the current contract, and the summary line is now pinned so the interaction between the two features stays covered. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(dolt): check version scope on the transaction owner withWriteTx and withRetryTx delegate transaction creation to commitWriteTx after #6719. Point the existing completeness guard at that owner so it still checks BeginTx and the versioned-history scope together. Agent-Signature: codex-unknown-model-unknown-reasoning on behalf of Denis Redozubov * fix(ci): register external policy files and isolate server cleanup Include all six new Go files in Bazel targets. Run the direct-server fixture before parallel proxied tests because its cleanup purges dropped databases across their shared server; observed initialization failures coincide with that cleanup. Agent-Signature: codex-unknown-model-unknown-reasoning on behalf of Denis Redozubov * fix(externaldeps): scope close-only batch policy and drop the claim --force hint Review-loop fixup for PR #6738 (iteration 1). The review approved with no blocker or major findings; this takes its three minors and its nit, all in code this PR introduces. Each minor lands with a test that a mutation of the covered code turns red. [minor] A refused proxied claim suggested an override that cannot work. The external claim guard ignores --force but shares ErrCloseBlocked with the close policy, so on the proxied route `bd update <id> --claim` against an externally blocked issue printed "(use --force to override)". proxiedUpdateFailure now reports a refused claim as the generic update failure, as the direct route always has. claim_is_atomic asserts the refusal never mentions --force; restoring the unconditional hint fails it on the proxied lane. [minor] A close-only batch demanded policy support for unrelated blockers. Without ClaimNext the batch closer still passed the workspace's whole externally blocked set to BatchCloserWithPolicy, so one external blocker anywhere made a backend lacking PolicyBatchCloserSource (such as one registered through internal/storage/backends) refuse to close unblocked issues. The policy is now scoped to the batch items unless the batch claims next work, which still needs every blocker for FilterClaim. CheckClose looks up exact ids, so no refusal changes. The NewBatchClosePolicy doc now says when the whole set is required. TestBatchCloserScopesPolicyWithoutClaim covers an unrelated blocker, a blocked item, and a next claim against such a backend. [minor] The policy's fallback target read had no pin. TestExecuteCloseBatchWithPolicyDefersToTheTargetRead drives it through sqlmock: a missing target keeps the backend's not-found, and a failing status read reports that failure, never ErrCloseBlocked. Refusing the missing target or swallowing the read error each fails it. [nit] DoltStore and EmbeddedDoltStore BatchCloserWithPolicy return ErrUnsupported on a nil receiver, as NewBatchCloser does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com> Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com> Co-authored-by: Eddie the Engineer <adopt-pr@gascity.local>
This commit is contained in:
parent
765c272151
commit
02f05340f6
26 changed files with 723 additions and 14 deletions
|
|
@ -450,6 +450,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
already refused the combination. Both routes now fail with the same
|
||||
`--format cannot be combined with --watch` usage error.
|
||||
|
||||
- Explicit `bd update --claim` and direct `bd close` now enforce unsatisfied
|
||||
external capability dependencies. Mixed close batches still commit eligible
|
||||
items together, and `--claim-next` skips externally blocked work even when
|
||||
`--force` overrides the close guard.
|
||||
|
||||
- **The smart migrate gate no longer auto-migrates a clone whose data is behind
|
||||
the remote, and `bd dolt pull` now works from that state**
|
||||
([#6575](https://github.com/gastownhall/beads/issues/6575)). The gate's
|
||||
|
|
|
|||
|
|
@ -737,6 +737,8 @@ go_test(
|
|||
"export_proxied_integration_test.go",
|
||||
"export_source_wisp_subset_test.go",
|
||||
"export_test.go",
|
||||
"external_policy_direct_integration_test.go",
|
||||
"external_policy_embedded_test.go",
|
||||
"external_ref_test.go",
|
||||
"federation_embedded_test.go",
|
||||
"feedback_test.go",
|
||||
|
|
|
|||
15
cmd/bd/external_policy_direct_integration_test.go
Normal file
15
cmd/bd/external_policy_direct_integration_test.go
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
//go:build cgo && unix
|
||||
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestProxiedServerExternalPolicyDirectParity(t *testing.T) {
|
||||
requireSharedProxiedServer(t)
|
||||
// This fixture drops its database and purges the shared server's dropped
|
||||
// databases on cleanup. Finish before parallel proxied fixtures start so
|
||||
// that server-wide cleanup cannot race their schema initialization.
|
||||
bd := buildEmbeddedBD(t)
|
||||
p := newDirectHistoryProject(t, bd, "xd")
|
||||
exerciseExternalMutationPolicy(t, crossModeEnv{mode: "direct-server", bd: bd, dir: p.dir, env: p.env})
|
||||
}
|
||||
117
cmd/bd/external_policy_embedded_test.go
Normal file
117
cmd/bd/external_policy_embedded_test.go
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
//go:build cgo
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
// Exercise the CLI wiring: testing Lifecycle.Close or IssueClaimer alone misses
|
||||
// that close uses BatchCloser and update --claim uses Lifecycle.Update.
|
||||
func TestEmbeddedExternalMutationPolicy(t *testing.T) {
|
||||
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
|
||||
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
|
||||
}
|
||||
t.Parallel()
|
||||
bd := buildEmbeddedBD(t)
|
||||
dir, _, _ := bdInit(t, bd, "--prefix", "xp")
|
||||
exerciseExternalMutationPolicy(t, crossModeEnv{mode: "embedded", bd: bd, dir: dir, env: bdEnv(dir)})
|
||||
}
|
||||
|
||||
func TestProxiedServerExternalMutationPolicy(t *testing.T) {
|
||||
requireSharedProxiedServer(t)
|
||||
t.Parallel()
|
||||
bd := buildEmbeddedBD(t)
|
||||
p := newSharedProxiedProject(t, bd, "xp")
|
||||
exerciseExternalMutationPolicy(t, crossModeEnv{mode: "proxied", bd: bd, dir: p.dir, env: bdProxiedEnv(p.dir)})
|
||||
}
|
||||
|
||||
func exerciseExternalMutationPolicy(t *testing.T, local crossModeEnv) {
|
||||
t.Helper()
|
||||
remoteDir, _, _ := bdInit(t, local.bd, "--prefix", "xr")
|
||||
remote := crossModeEnv{mode: "foreign-embedded", bd: local.bd, dir: remoteDir, env: bdEnv(remoteDir)}
|
||||
config := fmt.Sprintf("external_projects:\n remote: %q\n", remoteDir)
|
||||
if err := os.WriteFile(filepath.Join(local.dir, ".beads", "config.local.yaml"), []byte(config), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
provider := remote.create(t, "Payments provider", "--labels", "export:payments")
|
||||
blocked := local.create(t, "Blocked consumer", "--priority", "0")
|
||||
local.mustRun(t, "dep", "add", blocked, "external:remote:payments")
|
||||
|
||||
assertOpen := func(t *testing.T, id string) {
|
||||
t.Helper()
|
||||
got := local.show(t, id)
|
||||
if got.Status != types.StatusOpen || got.Assignee != "" {
|
||||
t.Fatalf("refused mutation changed %s: status=%s assignee=%q", id, got.Status, got.Assignee)
|
||||
}
|
||||
}
|
||||
refuse := func(t *testing.T, args ...string) string {
|
||||
t.Helper()
|
||||
stdout, stderr, code := local.run(t, args...)
|
||||
if code == 0 || !strings.Contains(stderr, "external:remote:payments") {
|
||||
t.Errorf("bd %v: expected external-blocker refusal, got exit %d\n%s\n%s", args, code, stdout, stderr)
|
||||
}
|
||||
return stderr
|
||||
}
|
||||
|
||||
t.Run("claim_is_atomic", func(t *testing.T) {
|
||||
// --force waives only the close policy, so a claim refusal must not
|
||||
// suggest it.
|
||||
if stderr := refuse(t, "update", blocked, "--claim", "--notes", "must not be written"); strings.Contains(stderr, "--force") {
|
||||
t.Errorf("claim refusal suggests --force, which cannot waive it:\n%s", stderr)
|
||||
}
|
||||
assertOpen(t, blocked)
|
||||
if got := local.show(t, blocked); got.Notes != "" {
|
||||
t.Fatalf("refused claim wrote notes: %q", got.Notes)
|
||||
}
|
||||
})
|
||||
t.Run("single_close", func(t *testing.T) {
|
||||
refuse(t, "close", blocked)
|
||||
assertOpen(t, blocked)
|
||||
})
|
||||
t.Run("mixed_batch_and_claim_next", func(t *testing.T) {
|
||||
finished := local.create(t, "Finished work")
|
||||
next := local.create(t, "Eligible next work", "--priority", "1")
|
||||
stdout, stderr, code := local.run(t, "close", blocked, finished, "--claim-next")
|
||||
// Partial success reports each refused item separately on stderr and,
|
||||
// since #6648, exits 1 with a count of the refusals. The eligible item
|
||||
// and --claim-next still land; that is asserted below.
|
||||
if code != 1 || !strings.Contains(stderr, "external:remote:payments") ||
|
||||
!strings.Contains(stderr, "1 of 2 issues failed to close") {
|
||||
t.Fatalf("mixed batch: exit %d\n%s\n%s", code, stdout, stderr)
|
||||
}
|
||||
assertOpen(t, blocked)
|
||||
if got := local.show(t, finished); got.Status != types.StatusClosed {
|
||||
t.Fatalf("eligible batch item was not closed: %s", got.Status)
|
||||
}
|
||||
if got := local.show(t, next); got.Status != types.StatusInProgress {
|
||||
t.Fatalf("claim-next did not choose eligible work: %s", got.Status)
|
||||
}
|
||||
})
|
||||
t.Run("force_only_waives_close", func(t *testing.T) {
|
||||
forced := local.create(t, "Forced close")
|
||||
local.mustRun(t, "dep", "add", forced, "external:remote:payments")
|
||||
local.mustRun(t, "close", forced, "--force", "--claim-next")
|
||||
assertOpen(t, blocked)
|
||||
if got := local.show(t, forced); got.Status != types.StatusClosed {
|
||||
t.Fatalf("forced close did not persist: %s", got.Status)
|
||||
}
|
||||
local.mustRun(t, "close", forced, "--claim-next")
|
||||
assertOpen(t, blocked)
|
||||
})
|
||||
t.Run("shipped_allows_claim_and_close", func(t *testing.T) {
|
||||
remote.mustRun(t, "close", provider)
|
||||
remote.mustRun(t, "ship", "payments")
|
||||
local.mustRun(t, "update", blocked, "--claim")
|
||||
local.mustRun(t, "close", blocked)
|
||||
if got := local.show(t, blocked); got.Status != types.StatusClosed {
|
||||
t.Fatalf("shipped capability did not allow closure: %s", got.Status)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -11,6 +11,7 @@ import (
|
|||
"github.com/steveyegge/beads/internal/hooks"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
"github.com/steveyegge/beads/memoryops"
|
||||
)
|
||||
|
|
@ -113,6 +114,8 @@ func TestServeIssueRolesComeFromBeneathTheHookDecorator(t *testing.T) {
|
|||
}
|
||||
inner := stubs(nil)
|
||||
middle := stubs(inner)
|
||||
policyReadErr := errors.New("external dependency lookup failed")
|
||||
middle.dependencyReadErr = policyReadErr
|
||||
chained := wireStorageDecorators(middle, hooks.NewRunner(t.TempDir()), false)
|
||||
|
||||
if _, ok := chained.(*storage.HookFiringStore); !ok {
|
||||
|
|
@ -232,8 +235,17 @@ func TestServeIssueRolesComeFromBeneathTheHookDecorator(t *testing.T) {
|
|||
if storage.RoleFiresHooks(roles.readyClaimer) {
|
||||
t.Error("bd serve would run this workspace's hooks on every HTTP ready claim")
|
||||
}
|
||||
if storage.RoleFiresHooks(roles.batchCloser) || roles.batchCloser != issueops.BatchCloser(middle.batchCloser) {
|
||||
t.Errorf("batch closer came from %p, want the layer directly beneath the hooks (%p)", roles.batchCloser, middle.batchCloser)
|
||||
if storage.RoleFiresHooks(roles.batchCloser) {
|
||||
t.Error("bd serve would run this workspace's hooks on every HTTP batch close")
|
||||
}
|
||||
// A failed external-policy lookup must still refuse the served close.
|
||||
// Peeling away that policy would reach the raw stub's ErrUnsupported instead.
|
||||
_, err = roles.batchCloser.CloseBatch(context.Background(), issueops.CloseBatchRequest{
|
||||
Actor: "serve-test",
|
||||
Items: []issueops.BatchCloseItem{{IssueID: "bd-blocked"}},
|
||||
})
|
||||
if !errors.Is(err, policyReadErr) {
|
||||
t.Errorf("served batch closer lost external policy: got %v, want %v", err, policyReadErr)
|
||||
}
|
||||
if storage.RoleFiresHooks(roles.batchCreator) || roles.batchCreator != issueops.BatchCreator(middle.batchCreator) {
|
||||
t.Errorf("batch creator came from %p, want the layer directly beneath the hooks (%p)", roles.batchCreator, middle.batchCreator)
|
||||
|
|
@ -419,6 +431,11 @@ var _ serveRoleSource = (*serveRolesStore)(nil)
|
|||
type serveRolesDoltStore struct {
|
||||
*serveRolesStore
|
||||
serveStubRest
|
||||
dependencyReadErr error
|
||||
}
|
||||
|
||||
func (s *serveRolesDoltStore) GetAllDependencyRecords(context.Context) (map[string][]*types.Dependency, error) {
|
||||
return nil, s.dependencyReadErr
|
||||
}
|
||||
|
||||
// serveStubRest carries the remainder of storage.DoltStorage for a stub that
|
||||
|
|
|
|||
|
|
@ -140,7 +140,7 @@ func applyUpdateProxiedOne(ctx context.Context, id string, in *updateInput) (*ty
|
|||
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return nil, nil, err
|
||||
}
|
||||
return nil, proxiedUpdateFailure(id, err), nil
|
||||
return nil, proxiedUpdateFailure(id, in.claim, err), nil
|
||||
}
|
||||
updated := result.Issue
|
||||
if updated == nil {
|
||||
|
|
@ -237,11 +237,15 @@ func proxiedClaimPoolAliases(ctx context.Context) func() []string {
|
|||
// proxiedUpdateFailure sorts a refused update into the per-id verdicts. A guard
|
||||
// refusal sets GuardMismatch so the batch exits 13 rather than 1.
|
||||
//
|
||||
// A refused claim reads as the generic update failure, as it does on the direct
|
||||
// route: the external claim guard ignores --force but shares ErrCloseBlocked
|
||||
// with the close policy, so the hint could name an override that cannot work.
|
||||
//
|
||||
// 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. The id still
|
||||
// fails, loudly and non-zero.
|
||||
func proxiedUpdateFailure(id string, err error) *updateIDFailure {
|
||||
func proxiedUpdateFailure(id string, claim bool, err error) *updateIDFailure {
|
||||
switch {
|
||||
case errors.Is(err, storage.ErrNotFound):
|
||||
fmt.Fprintf(os.Stderr, "Issue %s not found\n", id)
|
||||
|
|
@ -252,7 +256,7 @@ func proxiedUpdateFailure(id string, err error) *updateIDFailure {
|
|||
case errors.Is(err, storage.ErrCloseOpenChildren):
|
||||
fmt.Fprintf(os.Stderr, "%v\n", err)
|
||||
return &updateIDFailure{ID: id, Error: err.Error()}
|
||||
case errors.Is(err, storage.ErrCloseBlocked):
|
||||
case errors.Is(err, storage.ErrCloseBlocked) && !claim:
|
||||
fmt.Fprintf(os.Stderr, "%v (use --force to override)\n", err)
|
||||
return &updateIDFailure{ID: id, Error: fmt.Sprintf("%v (use --force to override)", err)}
|
||||
case uow.IsSerializationError(err):
|
||||
|
|
|
|||
|
|
@ -35,6 +35,11 @@ The decorator:
|
|||
- rejects `parent-child` external edges: hierarchy has no foreign lifecycle
|
||||
semantics, while scheduling edges have an explicit capability predicate;
|
||||
- applies the same guard to checked close and batch blocked-state reads.
|
||||
- guards explicit lifecycle claims (including `bd update --claim`) before any
|
||||
accompanying edits, and carries external blockers into `bd close` batches.
|
||||
Eligible items still close together in one local transaction; refused items
|
||||
retain their positions in the results. `--force` waives close policy, but
|
||||
never makes blocked work eligible for `--claim-next`.
|
||||
- leaves non-blocking external relationships visible without allowing them to
|
||||
gate readiness.
|
||||
|
||||
|
|
@ -54,6 +59,18 @@ existing atomic local `ClaimReadyIssue` operation. A concurrent foreign change
|
|||
may therefore take effect on the next query, matching the historical SQLite
|
||||
behavior without weakening local ready-selection or claim safety.
|
||||
|
||||
Direct batch closes pass an immutable external-blocker snapshot through an
|
||||
internal policy-aware batch accessor. Hooks and telemetry forward that policy
|
||||
to the existing batch executor, which applies both per-item refusals and claim
|
||||
exclusions inside its one transaction. An unsupported decorator fails closed
|
||||
instead of silently discarding the policy. The proxied UOW applies the same
|
||||
guards through its decorated issue use case. Neither path adds a public request
|
||||
field or persists foreign status locally.
|
||||
|
||||
Every non-forced batch close, and every batch close with a next claim, scans all
|
||||
external blocking edges and resolves their foreign capabilities before the
|
||||
local transaction. This shares the lookup-cost concern tracked in GH#6156.
|
||||
|
||||
## Verification
|
||||
|
||||
Regression tests cover unsatisfied and shipped capabilities, fail-closed
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ go_library(
|
|||
"annotation_queries.go",
|
||||
"batch.go",
|
||||
"batch_apply.go",
|
||||
"batch_close_policy.go",
|
||||
"bulk_issues.go",
|
||||
"child_counter_reservation.go",
|
||||
"compaction.go",
|
||||
|
|
@ -76,6 +77,7 @@ go_test(
|
|||
name = "storage_test",
|
||||
srcs = [
|
||||
"batch_apply_test.go",
|
||||
"batch_close_policy_test.go",
|
||||
"contract_leg_registry_test.go",
|
||||
"directory_size_test.go",
|
||||
"hook_batch_applier_test.go",
|
||||
|
|
|
|||
72
internal/storage/batch_close_policy.go
Normal file
72
internal/storage/batch_close_policy.go
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
package storage
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"sort"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// BatchClosePolicy is an immutable snapshot of blockers resolved outside the
|
||||
// local database. Its zero value adds no restrictions. Local close checks and
|
||||
// claim selection still run inside the backend's single batch transaction.
|
||||
type BatchClosePolicy struct {
|
||||
blockers map[string][]string
|
||||
}
|
||||
|
||||
// NewBatchClosePolicy copies the snapshot so later caller edits cannot alter it.
|
||||
// When the batch claims next work, include every externally blocked issue in the
|
||||
// workspace, not just batch items: FilterClaim also needs to exclude blocked
|
||||
// candidates for the next claim.
|
||||
func NewBatchClosePolicy(blockers map[string][]string) BatchClosePolicy {
|
||||
snapshot := make(map[string][]string, len(blockers))
|
||||
for id, refs := range blockers {
|
||||
if len(refs) > 0 {
|
||||
snapshot[id] = slices.Clone(refs)
|
||||
}
|
||||
}
|
||||
return BatchClosePolicy{blockers: snapshot}
|
||||
}
|
||||
|
||||
// CheckClose leaves the existing explicit close-policy override intact.
|
||||
func (p BatchClosePolicy) CheckClose(id string, force bool) error {
|
||||
if refs := p.blockers[id]; !force && len(refs) > 0 {
|
||||
return fmt.Errorf("%w: %s is blocked by %v", ErrCloseBlocked, id, refs)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// FilterClaim excludes blocked work even when Force waived closure policy.
|
||||
func (p BatchClosePolicy) FilterClaim(filter types.WorkFilter) types.WorkFilter {
|
||||
filter.ExcludeIDs = slices.Clone(filter.ExcludeIDs)
|
||||
ids := make([]string, 0, len(p.blockers))
|
||||
for id := range p.blockers {
|
||||
if !slices.Contains(filter.ExcludeIDs, id) {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
}
|
||||
sort.Strings(ids)
|
||||
filter.ExcludeIDs = append(filter.ExcludeIDs, ids...)
|
||||
return filter
|
||||
}
|
||||
|
||||
// PolicyBatchCloserSource carries a policy through storage decorators without
|
||||
// exposing internal filters in the public BatchCloser request or unwrapping
|
||||
// away hooks and telemetry. Backends consume it inside the existing batch.
|
||||
type PolicyBatchCloserSource interface {
|
||||
BatchCloserWithPolicy(BatchClosePolicy) (issueops.BatchCloser, error)
|
||||
}
|
||||
|
||||
// BatchCloserWithPolicy refuses unsupported policy rather than bypassing it.
|
||||
func BatchCloserWithPolicy(store DoltStorage, policy BatchClosePolicy) (issueops.BatchCloser, error) {
|
||||
if len(policy.blockers) == 0 {
|
||||
return store.BatchCloser()
|
||||
}
|
||||
source, ok := store.(PolicyBatchCloserSource)
|
||||
if !ok {
|
||||
return nil, &ErrUnsupported{Op: "BatchCloserWithPolicy", Backend: fmt.Sprintf("%T", store)}
|
||||
}
|
||||
return source.BatchCloserWithPolicy(policy)
|
||||
}
|
||||
46
internal/storage/batch_close_policy_test.go
Normal file
46
internal/storage/batch_close_policy_test.go
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
package storage
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
func TestBatchClosePolicySnapshotAndForce(t *testing.T) {
|
||||
refs := map[string][]string{"blocked": {"external:remote:payments"}, "empty": {}}
|
||||
policy := NewBatchClosePolicy(refs)
|
||||
refs["blocked"][0] = "changed"
|
||||
delete(refs, "blocked")
|
||||
if err := policy.CheckClose("blocked", false); !errors.Is(err, ErrCloseBlocked) || !strings.Contains(err.Error(), "external:remote:payments") {
|
||||
// The snapshot owns its refs; caller mutation cannot change a refusal.
|
||||
t.Fatalf("close refusal = %v", err)
|
||||
}
|
||||
if err := policy.CheckClose("blocked", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := policy.CheckClose("eligible", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
filter := types.WorkFilter{ExcludeIDs: []string{"existing"}}
|
||||
got := policy.FilterClaim(filter)
|
||||
if !reflect.DeepEqual(got.ExcludeIDs, []string{"existing", "blocked"}) {
|
||||
t.Fatalf("claim exclusions = %v", got.ExcludeIDs)
|
||||
}
|
||||
got.ExcludeIDs[0] = "changed"
|
||||
if filter.ExcludeIDs[0] != "existing" {
|
||||
t.Fatal("changed caller filter")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBatchClosePolicyUnsupportedStoreFailsClosed(t *testing.T) {
|
||||
// A decorator that cannot carry the policy must not silently drop it.
|
||||
var store struct{ DoltStorage }
|
||||
_, err := BatchCloserWithPolicy(&store, NewBatchClosePolicy(map[string][]string{"blocked": {"external:p:c"}}))
|
||||
var unsupported *ErrUnsupported
|
||||
if !errors.As(err, &unsupported) {
|
||||
t.Fatalf("error = %v, want unsupported", err)
|
||||
}
|
||||
}
|
||||
|
|
@ -24,7 +24,20 @@ func NewBatchCloser(store *DoltStore) (issueops.BatchCloser, error) {
|
|||
return &batchCloser{store: store}, nil
|
||||
}
|
||||
|
||||
type batchCloser struct{ store *DoltStore }
|
||||
// BatchCloserWithPolicy retains externally resolved blockers inside the batch.
|
||||
func (s *DoltStore) BatchCloserWithPolicy(policy storage.BatchClosePolicy) (issueops.BatchCloser, error) {
|
||||
if s == nil {
|
||||
return nil, &storage.ErrUnsupported{Op: "BatchCloserWithPolicy", Backend: "nil"}
|
||||
}
|
||||
return &batchCloser{store: s, policy: policy}, nil
|
||||
}
|
||||
|
||||
type batchCloser struct {
|
||||
store *DoltStore
|
||||
policy storage.BatchClosePolicy
|
||||
}
|
||||
|
||||
var _ storage.PolicyBatchCloserSource = (*DoltStore)(nil)
|
||||
|
||||
// CloseBatch runs every close, and the optional claim, in ONE transaction with
|
||||
// one commit. The message is composed inside the body because it names what
|
||||
|
|
@ -49,7 +62,7 @@ func (o *batchCloser) CloseBatch(ctx context.Context, request issueops.CloseBatc
|
|||
|
||||
var result issueops.CloseBatchResult
|
||||
err = o.store.runIssueOperationTxWithMessage(ctx, func(tx *sql.Tx) (storageissueops.ChangedTables, string, error) {
|
||||
attempt, tables, err := storageissueops.ExecuteCloseBatch(ctx, tx, request, claimFilter)
|
||||
attempt, tables, err := storageissueops.ExecuteCloseBatchWithPolicy(ctx, tx, request, claimFilter, o.policy)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
|
|
|||
|
|
@ -98,7 +98,7 @@ func TestEveryRawTxVersionScopeIsScopedOrExempt(t *testing.T) {
|
|||
for key, f := range doltFns {
|
||||
// In scope: a function that mints its own transaction AND hands it to a
|
||||
// versioning mutator IN ITS OWN BODY. A function given a tx by
|
||||
// withWriteTx/runDoltTransactionRecording inherits their scoping, and those two
|
||||
// commitWriteTx/runDoltTransactionRecording inherits their scoping, and those two
|
||||
// are covered by TestTxMintingWrappersScopeVersionedHistory below.
|
||||
// Reachability is deliberately DIRECT, for the reasons the journal
|
||||
// guard documents at length.
|
||||
|
|
@ -148,6 +148,7 @@ func TestEveryRawTxVersionScopeIsScopedOrExempt(t *testing.T) {
|
|||
// this second arm exists rather than being folded into the first.
|
||||
var txMintingWrappers = []string{
|
||||
"DoltStore.runDoltTransactionRecording",
|
||||
// withWriteTx and withRetryTx delegate transaction creation and scoping here.
|
||||
"DoltStore.commitWriteTx",
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -26,7 +26,20 @@ func NewBatchCloser(store *EmbeddedDoltStore) (issueops.BatchCloser, error) {
|
|||
return &batchCloser{store: store}, nil
|
||||
}
|
||||
|
||||
type batchCloser struct{ store *EmbeddedDoltStore }
|
||||
// BatchCloserWithPolicy retains externally resolved blockers inside the batch.
|
||||
func (s *EmbeddedDoltStore) BatchCloserWithPolicy(policy storage.BatchClosePolicy) (issueops.BatchCloser, error) {
|
||||
if s == nil {
|
||||
return nil, &storage.ErrUnsupported{Op: "BatchCloserWithPolicy", Backend: "nil"}
|
||||
}
|
||||
return &batchCloser{store: s, policy: policy}, nil
|
||||
}
|
||||
|
||||
type batchCloser struct {
|
||||
store *EmbeddedDoltStore
|
||||
policy storage.BatchClosePolicy
|
||||
}
|
||||
|
||||
var _ storage.PolicyBatchCloserSource = (*EmbeddedDoltStore)(nil)
|
||||
|
||||
// CloseBatch runs every close, and the optional claim, in ONE transaction with
|
||||
// one commit. The message is composed inside the body because it names what
|
||||
|
|
@ -42,7 +55,7 @@ func (o *batchCloser) CloseBatch(ctx context.Context, request issueops.CloseBatc
|
|||
|
||||
var result issueops.CloseBatchResult
|
||||
err = o.store.runIssueOperationTxWithMessage(ctx, func(tx *sql.Tx) (storageissueops.ChangedTables, string, error) {
|
||||
attempt, tables, err := storageissueops.ExecuteCloseBatch(ctx, tx, request, claimFilter)
|
||||
attempt, tables, err := storageissueops.ExecuteCloseBatchWithPolicy(ctx, tx, request, claimFilter, o.policy)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ load("@rules_go//go:def.bzl", "go_library", "go_test")
|
|||
go_library(
|
||||
name = "externaldeps",
|
||||
srcs = [
|
||||
"batch_closer.go",
|
||||
"decorator.go",
|
||||
"resolver.go",
|
||||
"role_accessors.go",
|
||||
|
|
|
|||
53
internal/storage/externaldeps/batch_closer.go
Normal file
53
internal/storage/externaldeps/batch_closer.go
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
package externaldeps
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
storageissueops "github.com/steveyegge/beads/internal/storage/issueops"
|
||||
"github.com/steveyegge/beads/internal/workapi"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// BatchCloser preserves external policy on bd close, including its next claim.
|
||||
func (s *Store) BatchCloser() (issueops.BatchCloser, error) {
|
||||
return &batchCloser{policy: s}, nil
|
||||
}
|
||||
|
||||
type batchCloser struct{ policy *Store }
|
||||
|
||||
func (c *batchCloser) CloseBatch(ctx context.Context, request issueops.CloseBatchRequest) (issueops.CloseBatchResult, error) {
|
||||
if err := storageissueops.ValidateCloseBatchRequest(request); err != nil {
|
||||
return issueops.CloseBatchResult{}, err
|
||||
}
|
||||
if request.ClaimNext != nil {
|
||||
if _, err := workapi.BuildReadyFilter(*request.ClaimNext); err != nil {
|
||||
return issueops.CloseBatchResult{}, err
|
||||
}
|
||||
}
|
||||
var policy storage.BatchClosePolicy
|
||||
if !request.Force || request.ClaimNext != nil {
|
||||
state, err := c.policy.loadBlockingState(ctx)
|
||||
if err != nil {
|
||||
return issueops.CloseBatchResult{}, err
|
||||
}
|
||||
blockers := state.refsByIssue
|
||||
if request.ClaimNext == nil {
|
||||
// Only a claim reads blockers beyond the batch. Scoping the rest
|
||||
// keeps an unrelated blocked issue from demanding policy support
|
||||
// of a backend that lacks it.
|
||||
blockers = make(map[string][]string, len(request.Items))
|
||||
for _, item := range request.Items {
|
||||
blockers[item.IssueID] = state.refsByIssue[item.IssueID]
|
||||
}
|
||||
}
|
||||
policy = storage.NewBatchClosePolicy(blockers)
|
||||
}
|
||||
inner, err := storage.BatchCloserWithPolicy(c.policy.inner, policy)
|
||||
if err != nil {
|
||||
return issueops.CloseBatchResult{}, err
|
||||
}
|
||||
return inner.CloseBatch(ctx, request)
|
||||
}
|
||||
|
||||
var _ issueops.BatchCloser = (*batchCloser)(nil)
|
||||
|
|
@ -64,6 +64,11 @@ func (l *lifecycle) Create(ctx context.Context, request publicops.CreateRequest)
|
|||
}
|
||||
|
||||
func (l *lifecycle) Update(ctx context.Context, request publicops.UpdateRequest) (publicops.UpdateResult, error) {
|
||||
if request.Claim {
|
||||
if err := l.policy.guardExternalClose(ctx, request.IssueID, false); err != nil {
|
||||
return publicops.UpdateResult{}, err
|
||||
}
|
||||
}
|
||||
if request.Patch.Status.Set && string(request.Patch.Status.Value) == string(types.StatusClosed) {
|
||||
if err := l.policy.guardExternalClose(ctx, request.IssueID, request.ForceClosePolicy); err != nil {
|
||||
return publicops.UpdateResult{}, err
|
||||
|
|
|
|||
|
|
@ -26,10 +26,22 @@ type fakeStore struct {
|
|||
blockerIDs []string
|
||||
closed []string
|
||||
lifecycle publicops.Lifecycle
|
||||
batch *fakeBatchCloser
|
||||
}
|
||||
|
||||
func (f *fakeStore) IssueLifecycle() (publicops.Lifecycle, error) { return f.lifecycle, nil }
|
||||
|
||||
// BatchCloser without BatchCloserWithPolicy models a backend that predates
|
||||
// storage.PolicyBatchCloserSource.
|
||||
func (f *fakeStore) BatchCloser() (publicops.BatchCloser, error) { return f.batch, nil }
|
||||
|
||||
type fakeBatchCloser struct{ closed int }
|
||||
|
||||
func (f *fakeBatchCloser) CloseBatch(_ context.Context, request publicops.CloseBatchRequest) (publicops.CloseBatchResult, error) {
|
||||
f.closed++
|
||||
return publicops.CloseBatchResult{Outcomes: make([]publicops.CloseOutcome, len(request.Items))}, nil
|
||||
}
|
||||
|
||||
type fakeLifecycle struct {
|
||||
publicops.Lifecycle
|
||||
closed int
|
||||
|
|
@ -514,6 +526,101 @@ func TestIssueLifecycleRefusesExternalCloseAndDoneUpdate(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestIssueLifecycleClaimExternalPolicy(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
depType types.DependencyType
|
||||
providerStatus types.Status
|
||||
labelErr error
|
||||
wantBlocked bool
|
||||
}{
|
||||
{"unshipped", types.DepBlocks, types.StatusOpen, nil, true},
|
||||
{"shipped", types.DepBlocks, types.StatusClosed, nil, false},
|
||||
{"unreadable", types.DepBlocks, types.StatusClosed, errors.New("foreign read failed"), true},
|
||||
{"nonblocking", types.DepRelated, types.StatusOpen, nil, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
lifecycle := &fakeLifecycle{}
|
||||
raw := &fakeStore{lifecycle: lifecycle, deps: map[string][]*types.Dependency{
|
||||
"be-consumer": {externalDep("be-consumer", "external:remote:payments", tc.depType)},
|
||||
}}
|
||||
foreign := &fakeStore{labelErr: tc.labelErr, labels: map[string][]*types.Issue{
|
||||
"provides:payments": {{ID: "remote-provider", Status: tc.providerStatus}},
|
||||
}}
|
||||
ops, err := testStore(raw, foreign, true).IssueLifecycle()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = ops.Update(t.Context(), publicops.UpdateRequest{IssueID: "be-consumer", Actor: "worker", Claim: true})
|
||||
if errors.Is(err, storage.ErrCloseBlocked) != tc.wantBlocked {
|
||||
t.Fatalf("claim error = %v, want blocked=%v", err, tc.wantBlocked)
|
||||
}
|
||||
if !tc.wantBlocked && err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wantCalls := 1
|
||||
if tc.wantBlocked {
|
||||
wantCalls = 0
|
||||
}
|
||||
if lifecycle.updated != wantCalls {
|
||||
t.Fatalf("inner updates = %d, want %d", lifecycle.updated, wantCalls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A backend without policy support still closes a batch that no external
|
||||
// blocker touches. A blocked item or a next claim, which must exclude every
|
||||
// blocked candidate, still refuses rather than bypassing the policy.
|
||||
func TestBatchCloserScopesPolicyWithoutClaim(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
items []string
|
||||
claimNext bool
|
||||
wantUnsupported bool
|
||||
}{
|
||||
{"unrelated_blocker", []string{"be-free"}, false, false},
|
||||
{"blocked_item", []string{"be-free", "be-consumer"}, false, true},
|
||||
{"claim_next", []string{"be-free"}, true, true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
batch := &fakeBatchCloser{}
|
||||
raw := &fakeStore{batch: batch, deps: map[string][]*types.Dependency{
|
||||
"be-consumer": {externalDep("be-consumer", "external:remote:payments", types.DepBlocks)},
|
||||
}}
|
||||
foreign := &fakeStore{labels: map[string][]*types.Issue{
|
||||
"provides:payments": {{ID: "remote-provider", Status: types.StatusOpen}},
|
||||
}}
|
||||
closer, err := testStore(raw, foreign, true).BatchCloser()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request := publicops.CloseBatchRequest{Actor: "worker"}
|
||||
for _, id := range tc.items {
|
||||
request.Items = append(request.Items, publicops.BatchCloseItem{IssueID: id})
|
||||
}
|
||||
if tc.claimNext {
|
||||
request.ClaimNext = &publicops.ReadyRequest{}
|
||||
}
|
||||
_, err = closer.CloseBatch(t.Context(), request)
|
||||
var unsupported *storage.ErrUnsupported
|
||||
if errors.As(err, &unsupported) != tc.wantUnsupported {
|
||||
t.Fatalf("close batch error = %v, want unsupported=%v", err, tc.wantUnsupported)
|
||||
}
|
||||
if !tc.wantUnsupported && err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wantCalls := 1
|
||||
if tc.wantUnsupported {
|
||||
wantCalls = 0
|
||||
}
|
||||
if batch.closed != wantCalls {
|
||||
t.Fatalf("inner batches = %d, want %d", batch.closed, wantCalls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetBlockedIssuesPaginatesCombinedExternalResults(t *testing.T) {
|
||||
local, external := issue("be-local"), issue("be-external")
|
||||
createdAt := time.Date(2026, time.August, 2, 0, 0, 0, 0, time.UTC)
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package externaldeps
|
|||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
|
||||
|
|
@ -337,21 +338,38 @@ func (u *issueUseCase) GetBlockedIssues(ctx context.Context, filter types.WorkFi
|
|||
}
|
||||
|
||||
func (u *issueUseCase) CloseIssueChecked(ctx context.Context, id string, params domain.CloseIssueParams, actor string, force bool) (domain.CloseIssueResult, error) {
|
||||
if err := u.guardExternalClose(ctx, id, force); err != nil {
|
||||
if err := u.guardExternalCheckedClose(ctx, id, force, u.IssueUseCase.GetIssue); err != nil {
|
||||
return domain.CloseIssueResult{}, err
|
||||
}
|
||||
return u.IssueUseCase.CloseIssueChecked(ctx, id, params, actor, force)
|
||||
}
|
||||
|
||||
func (u *issueUseCase) CloseWispChecked(ctx context.Context, id string, params domain.CloseIssueParams, actor string, force bool) (domain.CloseIssueResult, error) {
|
||||
if err := u.guardExternalClose(ctx, id, force); err != nil {
|
||||
if err := u.guardExternalCheckedClose(ctx, id, force, u.IssueUseCase.GetWisp); err != nil {
|
||||
return domain.CloseIssueResult{}, err
|
||||
}
|
||||
return u.IssueUseCase.CloseWispChecked(ctx, id, params, actor, force)
|
||||
}
|
||||
|
||||
func (u *issueUseCase) guardExternalCheckedClose(ctx context.Context, id string, force bool, get func(context.Context, string) (*types.Issue, error)) error {
|
||||
err := u.guardExternalClose(ctx, id, force)
|
||||
if !errors.Is(err, storage.ErrCloseBlocked) {
|
||||
return err
|
||||
}
|
||||
current, readErr := get(ctx, id)
|
||||
if readErr != nil {
|
||||
return readErr
|
||||
}
|
||||
// The backend owns not-found and idempotent re-close behavior. The
|
||||
// snapshot must not turn an already-settled close into a refusal.
|
||||
if current == nil || current.Status == types.StatusClosed {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (u *issueUseCase) ApplyUpdate(ctx context.Context, id string, spec domain.UpdateSpec, actor string) (*types.Issue, error) {
|
||||
if isClosedUpdate(spec.Fields) {
|
||||
if spec.Claim || isClosedUpdate(spec.Fields) {
|
||||
if err := u.guardExternalClose(ctx, id, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -359,6 +377,20 @@ func (u *issueUseCase) ApplyUpdate(ctx context.Context, id string, spec domain.U
|
|||
return u.IssueUseCase.ApplyUpdate(ctx, id, spec, actor)
|
||||
}
|
||||
|
||||
func (u *issueUseCase) ClaimIssue(ctx context.Context, id, actor string) (domain.ClaimResult, error) {
|
||||
if err := u.guardExternalClose(ctx, id, false); err != nil {
|
||||
return domain.ClaimResult{}, err
|
||||
}
|
||||
return u.IssueUseCase.ClaimIssue(ctx, id, actor)
|
||||
}
|
||||
|
||||
func (u *issueUseCase) ClaimWisp(ctx context.Context, id, actor string) (domain.ClaimResult, error) {
|
||||
if err := u.guardExternalClose(ctx, id, false); err != nil {
|
||||
return domain.ClaimResult{}, err
|
||||
}
|
||||
return u.IssueUseCase.ClaimWisp(ctx, id, actor)
|
||||
}
|
||||
|
||||
func isClosedUpdate(fields map[string]any) bool {
|
||||
switch status := fields["status"].(type) {
|
||||
case string:
|
||||
|
|
|
|||
|
|
@ -268,6 +268,17 @@ func TestWrapUOWProviderGuardsDoneUpdatesAndWispCloses(t *testing.T) {
|
|||
t.Fatalf("NewUOW: %v", err)
|
||||
}
|
||||
issueUC := uw.IssueUseCase()
|
||||
for _, id := range []string{durable.ID, wisp.ID} {
|
||||
if _, err := issueUC.ApplyUpdate(t.Context(), id, domain.UpdateSpec{Claim: true, Fields: map[string]any{"notes": "must not be written"}}, "tester"); !errors.Is(err, storage.ErrCloseBlocked) {
|
||||
t.Fatalf("ApplyUpdate claim %s: %v, want ErrCloseBlocked", id, err)
|
||||
}
|
||||
}
|
||||
if _, err := issueUC.ClaimIssue(t.Context(), durable.ID, "tester"); !errors.Is(err, storage.ErrCloseBlocked) {
|
||||
t.Fatalf("ClaimIssue error = %v, want ErrCloseBlocked", err)
|
||||
}
|
||||
if _, err := issueUC.ClaimWisp(t.Context(), wisp.ID, "tester"); !errors.Is(err, storage.ErrCloseBlocked) {
|
||||
t.Fatalf("ClaimWisp error = %v, want ErrCloseBlocked", err)
|
||||
}
|
||||
if _, err := issueUC.ApplyUpdate(t.Context(), durable.ID, domain.UpdateSpec{Fields: map[string]any{"status": string(types.StatusClosed)}}, "tester"); !errors.Is(err, storage.ErrCloseBlocked) {
|
||||
t.Fatalf("ApplyUpdate error = %v, want ErrCloseBlocked", err)
|
||||
}
|
||||
|
|
@ -284,6 +295,16 @@ func TestWrapUOWProviderGuardsDoneUpdatesAndWispCloses(t *testing.T) {
|
|||
if ids := blockedIssueIDs(blocked); !slices.Equal(ids, []string{durable.ID, wisp.ID}) {
|
||||
t.Fatalf("blocked IDs = %v, want [%s %s]", ids, durable.ID, wisp.ID)
|
||||
}
|
||||
durable.Status, wisp.Status = types.StatusClosed, types.StatusClosed
|
||||
if _, err := issueUC.CloseIssueChecked(t.Context(), durable.ID, domain.CloseIssueParams{}, "tester", false); err != nil {
|
||||
t.Fatalf("durable re-close: %v", err)
|
||||
}
|
||||
if _, err := issueUC.CloseWispChecked(t.Context(), wisp.ID, domain.CloseIssueParams{}, "tester", false); err != nil {
|
||||
t.Fatalf("wisp re-close: %v", err)
|
||||
}
|
||||
if !slices.Equal(issues.closed, []string{durable.ID, wisp.ID}) {
|
||||
t.Fatalf("re-closes did not reach the backend: %v", issues.closed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrapUOWProviderPaginatesCombinedExternalBlockedWork(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -25,6 +25,14 @@ type hookBatchCloser struct {
|
|||
hooks issueOperationHooks
|
||||
}
|
||||
|
||||
func (h *HookFiringStore) BatchCloserWithPolicy(policy BatchClosePolicy) (issueops.BatchCloser, error) {
|
||||
inner, err := BatchCloserWithPolicy(h.inner, policy)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &hookBatchCloser{inner: inner, hooks: h}, nil
|
||||
}
|
||||
|
||||
// CloseBatch fires the close hook once PER LANDED ITEM, in request order, and
|
||||
// fires nothing for an item that refused. Per item rather than once for the
|
||||
// batch because a hook script is written against one issue: collapsing N
|
||||
|
|
|
|||
|
|
@ -30,6 +30,33 @@ type batchCloserStore struct {
|
|||
|
||||
func (s batchCloserStore) BatchCloser() (issueops.BatchCloser, error) { return s.closer, s.err }
|
||||
|
||||
type policyBatchCloserStore struct {
|
||||
batchCloserStore
|
||||
policy BatchClosePolicy
|
||||
}
|
||||
|
||||
func (s *policyBatchCloserStore) BatchCloserWithPolicy(policy BatchClosePolicy) (issueops.BatchCloser, error) {
|
||||
s.policy = policy
|
||||
return s.BatchCloser()
|
||||
}
|
||||
|
||||
func TestHookFiringStoreForwardsBatchClosePolicy(t *testing.T) {
|
||||
inner := &fakeBatchCloser{}
|
||||
raw := &policyBatchCloserStore{batchCloserStore: batchCloserStore{closer: inner}}
|
||||
store := &HookFiringStore{inner: raw}
|
||||
closer, err := BatchCloserWithPolicy(store, NewBatchClosePolicy(map[string][]string{"blocked": {"external:p:c"}}))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !errors.Is(raw.policy.CheckClose("blocked", false), ErrCloseBlocked) {
|
||||
t.Fatal("hook wrapper dropped external policy")
|
||||
}
|
||||
hooked, ok := closer.(*hookBatchCloser)
|
||||
if !ok || hooked.inner != inner || hooked.hooks != store {
|
||||
t.Fatalf("policy accessor lost hook layer: %T", closer)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHookFiringStoreBatchCloserLayersHooksOverInner pins the recursion, for
|
||||
// the reason its Lifecycle sibling pins it: delegating would compile, satisfy
|
||||
// Storage, and silently stop running every on_close script.
|
||||
|
|
|
|||
|
|
@ -115,11 +115,30 @@ func closeOutcomeIsEphemeral(outcome publicops.CloseOutcome) bool {
|
|||
// claim, and so does a batch in which nothing landed — landed meaning an item
|
||||
// that CHANGED, so a batch whose items were all already closed earns no claim.
|
||||
func ExecuteCloseBatch(ctx context.Context, tx *sql.Tx, request publicops.CloseBatchRequest, claimFilter *types.WorkFilter) (publicops.CloseBatchResult, ChangedTables, error) {
|
||||
return ExecuteCloseBatchWithPolicy(ctx, tx, request, claimFilter, storage.BatchClosePolicy{})
|
||||
}
|
||||
|
||||
// ExecuteCloseBatchWithPolicy applies an externally resolved snapshot without
|
||||
// splitting the closes and next claim into separate transactions.
|
||||
func ExecuteCloseBatchWithPolicy(ctx context.Context, tx *sql.Tx, request publicops.CloseBatchRequest, claimFilter *types.WorkFilter, policy storage.BatchClosePolicy) (publicops.CloseBatchResult, ChangedTables, error) {
|
||||
result := publicops.CloseBatchResult{Outcomes: make([]publicops.CloseOutcome, len(request.Items))}
|
||||
tables := ChangedTables{}
|
||||
landed := 0
|
||||
|
||||
for i, item := range request.Items {
|
||||
if err := policy.CheckClose(item.IssueID, request.Force); err != nil {
|
||||
// Preserve idempotent re-closes and not-found precedence. Only
|
||||
// a live target can be refused by the external close policy.
|
||||
closed, _, found, readErr := isClosedInTx(ctx, tx, item.IssueID)
|
||||
if readErr != nil {
|
||||
result.Outcomes[i] = publicops.CloseOutcome{IssueID: item.IssueID, Err: readErr}
|
||||
continue
|
||||
}
|
||||
if found && !closed {
|
||||
result.Outcomes[i] = publicops.CloseOutcome{IssueID: item.IssueID, Err: err}
|
||||
continue
|
||||
}
|
||||
}
|
||||
closed, changedTables, err := ExecuteClose(ctx, tx, publicops.CloseRequest{
|
||||
Actor: request.Actor,
|
||||
IssueID: item.IssueID,
|
||||
|
|
@ -144,7 +163,7 @@ func ExecuteCloseBatch(ctx context.Context, tx *sql.Tx, request publicops.CloseB
|
|||
}
|
||||
|
||||
if claimFilter != nil && landed > 0 {
|
||||
claim, claimTables, err := ExecuteClaimNext(ctx, tx, request.Actor, *claimFilter)
|
||||
claim, claimTables, err := ExecuteClaimNext(ctx, tx, request.Actor, policy.FilterClaim(*claimFilter))
|
||||
if err != nil {
|
||||
return publicops.CloseBatchResult{}, nil, err
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,9 +2,12 @@ package issueops
|
|||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
publicops "github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// TestCountOpenChildrenInTxUsesTargetedOpenEdges keeps the close guard from
|
||||
|
|
@ -43,3 +46,65 @@ func TestCountOpenChildrenInTxUsesTargetedOpenEdges(t *testing.T) {
|
|||
t.Fatalf("unmet targeted-count SQL expectations: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestExecuteCloseBatchWithPolicyDefersToTheTargetRead pins the external
|
||||
// policy's fallback read. A snapshot names only ids, so it refuses a live
|
||||
// target alone: a missing target keeps the backend's not-found, and a status
|
||||
// read that fails reports that failure instead of a policy refusal.
|
||||
func TestExecuteCloseBatchWithPolicyDefersToTheTargetRead(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
const id = "close-policy-target"
|
||||
readErr := errors.New("status read failed")
|
||||
statusQuery := func(table string) string { return `SELECT status FROM ` + table + ` WHERE id = \?` }
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
expect func(sqlmock.Sqlmock)
|
||||
want error
|
||||
}{
|
||||
{
|
||||
// Neither table has the row, for the policy's read or for
|
||||
// ExecuteClose's own, so the backend's not-found stands.
|
||||
name: "missing",
|
||||
expect: func(mock sqlmock.Sqlmock) {
|
||||
for range 2 {
|
||||
for _, table := range []string{"issues", "wisps"} {
|
||||
mock.ExpectQuery(statusQuery(table)).
|
||||
WithArgs(id).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"status"}))
|
||||
}
|
||||
}
|
||||
},
|
||||
want: storage.ErrNotFound,
|
||||
},
|
||||
{
|
||||
name: "unreadable",
|
||||
expect: func(mock sqlmock.Sqlmock) {
|
||||
mock.ExpectQuery(statusQuery("issues")).
|
||||
WithArgs(id).
|
||||
WillReturnError(readErr)
|
||||
},
|
||||
want: readErr,
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, mock, tx := beginMockTx(t)
|
||||
tc.expect(mock)
|
||||
result, _, err := ExecuteCloseBatchWithPolicy(context.Background(), tx, publicops.CloseBatchRequest{
|
||||
Actor: "tester",
|
||||
Items: []publicops.BatchCloseItem{{IssueID: id}},
|
||||
}, nil, storage.NewBatchClosePolicy(map[string][]string{id: {"external:p:c"}}))
|
||||
if err != nil {
|
||||
t.Fatalf("ExecuteCloseBatchWithPolicy: %v", err)
|
||||
}
|
||||
if got := result.Outcomes[0].Err; !errors.Is(got, tc.want) || errors.Is(got, storage.ErrCloseBlocked) {
|
||||
t.Fatalf("outcome error = %v, want %v rather than a policy refusal", got, tc.want)
|
||||
}
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Fatalf("unmet target-read SQL expectations: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -61,6 +61,7 @@ go_library(
|
|||
go_test(
|
||||
name = "telemetry_test",
|
||||
srcs = [
|
||||
"batch_close_policy_test.go",
|
||||
"issue_claimer_test.go",
|
||||
"issue_operations_test.go",
|
||||
"issue_reader_test.go",
|
||||
|
|
|
|||
37
internal/telemetry/batch_close_policy_test.go
Normal file
37
internal/telemetry/batch_close_policy_test.go
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
package telemetry
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
type policyBatchCloserStore struct {
|
||||
storage.DoltStorage
|
||||
closer issueops.BatchCloser
|
||||
policy storage.BatchClosePolicy
|
||||
}
|
||||
|
||||
func (s *policyBatchCloserStore) BatchCloserWithPolicy(policy storage.BatchClosePolicy) (issueops.BatchCloser, error) {
|
||||
s.policy = policy
|
||||
return s.closer, nil
|
||||
}
|
||||
|
||||
func TestInstrumentedStorageForwardsBatchClosePolicy(t *testing.T) {
|
||||
sentinel := &roleAccessorSentinel{}
|
||||
raw := &policyBatchCloserStore{closer: sentinel}
|
||||
store := &InstrumentedStorage{inner: raw}
|
||||
closer, err := storage.BatchCloserWithPolicy(store, storage.NewBatchClosePolicy(map[string][]string{"blocked": {"external:p:c"}}))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !errors.Is(raw.policy.CheckClose("blocked", false), storage.ErrCloseBlocked) {
|
||||
t.Fatal("telemetry wrapper dropped external policy")
|
||||
}
|
||||
instrumented, ok := closer.(*instrumentedBatchCloser)
|
||||
if !ok || instrumented.inner != sentinel || instrumented.storage != store {
|
||||
t.Fatalf("policy accessor lost telemetry layer: %T", closer)
|
||||
}
|
||||
}
|
||||
|
|
@ -3,6 +3,7 @@ package telemetry
|
|||
import (
|
||||
"context"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
|
|
@ -17,6 +18,14 @@ func (s *InstrumentedStorage) BatchCloser() (issueops.BatchCloser, error) {
|
|||
return s.WrapBatchCloser(inner), nil
|
||||
}
|
||||
|
||||
func (s *InstrumentedStorage) BatchCloserWithPolicy(policy storage.BatchClosePolicy) (issueops.BatchCloser, error) {
|
||||
inner, err := storage.BatchCloserWithPolicy(s.Unwrap(), policy)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.WrapBatchCloser(inner), nil
|
||||
}
|
||||
|
||||
// WrapBatchCloser instruments guarded batch closes with this storage layer's
|
||||
// existing telemetry meter and tracer.
|
||||
func (s *InstrumentedStorage) WrapBatchCloser(inner issueops.BatchCloser) issueops.BatchCloser {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue